@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
@@ -1,692 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentDetailView-Cv-vgOj3.js","assets/vendor-react-K0fH_qHe.js","assets/star-D75YKEq-.js","assets/ExperimentalAgentOnboardingModal-Bx6yXVS5.js","assets/ExperimentalAgentOnboardingModal-B-APN_lM.css","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/AgentDetailView-BwJaLqZh.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/TodoView-CTmIfy2M.js","assets/TodoView-Cx9cVhq7.css","assets/SetupWizardModal-D1q548_L.js","assets/DirectoryPicker-xedtR-Rd.js","assets/folder-open-BZuKESeq.js","assets/DirectoryPicker-DzKVmxOf.css","assets/projectDetection-G3XuxD2X.js","assets/SetupWizardModal-CGYGKurR.css","assets/SettingsModal-BLsac7CJ.js","assets/SettingsModal-B1r0yASu.js","assets/SettingsModal-Cis-4Lot.css","assets/users-RS90Aii3.js","assets/SettingsModal-BNSrO1M9.css","assets/dashboard-view-4xAN3yO5.js","assets/createLucideIcon-BazL2hk5.js","assets/dashboard-view-BkTMSZYn.css","assets/dashboard-view-CyWN-d02.js","assets/dashboard-view-DdGlfuu-.css","assets/AgentsView-D6Zi5zfP.js","assets/upload-BYYTgWFj.js","assets/AgentsView-CV3vm7Qk.css","assets/DocumentsView-Bg2oaZks.js","assets/DocumentsView-gv4zG3aT.css","assets/InsightsView-Q1zvtF4F.js","assets/InsightsView-B0J4mhzV.css","assets/ResearchView-CERNf7sJ.js","assets/ResearchView-BEI4ZSGs.css","assets/EvalsView-B3uOCXfr.js","assets/EvalsView-CUNJ1TLc.css","assets/NodesView-RxXg58_Q.js","assets/NodesView-DT4pXowv.css","assets/ChatView-CAHjY9uO.js","assets/ChatView-DwJAd5G1.css","assets/SkillsView-ClLM6u6p.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-xcN_eouf.js","assets/MemoryView-zaXewZzi.css","assets/DevServerView--_WBvIDQ.js","assets/DevServerView-DlZpuAnj.css","assets/StashRecoveryView-ze0pEZ5U.js","assets/StashRecoveryView-B_8WIQEo.css"])))=>i.map(i=>d[i]);
2
- import{r as i,j as t,R as Ml,a as _a,g as Mg,c as Qv}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 Ag=(...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 Xv=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 Zv=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 pm=e=>{const n=Zv(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 jc={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 ey=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},ty=i.createContext({}),ny=()=>i.useContext(ty),sy=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=""}=ny()??{},g=a??h?Number(s??m)*24/Number(n??u):s??m;return i.createElement("svg",{ref:d,...jc,width:n??u??jc.width,height:n??u??jc.height,stroke:e??f,strokeWidth:g,className:Ag("lucide",p,r),...!o&&!ey(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 nt=(e,n)=>{const s=i.forwardRef(({className:a,...r},o)=>i.createElement(sy,{ref:o,iconNode:n,className:Ag(`lucide-${Xv(pm(e))}`,`lucide-${e}`,a),...r}));return s.displayName=pm(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 iy=[["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=nt("activity",iy);/**
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 ay=[["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"}]],ry=nt("archive-restore",ay);/**
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 oy=[["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"}]],So=nt("archive",oy);/**
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 ly=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Co=nt("arrow-down",ly);/**
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 cy=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],Fa=nt("arrow-left",cy);/**
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 dy=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],Eo=nt("arrow-right",dy);/**
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 uy=[["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"}]],Rg=nt("arrow-up-down",uy);/**
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 my=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Ra=nt("arrow-up",my);/**
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 hy=[["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"}]],py=nt("book-open",hy);/**
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 fy=[["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"}]],Vn=nt("bot",fy);/**
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 gy=[["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"}]],zd=nt("box",gy);/**
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 by=[["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"}]],go=nt("brain",by);/**
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 xy=[["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"}]],Pg=nt("calendar",xy);/**
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 vy=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],fm=nt("check-check",vy);/**
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 yy=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],bs=nt("check",yy);/**
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 wy=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],un=nt("chevron-down",wy);/**
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 ky=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],Zl=nt("chevron-left",ky);/**
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 jy=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],zn=nt("chevron-right",jy);/**
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 Ny=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],Ri=nt("chevron-up",Ny);/**
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 Sy=[["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"}]],Ts=nt("circle-alert",Sy);/**
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 Cy=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],Wn=nt("circle-check-big",Cy);/**
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 Ey=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],ec=nt("circle-dot",Ey);/**
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 _y=[["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"}]],Fd=nt("circle-question-mark",_y);/**
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 My=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],Ay=nt("circle-stop",My);/**
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 Ry=[["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"}]],_o=nt("circle-x",Ry);/**
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 Py=[["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"}]],Iy=nt("clipboard-list",Py);/**
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 Ty=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],Wi=nt("clock",Ty);/**
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 $y=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Ig=nt("code",$y);/**
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 Dy=[["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"}]],gm=nt("columns-3",Dy);/**
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 Ly=[["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"}]],ra=nt("copy",Ly);/**
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 Oy=[["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"}]],Tg=nt("cpu",Oy);/**
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 zy=[["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"}]],Fy=nt("download",zy);/**
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 By=[["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"}]],Uy=nt("ellipsis-vertical",By);/**
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 Hy=[["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"}]],Bd=nt("ellipsis",Hy);/**
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 qy=[["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"}]],$g=nt("external-link",qy);/**
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 Vy=[["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"}]],Su=nt("eye-off",Vy);/**
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 Wy=[["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"}]],Er=nt("eye",Wy);/**
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 Ky=[["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"}]],bi=nt("file-code",Ky);/**
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 Gy=[["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"}]],Ud=nt("file-diff",Gy);/**
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 Jy=[["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"}]],Yy=nt("file-minus",Jy);/**
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 Qy=[["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"}]],Dg=nt("file-pen",Qy);/**
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 Xy=[["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"}]],Zy=nt("file-plus",Xy);/**
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 ew=[["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"}]],tw=nt("file-question-mark",ew);/**
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 nw=[["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"}]],oa=nt("file-text",nw);/**
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 sw=[["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"}]],iw=nt("file-type",sw);/**
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 aw=[["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"}]],Lg=nt("file",aw);/**
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 rw=[["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"}]],ow=nt("flag",rw);/**
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 lw=[["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"}]],Hd=nt("folder-git-2",lw);/**
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 cw=[["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"}]],bm=nt("folder-root",cw);/**
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 dw=[["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"}]],ys=nt("folder",dw);/**
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 uw=[["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"}]],Al=nt("funnel",uw);/**
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 mw=[["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"}]],Ps=nt("git-branch",mw);/**
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 hw=[["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"}]],Mo=nt("git-commit-horizontal",hw);/**
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 pw=[["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"}]],Og=nt("git-merge",pw);/**
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 fw=[["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"}]],Js=nt("git-pull-request",fw);/**
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 gw=[["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"}]],tc=nt("globe",gw);/**
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 bw=[["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"}]],nc=nt("grid-3x3",bw);/**
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 xw=[["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"}]],sc=nt("grip-vertical",xw);/**
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 vw=[["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"}]],yw=nt("hard-drive",vw);/**
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 ww=[["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"}]],kw=nt("heart",ww);/**
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 jw=[["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=nt("history",jw);/**
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 Nw=[["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"}]],Ma=nt("inbox",Nw);/**
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 Sw=[["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"}]],zg=nt("key",Sw);/**
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 Cw=[["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"}]],Ew=nt("keyboard",Cw);/**
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 _w=[["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"}]],Ia=nt("layers",_w);/**
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 Mw=[["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"}]],la=nt("layout-grid",Mw);/**
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 Aw=[["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"}]],Pi=nt("lightbulb",Aw);/**
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 Rw=[["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"}]],pr=nt("link",Rw);/**
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 Pw=[["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"}]],Iw=nt("list-checks",Pw);/**
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 Tw=[["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"}]],$w=nt("list-ordered",Tw);/**
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 Dw=[["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"}]],Lw=nt("list-plus",Dw);/**
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 Ow=[["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"}]],ic=nt("list-tree",Ow);/**
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 zw=[["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"}]],qd=nt("list",zw);/**
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 Fw=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Nt=nt("loader-circle",Fw);/**
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 Bw=[["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"}]],ac=nt("lock",Bw);/**
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 Uw=[["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"}]],Ta=nt("mail",Uw);/**
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 Hw=[["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"}]],qw=nt("map",Hw);/**
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 Vw=[["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"}]],rc=nt("maximize-2",Vw);/**
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 Ww=[["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"}]],Kw=nt("message-square-plus",Ww);/**
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 Gw=[["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"}]],qi=nt("message-square",Gw);/**
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 Jw=[["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"}]],Ao=nt("minimize-2",Jw);/**
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 Yw=[["path",{d:"M5 12h14",key:"1ays0h"}]],Qw=nt("minus",Yw);/**
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 Xw=[["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"}]],fr=nt("monitor",Xw);/**
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 Zw=[["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"}]],ek=nt("move",Zw);/**
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 tk=[["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"}]],nk=nt("network",tk);/**
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 sk=[["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"}]],Vd=nt("package",sk);/**
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 ik=[["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"}]],Fg=nt("paperclip",ik);/**
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 ak=[["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"}]],xi=nt("pause",ak);/**
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 rk=[["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"}]],Os=nt("pencil",rk);/**
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 ok=[["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"}]],ss=nt("play",ok);/**
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 lk=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Cn=nt("plus",lk);/**
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 ck=[["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"}]],dk=nt("puzzle",ck);/**
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 uk=[["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"}]],Bg=nt("radio",uk);/**
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 mk=[["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"}]],fs=nt("refresh-cw",mk);/**
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 hk=[["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"}]],xm=nt("rocket",hk);/**
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 pk=[["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"}]],fk=nt("rotate-ccw",pk);/**
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 gk=[["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"}]],bk=nt("rotate-cw",gk);/**
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 xk=[["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"}]],Ug=nt("save",xk);/**
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 vk=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Hi=nt("search",vk);/**
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 yk=[["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"}]],Aa=nt("send",yk);/**
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 wk=[["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"}]],bo=nt("server",wk);/**
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 kk=[["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"}]],co=nt("settings",kk);/**
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 jk=[["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"}]],Nk=nt("shield-alert",jk);/**
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 Sk=[["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"}]],Ck=nt("shield",Sk);/**
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 Ek=[["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"}]],_k=nt("skull",Ek);/**
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 Mk=[["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"}]],xs=nt("sparkles",Mk);/**
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 Ak=[["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"}]],Cu=nt("square-check-big",Ak);/**
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 Rk=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Mi=nt("square",Rk);/**
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 Pk=[["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"}]],js=nt("target",Pk);/**
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 Ik=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],Vi=nt("terminal",Ik);/**
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 Tk=[["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"}]],Rl=nt("text-wrap",Tk);/**
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 $k=[["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"}]],Sn=nt("trash-2",$k);/**
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 Dk=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],Lk=nt("trending-up",Dk);/**
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 Ok=[["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"}]],Ro=nt("triangle-alert",Ok);/**
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 zk=[["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"}]],vm=nt("unlink",zk);/**
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 Fk=[["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"}]],Xa=nt("user",Fk);/**
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 Bk=[["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"}]],Hg=nt("webhook",Bk);/**
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 Uk=[["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"}]],Pl=nt("workflow",Uk);/**
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 Hk=[["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"}]],ym=nt("wrench",Hk);/**
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 qk=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],an=nt("x",qk);/**
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 Vk=[["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"}]],is=nt("zap",Vk),Wd="fusion:version-reload",Kd="fusion:version-update";let Eu=!0;function Nc(e){Eu=e}function Wk(){try{if(sessionStorage.getItem(Kd))return sessionStorage.removeItem(Kd),!0}catch{}return!1}function _u(e){if(sessionStorage.getItem(Wd)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}if(sessionStorage.setItem(Wd,"1"),!Eu){console.info("[versionCheck] auto-reload disabled by setting, skipping reload:",e);return}console.info("[versionCheck] reloading:",e),window.location.reload()}function Kk(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 Gk(e){return Kk(e)?(_u(`chunk load error: ${e?.message??e}`),!0):!1}async function Jk(){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 Yk(){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&&(Eu=!1)}catch{}}const Qk=6e4;let wm=0,Sc=!1;async function Cc(){if(!(Sc||document.visibilityState!=="visible")&&!(Date.now()-wm<Qk)){wm=Date.now(),Sc=!0;try{const e=await Jk();if(e&&e!=="f1ece4b1d-94291eea"){try{sessionStorage.setItem(Kd,"1")}catch{}_u(`build version changed: f1ece4b1d-94291eea -> ${e}`)}}finally{Sc=!1}}}function Xk(){Yk(),window.setTimeout(()=>sessionStorage.removeItem(Wd),5e3),document.addEventListener("visibilitychange",()=>{Cc()}),window.addEventListener("focus",()=>{Cc()}),window.setTimeout(()=>void Cc(),2e3)}class Po 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),!Gk(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(Ro,{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(Po,{level:"page",onError:n,children:e})}function Sa({children:e,onError:n}){return t.jsx(Po,{level:"modal",onError:n,children:e})}function Zk({children:e,onError:n}){return t.jsx(Po,{level:"root",onError:n,children:e})}const ej="modulepreload",tj=function(e){return"/"+e},km={},kn=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=tj(u),u in km)return;km[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":ej,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)})},Mu="fn.authToken",jm="token",nj="fn_token";let cr,Nm=!1,Il=!1;const Gd="fn:auth-token-recovery-required";function sj(){try{const e=window.localStorage.getItem(Mu);return e&&e.length>0?e:void 0}catch{return}}function qg(e){try{window.localStorage.setItem(Mu,e)}catch{}}function ij(){if(!(Nm||typeof window>"u")){Nm=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(jm);if(!n)return;qg(n),e.searchParams.delete(jm);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function gr(){if(cr!==void 0)return cr;const e=ij();if(e)return cr=e,e;const n=sj();if(n)return cr=n,n}function aj(e){cr=e,Il=!1,qg(e)}function rj(){cr=void 0,Il=!1;try{window.localStorage.removeItem(Mu)}catch{}}function Sm(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function oj(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function lj(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!oj(e.protocol))return!1;const s=e.hostname===n.hostname,a=e.port===n.port,r=Sm(e.protocol)===Sm(n.protocol);return s&&a&&r}function cj(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 Ii(e){const n=gr();if(!n||typeof window>"u")return e;const s=cj(e);return!s||!lj(s.parsed)?e:(s.parsed.searchParams.set(nj,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function yi(e){const n=gr();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function dj(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function uj(){typeof window>"u"||Il||(Il=!0,window.dispatchEvent(new CustomEvent(Gd)))}async function mj(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();dj(a)&&uj()}catch{}}function hj(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,gr();const e=window.fetch.bind(window);window.fetch=function(s,a){const r=gr(),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=>(mj(d),d))}}class Vg extends Error{status;details;constructor(n,s,a){super(n),this.name="ApiRequestError",this.status=s,this.details=a}}function pj(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function Ss(e){return`/api${e}`}async function T(e,n={}){const s=Ss(e),a=gr(),r=(()=>{if(a){const f=new Headers(n.headers??{});return f.has("Content-Type")||f.set("Content-Type","application/json"),yi(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")||pj(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 Vg(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function SF(){return T("/health")}function CF(){return T("/updates/check")}function fj(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 $a(e,n){const a=Ss(W(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(a,{headers:yi({"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 Wg(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:v,reviewLevel:N,executionMode:k,priority:E,source:y,nodeId:j,branch:P,baseBranch:F,githubTracking:_}=e;return Do(W("/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:v,reviewLevel:N,executionMode:k,priority:E,source:y,nodeId:j,branch:P,baseBranch:F,githubTracking:_})})}function qs(e,n,s){return T(W(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function gj(e,n,s,a,r,o,l,c,d){return T(W("/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 bj(e,n,s,a){return T(W(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n,...typeof a=="object"&&a?.preserveProgress?{preserveProgress:!0}:{}})})}function xj(e,n,s){const a=new URLSearchParams;s?.removeDependencyReferences&&a.set("removeDependencyReferences","true");const r=a.size>0?`?${a.toString()}`:"";return T(W(`/tasks/${e}${r}`,n),{method:"DELETE"})}function vj(e,n){return T(W(`/tasks/${e}/merge`,n),{method:"POST"})}function yj(e,n){return T(W(`/tasks/${e}/retry`,n),{method:"POST"})}function wj(e,n){return T(W(`/tasks/${e}/reset`,n),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirm:!0})})}function kj(e,n){return T(W(`/tasks/${e}/duplicate`,n),{method:"POST"})}function Kg(e,n){return T(W(`/tasks/${e}/pause`,n),{method:"POST"})}function jj(e,n){return T(W(`/tasks/${e}/unpause`,n),{method:"POST"})}function Nj(e,n){return T(W(`/tasks/${e}/archive`,n),{method:"POST"})}function Sj(e,n){return T(W(`/tasks/${e}/unarchive`,n),{method:"POST"})}function Cj(e){return T(W("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function Ej(e,n){return T(W(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function _j(e,n){return T(W(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function Mj(e){return T(W("/config",e))}function oc(e){return T(W("/settings",e))}function qo(e,n){return T(W("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function Aj(e){return T(W("/update-check",e))}function EF(e){return T(W("/remote/settings",e))}function _F(e,n){return T(W("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function MF(e){return T(W("/remote/status",e))}function AF(e){return T(W("/remote/install-cloudflared",e),{method:"POST"})}function RF(e){return T(W("/remote/tunnel/start",e),{method:"POST"})}function PF(e){return T(W("/remote/tunnel/stop",e),{method:"POST"})}function IF(e){return T(W("/remote/tunnel/kill-external",e),{method:"POST"})}function TF(e){return T(W("/remote/token/persistent/regenerate",e),{method:"POST"})}function $F(e,n){return T(W("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function Gg(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 DF(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:a}=e,r=Gg(null,s,a);return T(W(`/remote/url${r}`,n))}function LF(e="text",n={}){const{projectId:s,tokenType:a="persistent",ttlMs:r}=n,o=Gg(e,a,r);return T(W(`/remote/qr${o}`,s))}function OF(e){return T(W("/memory",e))}function zF(e,n){return T(W("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function FF(e){return T(W("/memory/files",e))}function BF(e,n){const s=`path=${encodeURIComponent(e)}`;return T(W(`/memory/file?${s}`,n))}function UF(e,n,s){return T(W("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function HF(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(W("/memory/compact",a),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function qF(e){return T(W("/memory/dream",e),{method:"POST"})}function VF(e){return T(W("/memory/insights",e))}function WF(e,n){return T(W("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function KF(e){return T(W("/memory/extract",e),{method:"POST"})}function GF(e){return T(W("/memory/audit",e))}function JF(e){return T(W("/memory/stats",e))}function YF(e){return T(W("/memory/backend",e))}function QF(e){return T(W("/memory/install-qmd",e),{method:"POST"})}function XF(e,n){return T(W("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function Ki(){return T("/settings/global")}function Pn(e){return T("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function ZF(e){return T(W("/settings/scopes",e))}function e3(e){return T(W("/settings/pi-extensions",e))}function t3(e,n){return T(W("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function n3(e,n,s){return T(W("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function s3(){return T("/pi-settings")}async function i3(e){return T("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function a3(e){return T("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function r3(e){return T(W("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function lc(e,n,s){const a=new FormData;a.append("file",n);const r=await fetch(Ss(W(`/tasks/${e}/attachments`,s)),{method:"POST",headers:yi(),body:a}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function Rj(e,n,s){return T(W(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function Cm(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=W(`/tasks/${e}/logs${r}`,n),l=await fetch(Ss(o),{headers:yi()});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 Pj(e,n,s,a){return T(W(`/tasks/${e}/comments/${n}`,a),{method:"PATCH",body:JSON.stringify({text:s})})}function Ij(e,n,s){return T(W(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function Tj(e,n){return T(W(`/tasks/${e}/documents`,n))}function $j(e,n,s){return T(W(`/tasks/${e}/documents/${n}/revisions`,s))}async function o3(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(W(r,n))}function l3(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const a=s.toString(),r=`/files/markdown-list${a?`?${a}`:""}`;return T(W(r,e))}function Em(e,n,s,a,r){return T(W(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:a?.author,metadata:a?.metadata})})}function Dj(e,n,s){return T(W(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function Lj(e,n,s){return T(W(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function Oj(e,n,s){return T(W(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function zj(e,n){return T(W(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function Fj(e,n,s){return T(W(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Fs(){return T("/models")}function Bj(){return T("/usage")}function Uj(){return T("/providers/claude-cli/status")}function Hj(){return T("/system/fn-binary/status")}function qj(){return T("/system/fn-binary/install",{method:"POST"})}function Vj(){return T("/providers/droid-cli/status")}function Wj(){return T("/providers/cursor-cli/status")}function Kj(){return T("/providers/llama-cpp/status")}async function c3(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 u3(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return T(`/providers/openclaw/status${n}`)}async function m3(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),T(`/providers/paperclip/status?${n.toString()}`)}async function h3(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 p3(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 f3(e){return T("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function g3(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 b3(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 x3(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 Gj(e){return T("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function Jj(e){return T("/auth/droid-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function Yj(e){return T("/auth/cursor-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function Qj(e){return T("/auth/llama-cpp",{method:"POST",body:JSON.stringify({enabled:e})})}async function Xj(){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 Zj(e){return T("/custom-providers",{method:"POST",body:JSON.stringify(e)})}function y3(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 w3(e){return T(`/custom-providers/${encodeURIComponent(e)}`,{method:"DELETE"})}function eN(e){const n=e.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible";return Zj({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 xo(){return T("/auth/status")}function tN(e){return T("/auth/login",{method:"POST",body:JSON.stringify({provider:e,origin:window.location.origin})})}function nN(e,n){return T("/auth/manual-code",{method:"POST",body:JSON.stringify({provider:e,code:n})})}function sN(e){return T("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function iN(e){return T("/auth/cancel",{method:"POST",body:JSON.stringify({provider:e})})}function aN(e,n){return T("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function rN(e){return T("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function oN(e,n,s,a){return T("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:a})})}function lN(e,n,s,a){return T(W("/github/issues/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function cN(e,n,s){return T("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function dN(e,n,s,a){return T(W("/github/pulls/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function uN(e){return T(W("/git/remotes",e))}function mN(e){return T(W("/git/remotes/detailed",e))}function hN(e,n,s){return T(W("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function pN(e,n){return T(W(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function fN(e,n,s){return T(W(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function gN(e,n,s){return T(W(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function bN(e,n,s){return T(W(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function xN(e,n){return T(W(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function vN(e,n){return(await T(W("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function Vo(e,n,s,a){return T(W("/terminal/sessions",a),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function _m(e,n){return T(W(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function yN(e){return T(W("/terminal/sessions",e))}function fi(e){return T(W("/git/status",e))}function wN(e,n){const s=e?`?limit=${e}`:"";return T(W(`/git/commits${s}`,n))}function Tl(e,n){return T(W(`/git/commits/${e}/diff`,n))}function kN(e){return T(W("/git/commits/ahead",e))}function jN(e,n,s,a){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return T(W(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,a))}function Lr(e){return T(W("/git/branches",e))}function NN(e,n,s){const a=`?limit=${n}`;return T(W(`/git/branches/${encodeURIComponent(e)}/commits${a}`,s))}function SN(e){return T(W("/git/worktrees",e))}function CN(e,n,s){return T(W("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function EN(e,n){return T(W(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function Mm(e,n,s){const a=n?"?force=true":"";return T(W(`/git/branches/${encodeURIComponent(e)}${a}`,s),{method:"DELETE"})}function _N(e,n){return T(W("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function MN(e,n){const s=typeof e=="string"?void 0:e;return T(W("/git/pull",typeof e=="string"?e:n),{method:"POST",body:JSON.stringify({rebase:s?.rebase??!1})})}function AN(e){return T(W("/git/push",e),{method:"POST"})}function Wo(e){return T(W("/git/stashes",e))}function RN(e,n){return T(W("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function PN(e,n,s){return T(W(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function IN(e,n){return T(W(`/git/stashes/${e}`,n),{method:"DELETE"})}function TN(e,n){return T(W(`/git/stashes/${e}/diff`,n))}function $N(e,n,s){const a=new URLSearchParams;return a.set("path",e),a.set("staged",String(n)),T(W(`/git/diff/file?${a.toString()}`,s))}function Za(e){return T(W("/git/changes",e))}function Am(e,n){return T(W("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function DN(e,n){return T(W("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function Rm(e,n){return T(W("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function LN(e,n){return T(W("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function ON(e){return T(W("/workspaces",e))}function zN(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 FN(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),T(`/files/${encodeURIComponent(n)}?${a.toString()}`)}function BN(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 UN(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 HN(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 qN(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 VN(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 WN(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 Jg(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${a.toString()}`}function KN(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${a.toString()}`}function GN(e,n,s){return T(W("/planning/create-draft",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function JN(e,n,s,a,r){return T(W("/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 Pm(e,n,s,a){return T(W("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function YN(e,n,s){return T(W(`/planning/${encodeURIComponent(e)}/back`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function QN(e,n,s){return T(W(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function XN(e,n,s){return T(W(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Yg(e,n,s){return T(W("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function k3(e,n,s,a){return T(W("/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(W("/agents/onboarding/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n})})}function N3(e,n){return T(W("/agents/onboarding/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function ZN(e,n,s){return T(W("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function eS(e,n,s){return T(W("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function tS(e,n,s){return T(W("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const Jd=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(Jd))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function nS(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function _r(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=nS(e,d),g=new EventSource(Ii(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 v=b;m(v)&&w(v)});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(),Jd.delete(f)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return Jd.add(f),f}function Im(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 br(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 sS(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 iS(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((a,r)=>sS(a,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function aS(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 Tm(e){return Array.isArray(e)?e.map(Im):(e.candidates??[]).map(Im)}async function rS(e){try{const n=await T(W("/dev-server/candidates",e));return Tm(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await T(W("/dev-server/detect",e));return Tm(s)}throw n}}function Au(e){return T(W("/dev-server/status",e)).then(br)}async function S3(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(W(`/dev-server/logs/history${a}`,n));return iS(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await Au(n);return aS(o.logs,e)}throw r}}function oS(e,n){const s=e.cwd??e.packagePath??".",a=e.scriptName;return T(W("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:a,scriptId:a,cwd:s,packagePath:e.packagePath})}).then(br)}function lS(e){return T(W("/dev-server/stop",e),{method:"POST"}).then(br)}function cS(e){return T(W("/dev-server/restart",e),{method:"POST"}).then(br)}async function dS(e,n){const s=typeof e=="string"?{url:e}:e;try{const a=await T(W("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return br(a)}catch(a){if(a instanceof Error&&/\/dev-server\/preview-url/.test(a.message)){const r=await T(W("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return br(r)}throw a}}function C3(e){return Ss(W("/dev-server/logs/stream",e))}async function E3(e){try{return(await T(W("/devserver",e))).sessions??[]}catch{try{const n=await Au(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 _3(e,n){try{return await T(W(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await Au(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 M3(e,n){try{return await T(W(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await oS({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 A3(e,n){try{return await T(W(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await lS(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 R3(e,n){try{return await T(W(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await cS(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 P3(e,n,s){try{const a=await T(W(`/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 dS({url:n},s);return{url:a.previewUrl??a.manualUrl??null,source:"manual"}}}async function I3(e){try{return(await T(W("/devserver/detect",e))).candidates??[]}catch{try{return(await rS(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function T3(e,n){return Ss(W(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function Io(e,n,s=25e3){const a=setInterval(()=>{n0(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(a)}}}function uS(e,n){return Ss(W(`/planning/${encodeURIComponent(e)}/stream`,n))}function mS(e,n){return Ss(W(`/agents/onboarding/${encodeURIComponent(e)}/stream`,n))}function $3(e,n,s,a){const r=mS(e,n),o=_r(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 hS(e,n,s,a){const r=uS(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},d=_r(r,{onOpen:()=>{c(),o=Io(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 To(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 pS(e){return T(To("/routines",e))}function fS(e,n){return T(To("/routines",n),{method:"POST",body:JSON.stringify(e)})}function $m(e,n,s){return T(To(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function gS(e,n){await T(To(`/routines/${e}`,n),{method:"DELETE"})}function bS(e,n){return T(To(`/routines/${e}/trigger`,n),{method:"POST"})}function Dm(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 xS(e){const n=W("/activity",e);return T(n,{method:"DELETE"})}function $o(e){return T(W("/workflow-steps",e))}function Lm(e,n){return T(W("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function vS(e,n,s){return T(W(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function yS(e,n){return T(W(`/workflow-steps/${e}`,n),{method:"DELETE"})}function Om(e,n){return T(W(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function wS(e,n){return T(W(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function kS(){return T("/workflow-step-templates")}function jS(){return T("/plugin-workflow-step-templates")}function NS(e,n){return T(W(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function vo(e){return T(W("/scripts",e))}function SS(e,n,s){return T(W("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function CS(e,n){return T(W(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function Qg(e,n,s){return(await T(W("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const Ko={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 Xg(e){if(!(e instanceof Error))return Ko.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?Ko.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?Ko.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:Ko.NETWORK}function ES(e,n){return T(W("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function _S(e,n,s){return T(W(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function MS(e,n){return Ss(W(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function AS(e,n,s,a){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=_r(MS(e,n),{onOpen:()=>{l(),r=Io(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 RS(e,n,s,a,r){return T(W("/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 Zg(e,n,s){return T(W("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function W(e,n){if(!n)return e;const s=e.includes("?")?"&":"?";return`${e}${s}projectId=${encodeURIComponent(n)}`}function PS(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 Do(e,n){const{nodeId:s,localNodeId:a,...r}=n??{},o=PS(e,s,a);return T(o,r)}function Mr(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 Yd(e,n){return T(W(`/agents/${encodeURIComponent(e)}`,n))}function IS(e,n){return T(W("/agents",n),{method:"POST",body:JSON.stringify(e)})}function TS(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function D3(e,n,s){const a=new FormData;a.append("file",n);const r=await fetch(Ss(W(`/agents/${encodeURIComponent(e)}/avatar`,s)),{method:"POST",headers:yi(),body:a}),o=await r.json();if(!r.ok)throw new Error(o.error||"Avatar upload failed");return o}function L3(e,n){return T(W(`/agents/${encodeURIComponent(e)}/avatar`,n),{method:"DELETE"})}function O3(e,n){return T(W(`/agents/${encodeURIComponent(e)}/upgrade-heartbeat-procedure`,n),{method:"POST"})}function z3(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function F3(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function B3(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function U3(e,n){return T(W(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function H3(e,n,s){const a=`path=${encodeURIComponent(n)}`;return T(W(`/agents/${encodeURIComponent(e)}/memory/file?${a}`,s))}function q3(e,n,s,a){return T(W(`/agents/${encodeURIComponent(e)}/memory/file`,a),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function $S(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function DS(e,n){return T(W(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function V3(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 W3(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function K3(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function G3(e,n,s){const a=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return T(W(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:a,triggerDetail:r})})}function J3(e,n){return T(W(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function LS(e){return T(W("/agents/stats",e))}function Y3(e,n){return T(W(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function Q3(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 X3(e,n){return T(W(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function zm(e,n,s){return T(W(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function eb(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 OS(e,n){const s=await T(W(`/tasks/${encodeURIComponent(e)}/review`,n));return eb(s)}async function zS(e,n){const s=await T(W(`/tasks/${encodeURIComponent(e)}/review/refresh`,n),{method:"POST"});return eb(s)}function FS(e,n,s){return T(W(`/tasks/${encodeURIComponent(e)}/review/address`,s),{method:"POST",body:JSON.stringify({selectedItems:n,tab:"review"})})}function Z3(e,n){return T(W(`/agents/${encodeURIComponent(e)}/tasks`,n))}function e6(){return T("/agents/companies")}function t6(e,n){return T(W("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function n6(e,n){return T(W("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function s6(e,n){return T(W(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function i6(e){return T(W("/backups",e))}function a6(e){return T(W("/backups",e),{method:"POST"})}function r6(e,n){const s=W("/settings/export",n),a=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return T(a)}function o6(e,n,s){return T(W("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function BS(e){return Array.isArray(e.nodeMappings)||Array.isArray(e.projectNodeMappings)||Array.isArray(e.pathMappings)}function Fm(){return T("/projects/across-nodes")}function $l(){return T("/nodes")}function l6(){return T("/docker/nodes")}function c6(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 u6(e){return T("/docker-nodes",{method:"POST",body:JSON.stringify(e)})}function US(e){return T("/nodes",{method:"POST",body:JSON.stringify(e)})}function HS(e){return T("/nodes/discover-projects",{method:"POST",body:JSON.stringify(e)})}function qS(e,n){return T(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function VS(e){return T(`/nodes/${encodeURIComponent(e)}/docker-config`)}function WS(e,n){return T(`/nodes/${encodeURIComponent(e)}/docker-config`,{method:"PATCH",body:JSON.stringify(n)})}function KS(e){return T(`/nodes/${encodeURIComponent(e)}/docker-config/diff`)}function Bm(e){return T(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function GS(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()}}function m6(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=gr();l&&o.set("fn_token",l);const c=o.toString(),d=`/browse-directory${c?`?${c}`:""}`;return T(d)}function JS(e){return T("/projects",{method:"POST",body:JSON.stringify(e)})}function tb(e){return T(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function YS(e,n,s){return T(`/projects/${encodeURIComponent(e)}/path-mappings/${encodeURIComponent(n)}`,{method:"PUT",body:JSON.stringify({path:s})})}function Um(e){return T(`/projects/${encodeURIComponent(e)}/health`)}function QS(e){return T(W("/executor/stats",e))}function XS(e){return T(W("/system-stats",e))}function ZS(e){return T(W("/kill-vitest",e),{method:"POST"})}function Hm(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 e1(e){return T(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function t1(e){return T(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function h6(){return T("/global-concurrency")}function p6(e){return T("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function n1(e,n){return T(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function nb(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 s1(e){return T(W("/missions",e))}function i1(e,n){return T(W("/missions",n),{method:"POST",body:JSON.stringify(e)})}function sb(e,n){return T(W(`/missions/${encodeURIComponent(e)}`,n))}function a1(e,n,s){return T(W(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function r1(e,n){return T(W(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function o1(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(W(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function l1(e){return T(W("/missions/health",e))}function c1(e,n,s){return T(W(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function d1(e,n,s){return T(W(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function u1(e,n){return T(W(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function m1(e,n,s){return T(W(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function h1(e,n,s){return T(W(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function p1(e,n){return T(W(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function f1(e,n){return T(W(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function g1(e,n,s){return T(W(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function b1(e,n,s){return T(W(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function x1(e,n){return T(W(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function v1(e,n,s){return T(W(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function y1(e,n){return T(W(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function w1(e,n,s,a,r){return T(W(`/missions/features/${encodeURIComponent(e)}/triage`,a),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s,...r})})}function k1(e,n,s){return T(W(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST",body:JSON.stringify({})})}function Ec(e,n){return T(W(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function j1(e,n,s){return T(W(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function N1(e,n,s){return T(W(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function S1(e,n,s){return T(W(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function C1(e,n,s){return T(W(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function E1(e,n){return T(W(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function _c(e,n){return T(W(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function qm(e,n){return T(W(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function _1(e,n){return T(W(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function Vm(e,n){return T(W(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function M1(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(W(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function A1(e,n){return T(W(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function R1(e,n){return T(W(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function P1(e,n){return T(W(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function I1(e,n){return T(W(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function T1(e,n,s){return T(W(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function $1(e,n,s){return T(W("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function D1(e,n,s,a){return T(W("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function L1(e,n,s){return T(W(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function ib(e,n,s){return T(W("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function O1(e,n,s,a){return T(W("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function z1(e,n,s,a){const r=Ss(W(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=_r(r,{onOpen:()=>{c(),o=Io(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 Lo(e,n,s){return W(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function Oo(e,n,s){return W(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function F1(e,n){return T(Lo(e,"/start",n),{method:"POST"})}function B1(e,n,s,a){return T(Lo(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function U1(e,n,s,a){const r=Ss(Lo(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=_r(r,{onOpen:()=>{c(),o=Io(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 H1(e,n,s){return T(Lo(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function q1(e,n){return T(Lo(e,"/skip",n),{method:"POST"})}function V1(e,n){return T(Oo(e,"/start",n),{method:"POST"})}function W1(e,n,s,a){return T(Oo(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function K1(e,n,s,a){const r=Ss(Oo(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=_r(r,{onOpen:()=>{c(),o=Io(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 G1(e,n,s){return T(Oo(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function J1(e,n){return T(Oo(e,"/skip",n),{method:"POST"})}async function Y1(e,n){try{return await T(W(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function f6(e){return T(W("/todos",e))}function g6(e,n){const s={title:e};return T(W("/todos",n),{method:"POST",body:JSON.stringify(s)})}function b6(e,n,s){const a={title:n};return T(W(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function x6(e,n){return T(W(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function v6(e,n,s){const a={text:n};return T(W(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(a)})}function y6(e,n,s){const a=n;return T(W(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function w6(e,n){return T(W(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function k6(e,n,s){return T(W(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function xr(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function Ru(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(Ss(`/ai-sessions${a?`?${a}`:""}`),{headers:yi()});return r.ok?(await r.json()).sessions??[]:[]}async function Q1(e){return T(`/ai-sessions/${encodeURIComponent(e)}/archive`,{method:"POST"})}async function X1(e){return T(`/ai-sessions/${encodeURIComponent(e)}/unarchive`,{method:"POST"})}async function Ai(e){const n=await fetch(Ss(`/ai-sessions/${encodeURIComponent(e)}`),{headers:yi()});return n.ok?n.json():null}async function Z1(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 e0(e,n){return T(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function t0(e,n){return T(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function ab(e){await fetch(Ss(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:yi()})}function n0(e,n){return T(W(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function s0(e,n,s){return T(W(`/ai-sessions/${encodeURIComponent(e)}/draft`,s),{method:"PATCH",body:JSON.stringify(n)})}function i0(e,n){return T(W(`/planning/${encodeURIComponent(e)}/summarize-draft-title`,n),{method:"POST"})}function a0(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 r0(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 rb(e){return T(W("/messages/unread-count",e))}function o0(e,n){return T(W("/messages",n),{method:"POST",body:JSON.stringify(e)})}function l0(e,n){return T(W(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function c0(e){return T(W("/messages/read-all",e),{method:"POST"})}function d0(e,n){return T(W(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function u0(e,n,s){const a=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return T(W(a,s))}function m0(e,n){return T(W(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function Go(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 Wm(e,n){return T(W(`/approvals/${encodeURIComponent(e)}`,n))}function h0(e,n,s){return T(W(`/approvals/${encodeURIComponent(e)}/decision`,s),{method:"POST",body:JSON.stringify(n)})}function j6(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 N6(e,n){return T(W(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function S6(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 C6(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 E6(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function _6(e,n){return T(W(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function M6(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function A6(e,n){return T(W(`/agents/${encodeURIComponent(e)}/budget`,n))}function R6(e,n){return T(W(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function P6(e){return T(W("/plugins",e))}async function I6(e,n){return T(W("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function T6(e,n){return T(W(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function $6(e,n){return T(W(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function D6(e,n){return T(W(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function L6(e,n){return T(W(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function O6(e,n,s){return T(W(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function z6(e,n){return T(W(`/plugins/${encodeURIComponent(e)}/setup-status`,n))}async function F6(e,n){return T(W(`/plugins/${encodeURIComponent(e)}/setup/install`,n),{method:"POST"})}async function B6(e,n){return T(W(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function U6(e,n,s){return T(W(`/plugins/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function H6(e,n){return T(W(`/plugins/${encodeURIComponent(e)}/rescan`,n),{method:"POST"})}async function p0(e){return T(W("/plugins/ui-slots",e))}async function f0(e){return T(W("/plugins/dashboard-views",e))}async function q6(e){return T(W("/plugins/runtimes",e))}async function g0(e){return(await T(W("/skills/discovered",e))).skills}async function V6(e,n,s){return T(W("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function W6(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(W(`/skills/catalog${r}`,s))}async function K6(e,n){return(await T(W(`/skills/${encodeURIComponent(e)}/content`,n))).content}function Km(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const a=s.toString();return T(`/chat/sessions${a?`?${a}`:""}`)}async function b0(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 x0(e,n){return T(W("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function v0(e,n){return T(W(`/chat/sessions/${encodeURIComponent(e)}`,n))}function G6(e,n,s){return T(W(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function J6(e,n){return T(W(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Or(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(W(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function Y6(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 Q6(e,n){const s={...e,...n?{projectId:n}:{}};return T(W("/chat/rooms",n),{method:"POST",body:JSON.stringify(s)})}function X6(e,n){return T(W(`/chat/rooms/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Z6(e,n){return T(W(`/chat/rooms/${encodeURIComponent(e)}/members`,n))}function e5(e,n,s){const a=new URLSearchParams;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(W(`/chat/rooms/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function t5(e,n,s){return T(W(`/chat/rooms/${encodeURIComponent(e)}/messages`,s),{method:"POST",body:JSON.stringify(n)})}function y0(e,n){return T(W(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function w0(e,n,s,a,r,o){const l=Ss(W(`/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 v=JSON.parse(b);s.onDone?.({messageId:typeof v.messageId=="string"?v.messageId:"",...v.message&&typeof v.message=="object"?{message:v.message}:{}})}catch{s.onDone?.({messageId:""})}break;case"error":u=!0;try{const v=JSON.parse(b);s.onError?.(v.message||v)}catch{s.onError?.(b||"Stream error")}break}};return(async()=>{try{const w=Array.isArray(a)&&a.length>0,b=w?(()=>{const _=new FormData;return _.append("content",n),a.forEach(R=>_.append("attachments",R)),_})():JSON.stringify({content:n}),v=await fetch(l,{method:"POST",headers:w?yi():yi({"Content-Type":"application/json"}),body:b,signal:c.signal});if(!v.ok){const _=await v.text();let R=`Request failed: ${v.status}`;try{R=JSON.parse(_).error||R}catch{}s.onError?.(R);return}if(!v.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 N=v.body.getReader(),k=new TextDecoder;let E="",y="",j=[];const P=(_,R=!1)=>{E+=_;const L=E.split(`
643
- `);E=L.pop()||"",R&&E.length>0&&(L.push(E),E="");for(const U of L){const C=U.endsWith("\r")?U.slice(0,-1):U;if(C.startsWith("event:"))y=C.slice(6).trim();else if(C.startsWith("data:")){const $=C.slice(5);j.push($.startsWith(" ")?$.slice(1):$)}else if(C===""){const $=j.join(`
644
- `);x(y,$),y="",j=[]}}if(R&&y&&j.length>0){const U=j.join(`
645
- `);x(y,U),y="",j=[]}};for(;;){const{done:_,value:R}=await N.read();if(_){P(k.decode(),!0);break}P(k.decode(R,{stream:!0}))}const F=E.length>0||y.length>0||j.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 k0(e,n,s,a){const r=Ss(W(`/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;try{const h=JSON.parse(m);n.onError?.(h.message||h)}catch{n.onError?.(m||"Stream error")}break}};return(async()=>{try{const u=new Headers(yi());a?.lastEventId;const m=await fetch(r,{method:"GET",headers:u,signal:o.signal});if(!m.ok){const v=await m.text();let N=`Request failed: ${m.status}`;try{N=JSON.parse(v).error||N}catch{}n.onError?.(N);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=(v,N=!1)=>{p+=v;const k=p.split(`
646
- `);p=k.pop()||"",N&&p.length>0&&(k.push(p),p="");for(const E of k){const y=E.endsWith("\r")?E.slice(0,-1):E;if(y.startsWith("event:"))g=y.slice(6).trim();else if(y.startsWith("data:")){const j=y.slice(5);x.push(j.startsWith(" ")?j.slice(1):j)}else if(y===""){const j=x.join(`
647
- `);d(g,j),g="",x=[]}}if(N&&g&&x.length>0){const E=x.join(`
648
- `);d(g,E),g="",x=[]}};for(;;){const{done:v,value:N}=await h.read();if(v){w(f.decode(),!0);break}w(f.decode(N,{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 n5(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(W(`/insights${a}`,n))}function s5(e,n){return T(W(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function i5(e,n){return T(W(`/insights/${encodeURIComponent(e)}/archive`,n),{method:"POST"})}function a5(e,n){return T(W(`/insights/${encodeURIComponent(e)}/unarchive`,n),{method:"POST"})}function r5(e="manual",n,s,a,r){const o={trigger:e,inputMetadata:n};return a&&(o.modelProvider=a),r&&(o.modelId=r),T(W("/insights/run",s),{method:"POST",body:JSON.stringify(o)})}function o5(e){return T(W("/insights/runs",e))}function l5(e,n){return T(W(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function c5(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(W(`/evals${a}`,n))}function d5(e,n){return T(W(`/evals/${encodeURIComponent(e)}`,n))}function u5(e){return T(W("/evals/runs",e))}function m5(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(W(`/research/runs${a}`,n))}function h5(e,n){return T(W("/research/runs",n),{method:"POST",body:JSON.stringify(e)})}function p5(e,n){return T(W(`/research/runs/${encodeURIComponent(e)}`,n))}function ob(e){if(e instanceof Vg){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 f5(e,n){try{return await T(W(`/research/runs/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}catch(s){ob(s)}}async function g5(e,n){try{return await T(W(`/research/runs/${encodeURIComponent(e)}/retry`,n),{method:"POST"})}catch(s){ob(s)}}function b5(e,n,s){return T(W(`/research/runs/${encodeURIComponent(e)}/export?format=${encodeURIComponent(n)}`,s))}function x5(e,n,s){const a=n.findingId??"finding-1";return T(W(`/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 v5(e,n,s){const a=n.findingId??"finding-1";return T(W(`/research/runs/${encodeURIComponent(e)}/findings/${encodeURIComponent(a)}/tasks/${encodeURIComponent(n.taskId)}/enrich`,s),{method:"POST",body:JSON.stringify({attachExport:n.attachExport})})}async function j0(e){return Do("/health",{nodeId:e})}async function N0(e){return Do("/projects",{nodeId:e})}async function S0(e,n,s){const a=new URLSearchParams({projectId:n});return s&&s.trim()&&a.set("q",s.trim()),Do(`/tasks?${a.toString()}`,{nodeId:e})}async function C0(e,n){return Do(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function y5(e){return T(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function w5(e){return T(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function k5(e){return T(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function j5(e){return T(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}async function E0(e,n){return Promise.all(n.map(({projectId:s,path:a})=>YS(s,e,a)))}function _0(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 M0({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}=_0(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 A0(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Da({status:e,showLabel:n=!1,className:s,compact:a=!1}){const r=A0(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 Gm=new Map,R0=6e4;function lb(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=Gm.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 p0(e);if(h||d.current)return;Gm.set(m,{slots:x,expiresAt:Date.now()+R0}),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 Jm({size:e,color:n,label:s="llama.cpp"}){return t.jsx(Tg,{size:e,color:n,"aria-label":s,"data-testid":"llama-cpp-icon"})}const P0={sm:16,md:20,lg:24};function I0({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 Ym({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 Si({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 T0({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 Qm({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 $0({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 Mc({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 Xm({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 Zm({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 eh({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 Ac({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 th({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 zr({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 nh({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 Rc({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 sh({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 Pc({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 D0({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 L0({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 ih({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 Ic({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 O0({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 ah({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 Tc({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 rh({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 $c({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 oh({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 z0({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 F0({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 B0={anthropic:{component:I0,color:"var(--provider-anthropic)"},"claude-cli":{component:oh,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:oh,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"droid-cli":{component:z0,color:"var(--provider-openai)",label:"Factory AI — via Droid CLI"},"cursor-cli":{component:F0,color:"var(--provider-cursor-cli)",label:"Cursor — via Cursor CLI"},"llama-cpp":{component:Jm,color:"var(--provider-ollama)",label:"llama.cpp"},"llama-server":{component:Jm,color:"var(--provider-ollama)",label:"llama.cpp"},openai:{component:Ym,color:"var(--provider-openai)"},"openai-codex":{component:Ym,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:Si,color:"var(--provider-gemini)"},gemini:{component:Si,color:"var(--provider-gemini)"},"google-antigravity":{component:Si,color:"var(--provider-gemini)",label:"Google Gemini"},antigravity:{component:Si,color:"var(--provider-gemini)",label:"Google Gemini"},"google-vertex":{component:Si,color:"var(--provider-gemini)",label:"Google Vertex AI"},vertex:{component:Si,color:"var(--provider-gemini)",label:"Google Vertex AI"},"google-cloud-code":{component:Si,color:"var(--provider-gemini)",label:"Google Cloud Code"},"cloud-code":{component:Si,color:"var(--provider-gemini)",label:"Google Cloud Code"},"google-gemini-cli":{component:Si,color:"var(--provider-gemini)",label:"Google Gemini CLI"},"google-generative-ai":{component:Si,color:"var(--provider-gemini)",label:"Google Generative AI"},ollama:{component:T0,color:"var(--text)"},github:{component:ah,color:"var(--text)"},"github-copilot":{component:ah,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:O0,color:"var(--provider-openrouter)"},minimax:{component:Qm,color:"var(--provider-minimax)"},"minimax-cn":{component:Qm,color:"var(--provider-minimax)",label:"MiniMax (CN)"},zai:{component:$0,color:"var(--provider-zai)"},kimi:{component:Mc,color:"var(--provider-kimi)"},moonshot:{component:Mc,color:"var(--provider-kimi)"},"kimi-coding":{component:Mc,color:"var(--provider-kimi)",label:"Kimi"},bedrock:{component:Xm,color:"var(--provider-bedrock)"},"amazon-bedrock":{component:Xm,color:"var(--provider-bedrock)",label:"Amazon Bedrock"},xai:{component:Zm,color:"var(--text)"},grok:{component:Zm,color:"var(--text)",label:"xAI"},opencode:{component:eh,color:"var(--provider-opencode)"},"opencode-go":{component:eh,color:"var(--provider-opencode)",label:"Opencode (Go)"},deepseek:{component:Ac,color:"var(--provider-deepseek)",label:"DeepSeek"},"deepseek-ai":{component:Ac,color:"var(--provider-deepseek)",label:"DeepSeek"},"deep-seek":{component:Ac,color:"var(--provider-deepseek)",label:"DeepSeek"},cloudflare:{component:th,color:"var(--provider-cloudflare)",label:"Cloudflare"},cloudflared:{component:th,color:"var(--provider-cloudflare)",label:"Cloudflare"},qwen:{component:zr,color:"var(--provider-qwen)"},"qwen-ai":{component:zr,color:"var(--provider-qwen)",label:"Qwen"},"qwen-coder":{component:zr,color:"var(--provider-qwen)",label:"Qwen Coder"},alibaba:{component:zr,color:"var(--provider-qwen)",label:"Qwen"},tongyi:{component:zr,color:"var(--provider-qwen)",label:"Qwen"},lmstudio:{component:nh,color:"var(--provider-lmstudio)",label:"LM Studio"},"lm-studio":{component:nh,color:"var(--provider-lmstudio)",label:"LM Studio"},huggingface:{component:Rc,color:"var(--provider-huggingface)",label:"Hugging Face"},"hugging-face":{component:Rc,color:"var(--provider-huggingface)",label:"Hugging Face"},hf:{component:Rc,color:"var(--provider-huggingface)",label:"Hugging Face"},mistral:{component:sh,color:"var(--provider-mistral)",label:"Mistral AI"},"mistral-ai":{component:sh,color:"var(--provider-mistral)",label:"Mistral AI"},azure:{component:Pc,color:"var(--provider-azure)"},"azure-openai":{component:Pc,color:"var(--provider-azure)",label:"Azure OpenAI"},"azure-openai-responses":{component:Pc,color:"var(--provider-azure)",label:"Azure OpenAI"},fireworks:{component:Ic,color:"var(--provider-fireworks)",label:"Fireworks AI"},"fireworks-ai":{component:Ic,color:"var(--provider-fireworks)",label:"Fireworks AI"},fireworksai:{component:Ic,color:"var(--provider-fireworks)",label:"Fireworks AI"},cerebras:{component:D0,color:"var(--provider-cerebras)"},groq:{component:L0,color:"var(--provider-groq)"},vercel:{component:ih,color:"var(--provider-vercel)"},"vercel-ai-gateway":{component:ih,color:"var(--provider-vercel)",label:"Vercel AI Gateway"},hermes:{component:Tc,color:"var(--provider-hermes)",label:"Hermes"},"hermes-agent":{component:Tc,color:"var(--provider-hermes)",label:"Hermes"},hermesagent:{component:Tc,color:"var(--provider-hermes)",label:"Hermes"},openclaw:{component:rh,color:"var(--provider-openclaw)",label:"OpenClaw"},"open-claw":{component:rh,color:"var(--provider-openclaw)",label:"OpenClaw"},paperclip:{component:$c,color:"var(--provider-paperclip)",label:"Paperclip"},paperclipai:{component:$c,color:"var(--provider-paperclip)",label:"Paperclip"},"paperclip-ai":{component:$c,color:"var(--provider-paperclip)",label:"Paperclip"}};function Tn({provider:e,size:n="sm"}){const s=e.toLowerCase(),a=B0[s],r=a?.component,o=a?.color??"var(--text-muted)",l=a?.label,c=P0[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(Tg,{size:c})})}function cb({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 Vj();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 v=await Jj(b);u.current&&d({kind:v.enabled?"enabled":"disabled",restartRequired:v.restartRequired}),n?.(v.enabled),await m()}catch(v){u.current&&d({kind:"error",message:v instanceof Error?v.message:String(v)})}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(Nt,{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(Tn,{provider:"droid-cli",size:"sm"}),t.jsx("strong",{children:"Factory AI — via Droid CLI"}),t.jsx(U0,{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(lh,{status:a,authenticated:e}),c&&t.jsx(ch,{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(Tn,{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(lh,{status:a,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:w}),c&&t.jsx(ch,{action:c})]})}function U0({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 lh({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(Nt,{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 ch({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 dh({actions:e}){return t.jsx(cb,{compact:!0,authenticated:!1,onToggled:()=>{e?.refreshAuthProviders?.()}})}function H0({actions:e}){return t.jsx(cb,{authenticated:!1,onToggled:()=>{e?.refreshAuthProviders?.()}})}function q0(){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 V0({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 W0=[{pluginId:"fusion-plugin-droid-runtime",slotId:"settings-provider-card",componentPath:"./components/settings-provider-card.js",component:dh},{pluginId:"fusion-plugin-droid-runtime",slotId:"settings-integration-card",componentPath:"./components/settings-integration-card.js",component:dh},{pluginId:"fusion-plugin-droid-runtime",slotId:"onboarding-provider-card",componentPath:"./components/onboarding-provider-card.js",component:H0},{pluginId:"fusion-plugin-droid-runtime",slotId:"onboarding-setup-help",componentPath:"./components/onboarding-setup-help.js",component:q0},{pluginId:"fusion-plugin-droid-runtime",slotId:"post-onboarding-recommendation",componentPath:"./components/post-onboarding-recommendation.js",component:V0}];function K0(e){return W0.find(s=>s.pluginId===e.pluginId&&s.slotId===e.slot.slotId&&s.componentPath===e.slot.componentPath)?.component??null}function G0({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 ia({slotId:e,projectId:n,pluginIds:s,renderPlaceholder:a=!0,actions:r}){const{getSlotsForId:o,loading:l,error:c}=lb(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(Po,{level:"page",children:t.jsx(t.Fragment,{children:d.map((u,m)=>{const h=`${u.pluginId}-${u.slot.slotId}-${m}`,f=K0(u);return f?t.jsx(f,{entry:u,actions:r},h):a?t.jsx(G0,{slotId:u.slot.slotId,pluginId:u.pluginId},h):null})})})}function J0(){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 Zs(){const[e,n]=i.useState(J0);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 Ar(e){return e.replace(/\\/g,"/")}function Pu(e){return e.replace(/[\\/]+$/g,"")}function Iu(e){const n=Ar(Pu(e));return n?n.split("/").filter(Boolean):[]}function Tu(e){const n=Ar(Pu(e));if(!n)return e;const s=n.split("/").filter(Boolean);return s[s.length-1]||n}function db(e,n){const s=Iu(e);return s.length===0?Ar(e):s.slice(-2).join("/")}function Y0(e){const n=Ar(Pu(e)),s=n.lastIndexOf("/");return s<0?"":n.slice(0,s+1)}function Q0(e,n){return!e||e==="."?n:[...Iu(e),n].join("/")}function X0(e){const n=Iu(e);return n.length===0?".":(n.pop(),n.length===0?".":n.join("/"))}function N5(e){const n=Ar(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 $u=new Map;function zo(e,n){return`plugin:${e}:${n}`}function ub(e){const n=/^plugin:([^:]+):(.+)$/u.exec(e);return n?{pluginId:n[1],viewId:n[2]}:null}function ur(e){return ub(e)!==null}function uh(e,n,s){$u.set(zo(e,n),s)}function Z0(e,n){return $u.get(zo(e,n))??null}function mb(e,n){return $u.has(zo(e,n))}function Dc({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(Ro,{}),"Plugin view unavailable"]}),t.jsxs("p",{className:"plugin-dashboard-view-missing-description",children:["No host registration found for ",t.jsx("code",{children:e}),"."]})]})}function eC({viewId:e,context:n}){const s=ub(e);if(!s)return t.jsx(Dc,{viewId:e});const a=Z0(s.pluginId,s.viewId);return a?t.jsx(Po,{fallback:t.jsx(Dc,{viewId:e}),children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(a,{context:n})})}):t.jsx(Dc,{viewId:e})}const uo=zo,tC={activity:Ys,bot:Vn,brain:go,checksquare:Cu,clock:Wi,filetext:oa,folder:ys,gitbranch:Ps,grid3x3:nc,layoutgrid:la,mail:Ta,map:qw,messagesquare:qi,monitor:fr,search:Hi,sparkles:xs,target:js,workflow:Pl,zap:is};function nC(e){return(e??"").trim().toLowerCase().replace(/[-_\s]/g,"")}function Dl(e){return tC[nC(e)]??nc}const Jo="__fusion:no-branch__",hb={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function sC({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(un,{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=hb[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:db(d.path)})]}),u&&t.jsx(bs,{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 mh({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 iC({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:v,onRunScript:N,onToggleTerminal:k,onOpenFiles:E,filesOpen:y,onOpenTodos:j,todosOpen:P,todosEnabled:F,globalPaused:_,enginePaused:R,onToggleGlobalPause:L,onToggleEnginePause:U,view:C="board",onChangeView:$,showSkillsTab:V,showAgentsTab:Y,searchQuery:ne="",onSearchChange:q,branchFilter:A="",baseBranchFilter:I="",branchOptions:D=[],baseBranchOptions:S=[],onBranchFilterChange:G,onBaseBranchFilterChange:he,projects:Se=[],currentProject:Ue,onSelectProject:ce,onViewAllProjects:Ae,projectId:X,shellHost:Z={kind:"browser"},mobileNavEnabled:ee,availableNodes:le=[],currentNode:K,onSelectNode:O,isRemote:pe=!1,experimentalFeatures:ve,pluginDashboardViews:B=[],shellConnectionControl:we}){const ze=Zs(),re=ze==="mobile",Pe=re||ze==="tablet",tt=re&&ee,[qe,de]=i.useState(!1),[De,Te]=i.useState(!1),[ct,Ve]=i.useState(!1),[me,oe]=i.useState(!1),[Me,Xe]=i.useState(!1),[rt,ht]=i.useState(!1),[yt,Re]=i.useState(!1),[Ge,at]=i.useState(!1),[ie,Ke]=i.useState(!1),[je,Fe]=i.useState(!1),[Be,St]=i.useState(!1),[ye,kt]=i.useState({}),[It,Ie]=i.useState(!1),[be,ot]=i.useState(-1),[gt,xt]=i.useState(null),[jt,Bt]=i.useState({}),[Jt,Vt]=i.useState(!1),pn=i.useRef(null),Xt=i.useRef(null),mn=i.useRef(null),Ht=i.useRef(null),Zt=i.useRef(null),tn=i.useRef(null),dn=i.useRef(!1),qt=i.useRef(null),ke=i.useRef(null),$e=i.useRef(null),Ye=i.useRef(null),ut=i.useRef(null),We=i.useRef(null),$t=i.useRef(null),At=i.useRef(null),wt=i.useRef(!1),zt=i.useMemo(()=>le.filter(ae=>ae.type==="remote"),[le]),Lt=zt.length>0,Ot=i.useMemo(()=>Object.entries(ye).sort(([ae],[pt])=>ae.localeCompare(pt)),[ye]),nn=Ot.length>0,Yt=Ot.length+(nn?1:0),rn=i.useMemo(()=>Object.entries(jt).sort(([ae],[pt])=>ae.localeCompare(pt)),[jt]),_e=i.useMemo(()=>!!($||ve?.researchView||F||ve?.insights||V||ve?.memoryView||ve?.devServerView||!tt||B.some(ae=>ae.view.placement!=="primary")),[$,ve,F,V,tt,B]),it=i.useCallback(()=>{const ae=window.visualViewport;return ae&&ae.width>0&&ae.height>0?{width:ae.width,height:ae.height,offsetTop:ae.offsetTop,offsetLeft:ae.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),bt=i.useCallback(()=>{const ae=$t.current;if(!ae)return;const pt=ae.getBoundingClientRect(),gn=At.current,{width:us,height:Kn,offsetTop:_n,offsetLeft:$n}=it(),hn=16,Ut=16,Dn=6,as=gn?.offsetWidth||Math.max(pt.width,260),Rn=Math.min(as,Math.max(us-hn*2,160)),ms=gn?.offsetHeight||280,Xn=Math.min(ms,Math.max(Kn-Ut*2,160)),vs=pt.top-_n,Gn=pt.bottom-_n,hs=pt.right-$n,Ln=Kn-Gn,En=vs,ps=Ln<Xn&&En>Ln,Nn=Math.min(Math.max(hs-Rn,hn),us-hn-Rn)+$n,As=ps?Math.max(Ut+_n,vs-Xn-Dn+_n):Math.min(Gn+Dn+_n,Kn+_n-Ut-Xn);xt({top:As,left:Nn,width:Rn})},[it]),Rt=i.useCallback((ae,pt)=>{N?.(ae,pt),St(!1),ot(-1)},[N]),se=i.useCallback(()=>{v?.(),St(!1),ot(-1)},[v]),te=i.useCallback(ae=>{switch(ae.key){case"ArrowDown":ae.preventDefault(),Yt>0&&ot(pt=>pt<Yt-1?pt+1:0);break;case"ArrowUp":ae.preventDefault(),Yt>0&&ot(pt=>pt>0?pt-1:Yt-1);break;case"Enter":if(ae.preventDefault(),be>=0)if(be<Ot.length){const[pt,gn]=Ot[be];Rt(pt,gn)}else nn&&be===Ot.length&&se();break;case"Home":ae.preventDefault(),Yt>0&&ot(0);break;case"End":ae.preventDefault(),Yt>0&&ot(Yt-1);break}},[se,Rt,be,Ot,nn,Yt]);i.useEffect(()=>{dn.current=Me},[Me]),i.useEffect(()=>{wt.current=Be},[Be]),i.useEffect(()=>{if(!Me||!Pe)return;let ae=!1;return Vt(!0),vo(X).then(pt=>{ae||Bt(pt)}).catch(()=>{ae||Bt({})}).finally(()=>{ae||Vt(!1)}),()=>{ae=!0}},[Me,Pe,X]),i.useEffect(()=>{if(!Be||Pe)return;let ae=!1;return Ie(!0),vo(X).then(pt=>{ae||kt(pt)}).catch(()=>{ae||kt({})}).finally(()=>{ae||Ie(!1)}),()=>{ae=!0}},[Be,Pe,X]),i.useEffect(()=>{if(!Be)return;const ae=pt=>{We.current&&!We.current.contains(pt.target)&&St(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[Be]),i.useEffect(()=>{if(!Be)return;const ae=pt=>{pt.key==="Escape"&&(St(!1),$t.current?.focus())};return document.addEventListener("keydown",ae),()=>document.removeEventListener("keydown",ae)},[Be]),i.useEffect(()=>{if(Be){ot(-1);const ae=window.setTimeout(()=>At.current?.focus(),0);return()=>window.clearTimeout(ae)}xt(null)},[Be]),i.useEffect(()=>{if(!Be)return;const ae=requestAnimationFrame(()=>{bt()});return()=>cancelAnimationFrame(ae)},[Be,It,Ot.length,nn,bt]),i.useEffect(()=>{if(!Be)return;const ae=()=>bt();window.addEventListener("resize",ae),window.addEventListener("scroll",ae,!0);const pt=window.visualViewport;return pt&&(pt.addEventListener("resize",ae),pt.addEventListener("scroll",ae)),()=>{window.removeEventListener("resize",ae),window.removeEventListener("scroll",ae,!0),pt&&(pt.removeEventListener("resize",ae),pt.removeEventListener("scroll",ae))}},[Be,bt]),i.useEffect(()=>{Pe&&(St(!1),ot(-1))},[Pe]);const Oe=qe||ne.length>0,mt=(De||ne.length>0)&&!ct,Pt=(C==="board"||C==="list")&&!re&&q&&!ct&&ne.length===0,sn=(C==="board"||C==="list")&&!re&&q,In=C==="board";i.useEffect(()=>{ne===""&&Ve(!1)},[ne]),i.useEffect(()=>{if(!me)return;const ae=pt=>{Xt.current&&!Xt.current.contains(pt.target)&&pn.current&&!pn.current.contains(pt.target)&&oe(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[me]),i.useEffect(()=>{if(!ie)return;const ae=pt=>{Ht.current&&!Ht.current.contains(pt.target)&&mn.current&&!mn.current.contains(pt.target)&&Ke(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[ie]),i.useEffect(()=>{if(!rt)return;const ae=pt=>{qt.current&&!qt.current.contains(pt.target)&&ht(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[rt]),i.useEffect(()=>{const ae=pt=>{if(pt.key==="Escape"){if(at(!1),Ke(!1),dn.current){Xe(!1);return}if(wt.current){St(!1),$t.current?.focus();return}oe(!1),de(!1),ht(!1),Re(!1)}};return document.addEventListener("keydown",ae),()=>document.removeEventListener("keydown",ae)},[]),i.useEffect(()=>{if(!yt)return;const ae=pt=>{ke.current&&!ke.current.contains(pt.target)&&Re(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[yt]),i.useEffect(()=>{if(!je)return;const ae=pt=>{ut.current&&!ut.current.contains(pt.target)&&Fe(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[je]),i.useEffect(()=>{if(!je)return;const ae=pt=>{pt.key==="Escape"&&Fe(!1)};return document.addEventListener("keydown",ae),()=>document.removeEventListener("keydown",ae)},[je]),i.useEffect(()=>{if(!Ge)return;const ae=pt=>{$e.current&&!$e.current.contains(pt.target)&&Ye.current&&!Ye.current.contains(pt.target)&&at(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[Ge]);const fe=i.useCallback(()=>{de(ae=>!ae)},[]),ft=i.useCallback(()=>{Te(!0),Ve(!1)},[]),lt=i.useCallback(()=>{Te(!1),Ve(!0),q&&q("")},[q]),vt=i.useCallback(()=>{oe(ae=>!ae)},[]),et=i.useCallback(ae=>{ae&&ae(),oe(!1),Xe(!1)},[]),_t=i.useCallback(()=>{de(!1),q&&q("")},[q]),Gt=Z.kind==="desktop-shell";return t.jsxs("div",{className:"header-wrapper",children:[t.jsxs("header",{className:"header","data-shell-kind":Z.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"})]}),re&&Se.length>=1&&ce&&t.jsxs("div",{className:"mobile-project-switch",ref:ke,children:[t.jsx("button",{className:`mobile-project-switch-trigger${yt?" mobile-project-switch-trigger--open":""}`,onClick:()=>Re(ae=>!ae),title:"Switch project","aria-label":"Switch project","aria-expanded":yt,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(un,{size:14,className:`mobile-project-switch-chevron${yt?" mobile-project-switch-chevron--open":""}`})}),yt&&t.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:Se.map(ae=>{const pt=Ue?.id===ae.id,gn=hb[ae.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${pt?" mobile-project-switch-item--current":""}`,onClick:()=>{ce(ae),Re(!1)},role:"option","aria-selected":pt,"data-testid":`mobile-project-switch-item-${ae.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:gn||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:ae.name}),t.jsx("span",{className:"mobile-project-switch-path",children:db(ae.path)})]}),pt&&t.jsx(bs,{size:14,className:"mobile-project-switch-check"})]},ae.id)})})]}),!Pe&&Se.length>=1&&Ae&&t.jsx(sC,{projects:Se,currentProject:Ue??null,onViewAll:Ae,onSelectProject:ce}),Lt&&t.jsxs("div",{className:`header-node-selector${re?" header-node-selector--mobile":""}`,ref:re?void 0:qt,children:[t.jsx(M0,{node:K??null,showDetails:!re}),!re&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${rt?" node-selector-trigger--open":""}`,onClick:()=>ht(ae=>!ae),title:"Switch node","aria-label":"Switch node","aria-expanded":rt,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(zn,{size:12,className:`node-selector-chevron${rt?" node-selector-chevron--open":""}`})}),rt&&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:()=>{O?.(null),ht(!1)},role:"option","aria-selected":!pe,"data-testid":"node-option-local",children:[t.jsx(Da,{status:"online",compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),zt.map(ae=>t.jsxs("button",{className:`node-selector-option${K?.id===ae.id?" node-selector-option--active":""}`,onClick:()=>{O?.(ae),ht(!1)},role:"option","aria-selected":K?.id===ae.id,"data-testid":`node-option-${ae.id}`,children:[t.jsx(Da,{status:ae.status,compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:ae.name}),t.jsx("span",{className:"node-selector-option-status",children:ae.status})]},ae.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[we,tt&&$&&(C==="board"||C==="list")&&t.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${C==="board"?" active":""}`,onClick:()=>$("board"),title:"Board view","aria-label":"Board view","aria-pressed":C==="board","data-testid":"mobile-view-toggle-board",children:t.jsx(la,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="list"?" active":""}`,onClick:()=>$("list"),title:"List view","aria-label":"List view","aria-pressed":C==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(qd,{size:16})})]}),q&&re&&(tt||C==="board"||C==="list")&&!Oe&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:fe,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx(Hi,{size:16})}),Pt&&t.jsx("button",{className:"btn-icon",onClick:ft,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(Hi,{size:16})}),re&&tt&&o&&t.jsx("button",{className:"btn-icon",onClick:ae=>o(ae.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(Ys,{size:16})}),!tt&&$&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${C==="board"?" active":""}`,onClick:()=>$("board"),title:"Board view","aria-label":"Board view","aria-pressed":C==="board",children:t.jsx(la,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="list"?" active":""}`,onClick:()=>$("list"),title:"List view","aria-label":"List view","aria-pressed":C==="list",children:t.jsx(qd,{size:16})}),Y&&t.jsx("button",{className:`view-toggle-btn${C==="agents"?" active":""}`,onClick:()=>$("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":C==="agents",children:t.jsx(Vn,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="missions"?" active":""}`,onClick:()=>$("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":C==="missions",children:t.jsx(js,{size:16})}),t.jsxs("button",{className:`view-toggle-btn${C==="chat"?" active":""}`,onClick:()=>$("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":C==="chat","data-testid":"header-chat-view-btn",children:[t.jsx(qi,{size:16}),h&&C!=="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${C==="documents"?" active":""}`,onClick:()=>$("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":C==="documents",children:t.jsx(oa,{size:16})}),t.jsxs("button",{className:`view-toggle-btn${C==="mailbox"?" active":""}`,onClick:()=>$("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":C==="mailbox",children:[t.jsx(Ta,{size:16}),m>0&&C!=="mailbox"&&t.jsx("span",{className:"status-dot status-dot--pending header-chat-unread-dot","aria-label":"Pending approvals"})]}),B.filter(ae=>ae.view.placement==="primary").sort((ae,pt)=>(ae.view.order??Number.MAX_SAFE_INTEGER)-(pt.view.order??Number.MAX_SAFE_INTEGER)).map(ae=>{const pt=uo(ae.pluginId,ae.view.viewId),gn=Dl(ae.view.icon);return t.jsx("button",{className:`view-toggle-btn${C===pt||C==="graph"&&ae.pluginId==="fusion-plugin-dependency-graph"&&ae.view.viewId==="graph"?" active":""}`,onClick:()=>$(ae.pluginId==="fusion-plugin-dependency-graph"&&ae.view.viewId==="graph"?"graph":pt),title:`${ae.view.label} view`,"aria-label":`${ae.view.label} view`,"aria-pressed":C===pt,"data-testid":`view-toggle-plugin-${ae.pluginId}-${ae.view.viewId}`,children:t.jsx(gn,{size:16})},`${ae.pluginId}:${ae.view.viewId}`)}),_e&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:Ye,className:`view-toggle-btn${["research","skills","insights","memory","dev-server","devserver","graph","stash-recovery"].includes(C)||ve?.evalsView&&C==="evals"||F&&P||ur(C)?" active":""}`,onClick:()=>at(ae=>!ae),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":Ge,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(un,{size:12})}),Ge&&t.jsxs("div",{ref:$e,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[ve?.evalsView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="evals"?" active":""}`,onClick:()=>{$("evals"),at(!1)},role:"menuitem","data-testid":"view-overflow-evals",children:[t.jsx(js,{size:14}),t.jsx("span",{children:"Evals"})]}),t.jsxs("button",{className:`view-toggle-overflow-item${C==="stash-recovery"?" active":""}`,onClick:()=>{$("stash-recovery"),at(!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]}),ve?.researchView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="research"?" active":""}`,onClick:()=>{$("research"),at(!1)},role:"menuitem","data-testid":"view-overflow-research",children:[t.jsx(Hi,{size:14}),t.jsx("span",{children:"Research"})]}),ve?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="insights"?" active":""}`,onClick:()=>{$("insights"),at(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(xs,{size:14}),t.jsx("span",{children:"Insights"})]}),V&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="skills"?" active":""}`,onClick:()=>{$("skills"),at(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(is,{size:14}),t.jsx("span",{children:"Skills"})]}),ve?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="memory"?" active":""}`,onClick:()=>{$("memory"),at(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(go,{size:14}),t.jsx("span",{children:"Memory"})]}),ve?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="dev-server"||C==="devserver"?" active":""}`,onClick:()=>{$("devserver"),at(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(fr,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]}),F&&j&&t.jsxs("button",{className:`view-toggle-overflow-item${P?" active":""}`,onClick:()=>{j(),at(!1)},role:"menuitem","data-testid":"view-overflow-todos",children:[t.jsx(Cu,{size:14}),t.jsx("span",{children:"Todos"})]}),B.filter(ae=>ae.view.placement!=="primary").sort((ae,pt)=>(ae.view.order??Number.MAX_SAFE_INTEGER)-(pt.view.order??Number.MAX_SAFE_INTEGER)).map(ae=>{const pt=uo(ae.pluginId,ae.view.viewId),gn=Dl(ae.view.icon);return t.jsxs("button",{className:`view-toggle-overflow-item${C===pt||C==="graph"&&ae.pluginId==="fusion-plugin-dependency-graph"&&ae.view.viewId==="graph"?" active":""}`,onClick:()=>{$(ae.pluginId==="fusion-plugin-dependency-graph"&&ae.view.viewId==="graph"?"graph":pt),at(!1)},role:"menuitem","data-testid":`view-overflow-plugin-${ae.pluginId}-${ae.view.viewId}`,children:[t.jsx(gn,{size:14}),t.jsx("span",{children:ae.view.label})]},`${ae.pluginId}:${ae.view.viewId}`)})]})]})]}),!Pe&&o&&t.jsx("button",{className:"btn-icon",onClick:ae=>o(ae.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(fr,{size:16})}),!Pe&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(Pa,{size:16})}),!Pe&&!Gt&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(mh,{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(Pi,{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:We,children:[t.jsx("button",{className:"btn-icon btn-icon--terminal terminal-split-btn__main",onClick:k,title:"Open Terminal","data-testid":"terminal-toggle-btn",children:t.jsx(Vi,{size:16})}),v&&N&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"terminal-split-btn__divider"}),t.jsx("button",{ref:$t,className:`btn-icon terminal-split-btn__chevron${Be?" btn-icon--active":""}`,onClick:()=>St(ae=>!ae),title:"Scripts","aria-haspopup":"listbox","aria-expanded":Be,"aria-label":"Quick scripts","data-testid":"scripts-btn",children:t.jsx(un,{size:12,className:`quick-scripts-dropdown__trigger-chevron${Be?" rotate":""}`})}),Be&&t.jsx("div",{ref:At,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:te,"data-testid":"quick-scripts-dropdown",style:gt?{position:"fixed",top:`${gt.top}px`,left:`${gt.left}px`,width:`${gt.width}px`,right:"auto"}:void 0,children:It?t.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[t.jsx(Nt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):Ot.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(Vi,{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:Ot.map(([ae,pt],gn)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${be===gn?"highlighted":""}`,onClick:()=>Rt(ae,pt),role:"option","aria-selected":be===gn,"data-testid":`quick-script-item-${ae}`,children:[t.jsx(ss,{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:ae}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:pt,children:pt.length>50?`${pt.slice(0,50)}...`:pt})]})]},ae))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${nn&&be===Ot.length?"highlighted":""}`,onClick:se,"data-testid":"quick-scripts-manage",children:[t.jsx(co,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})]}),!Pe&&E&&t.jsx("button",{className:`btn-icon${y?" btn-icon--active":""}`,onClick:E,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(ys,{size:16})}),!Pe&&g&&t.jsx("button",{className:"btn-icon",onClick:g,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Ps,{size:16})}),!Pe&&b&&t.jsx("button",{className:"btn-icon",onClick:b,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(Pl,{size:16})}),!Pe&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:mn,className:"btn-icon",onClick:()=>Ke(ae=>!ae),title:"More actions","aria-label":"More actions","aria-expanded":ie,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(Bd,{size:16})}),ie&&t.jsxs("div",{ref:Ht,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[x&&w!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{x(),Ke(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx(bo,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{et(p),Ke(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(Wi,{size:14}),t.jsx("span",{children:"Automation"})]})]})]}),t.jsxs("div",{className:"engine-control-split-btn",ref:ut,children:[t.jsx("button",{className:`btn-icon engine-control-split-btn__main${_?" btn-icon--stopped":""}`,onClick:L,title:_?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:_?t.jsx(ss,{size:16}):t.jsx(Mi,{size:16})}),t.jsx("span",{className:"engine-control-split-btn__divider"}),t.jsx("button",{className:`btn-icon engine-control-split-btn__chevron${je?" btn-icon--active":""}`,onClick:()=>Fe(ae=>!ae),title:"Engine options","aria-haspopup":"menu","aria-expanded":je,"data-testid":"engine-control-chevron-btn",children:t.jsx(un,{size:12})}),je&&t.jsx("div",{className:"engine-control-split-btn__menu",role:"menu",children:t.jsxs("button",{className:`engine-control-split-btn__menu-item${R?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{U?.(),Fe(!1)},role:"menuitem",title:R?"Resume scheduling":"Pause triage",disabled:!!_,"data-testid":"engine-control-pause-triage-btn",children:[R?t.jsx(ss,{size:14}):t.jsx(xi,{size:14}),t.jsx("span",{children:R?"Resume scheduling":"Pause triage"})]})})]}),!Pe&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(co,{size:16})}),t.jsx(ia,{slotId:"header-action",projectId:X}),Pe&&!tt&&t.jsx("button",{ref:pn,className:"btn-icon compact-overflow-trigger",onClick:vt,title:"More header actions","aria-label":"More header actions","aria-expanded":me,"aria-haspopup":"menu",children:t.jsx(Bd,{size:16})}),Pe&&!tt&&me&&t.jsxs("div",{ref:Xt,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[Se.length>=1&&Ae&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>et(Ae),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(nc,{size:16}),t.jsx("span",{children:"Projects"})]}),E&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>et(E),role:"menuitem","data-testid":"overflow-files-btn",children:[t.jsx(ys,{size:16}),t.jsx("span",{children:"Browse Files"})]}),t.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>et(r>0&&a?a:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx(Pi,{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:()=>et(g),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(Ps,{size:16}),t.jsx("span",{children:"Git Manager"})]}),x&&w!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>et(x),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(bo,{size:16}),t.jsx("span",{children:"Nodes"})]}),!Gt&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>et(n),role:"menuitem",children:[t.jsx(mh,{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:()=>et(k),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[t.jsx(Vi,{size:16}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>Xe(ae=>!ae),role:"menuitem","aria-expanded":Me,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(zn,{size:14,className:`mobile-overflow-chevron${Me?" mobile-overflow-chevron--open":""}`})})]}),Me&&t.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:Jt?t.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[t.jsx(Nt,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):rn.length>0?t.jsxs(t.Fragment,{children:[rn.map(([ae,pt])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{N&&N(ae,pt),oe(!1),Xe(!1)},role:"menuitem","data-testid":`overflow-script-item-${ae}`,children:[t.jsx(ss,{size:14}),t.jsx("span",{children:ae})]},ae)),v&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>et(v),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(bi,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):v&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>et(v),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(bi,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>et(p),role:"menuitem","data-testid":"overflow-schedules-btn",children:[t.jsx(Wi,{size:16}),t.jsx("span",{children:"Automation"})]}),l&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>et(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:()=>et(d),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(Ta,{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:ae=>et(()=>o(ae.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:()=>et(b),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(Pl,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>et(e),role:"menuitem",children:[t.jsx(co,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),sn&&mt&&t.jsxs("div",{className:"header-floating-search",children:[t.jsxs("div",{className:"header-search",children:[t.jsx(Hi,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:ne,onChange:ae=>q(ae.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:lt,"aria-label":"Close search",children:t.jsx(an,{size:14})})]}),In&&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:ae=>G?.(ae.target.value),"data-testid":"working-branch-filter",children:[t.jsx("option",{value:"",children:"All working branches"}),t.jsx("option",{value:Jo,children:"No working branch"}),D.map(ae=>t.jsx("option",{value:ae,children:ae},ae))]})]}),t.jsxs("label",{className:"header-branch-filter-label",children:[t.jsx("span",{children:"Base branch"}),t.jsxs("select",{className:"header-branch-filter-select",value:I,onChange:ae=>he?.(ae.target.value),"data-testid":"target-branch-filter",children:[t.jsx("option",{value:"",children:"All base branches"}),t.jsx("option",{value:Jo,children:"No base branch"}),S.map(ae=>t.jsx("option",{value:ae,children:ae},ae))]})]})]})]}),q&&re&&Oe&&t.jsxs("div",{className:"header-floating-search",children:[t.jsxs("div",{ref:Zt,className:"header-search mobile-search-expanded",children:[t.jsx(Hi,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:tn,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:ne,onChange:ae=>q(ae.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:_t,"aria-label":"Close search",children:t.jsx(an,{size:14})})]}),In&&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:ae=>G?.(ae.target.value),"data-testid":"working-branch-filter-mobile",children:[t.jsx("option",{value:"",children:"All working branches"}),t.jsx("option",{value:Jo,children:"No working branch"}),D.map(ae=>t.jsx("option",{value:ae,children:ae},ae))]})]}),t.jsxs("label",{className:"header-branch-filter-label",children:[t.jsx("span",{children:"Base branch"}),t.jsxs("select",{className:"header-branch-filter-select",value:I,onChange:ae=>he?.(ae.target.value),"data-testid":"target-branch-filter-mobile",children:[t.jsx("option",{value:"",children:"All base branches"}),t.jsx("option",{value:Jo,children:"No base branch"}),S.map(ae=>t.jsx("option",{value:ae,children:ae},ae))]})]})]})]})]})}const aC={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,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,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:{}},rC={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,strictScopeEnforcement:!1,buildRetryCount:0,verificationFixRetries:3,buildTimeoutMs:3e5,requirePlanApproval:!1,specStalenessEnabled:!1,specStalenessMaxAgeMs:360*60*1e3,taskStuckTimeoutMs:void 0,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},oC=Object.freeze(Object.keys(aC)),lC=Object.freeze(Object.keys(rC));function S5(e){return oC.includes(e)}function C5(e){return lC.includes(e)}function Ce(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function cC(e){return!!(e?.provider&&e?.modelId)}function ca(...e){for(const n of e)if(cC(n))return{provider:n.provider,modelId:n.modelId};return{}}function cc(e){return ca({provider:e?.defaultProviderOverride,modelId:e?.defaultModelIdOverride},{provider:e?.defaultProvider,modelId:e?.defaultModelId})}function dC(e){return ca({provider:e?.executionProvider,modelId:e?.executionModelId},{provider:e?.executionGlobalProvider,modelId:e?.executionGlobalModelId},cc(e))}function uC(e){return ca({provider:e?.planningProvider,modelId:e?.planningModelId},{provider:e?.planningGlobalProvider,modelId:e?.planningGlobalModelId},cc(e))}function mC(e){return ca({provider:e?.validatorProvider,modelId:e?.validatorModelId},{provider:e?.validatorGlobalProvider,modelId:e?.validatorGlobalModelId},cc(e))}function E5(e){return ca({provider:e?.titleSummarizerProvider,modelId:e?.titleSummarizerModelId},{provider:e?.titleSummarizerGlobalProvider,modelId:e?.titleSummarizerGlobalModelId},{provider:e?.planningProvider,modelId:e?.planningModelId},cc(e))}function pb(e,n){return ca({provider:e.modelProvider,modelId:e.modelId},dC(n))}function fb(e,n){return ca({provider:e.validatorModelProvider,modelId:e.validatorModelId},mC(n))}function gb(e,n){return ca({provider:e.planningModelProvider,modelId:e.planningModelId},uC(n))}const _5=["off","minimal","low","medium","high"],sa=["triage","todo","in-progress","in-review","done","archived"],Ll="triage";function Du(e){return typeof e=="string"&&sa.includes(e)}function bb(e,n=Ll){return Du(e)?e:n}const da=["low","normal","high","urgent"],Ms="normal",hC=["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"],dc=/^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/,cs={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},pC={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"},Qd={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 fC(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 hh(e){return e==="urgent"?3:e==="high"?2:e==="low"?0:1}function ph(e,n){return hh(n)-hh(e)}function Lc(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 fh(e){const n=e.columnMovedAt??e.updatedAt??e.createdAt,s=Date.parse(n);return Number.isFinite(s)?s:0}function gh(e){return e==="merging"||e==="merging-pr"||e==="merging-fix"}function xb(e,n){return n==="todo"?[...e].sort((s,a)=>{const r=ph(s.priority,a.priority);return r!==0?r:s.createdAt!==a.createdAt?s.createdAt.localeCompare(a.createdAt):Lc(s.id,a.id)}):[...e].sort((s,a)=>{if(n==="done"){const o=fh(a)-fh(s);return o!==0?o:Lc(s.id,a.id)}if(n==="in-review"){const o=gh(s.status),l=gh(a.status);if(o!==l)return o?-1:1}const r=ph(s.priority,a.priority);return r!==0?r:Lc(s.id,a.id)})}function gC(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 bC({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 vb=i.createContext(null);function xC({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 Ml.createElement(vb.Provider,{value:d},e,Ml.createElement(bC,{isOpen:c!==null,options:c?.options??null,onConfirm:()=>l(!0),onCancel:()=>l(!1)}))}function ci(){const e=i.useContext(vb);return e||{confirm:async n=>!1}}function vC(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 yb({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(Js,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("a",{className:`card-github-badge ${vC(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,href:n.url,target:"_blank",rel:"noopener noreferrer",children:[t.jsx(ec,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function Yo(e,n){return`${e??"default"}:${n}`}class yC{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=Yo(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const a=Yo(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=Yo(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(Ii(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=Yo(this.projectId,l.taskId),d=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:bh(l,"prInfo")?l.prInfo??null:d?.prInfo,issueInfo:bh(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 Ca=new yC;let wC=0;function bh(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function wb(e){const n=i.useRef(null);n.current===null&&(n.current=`badge-hook-${wC++}`);const s=i.useSyncExternalStore(o=>Ca.subscribe(o),()=>Ca.getSnapshot(),()=>Ca.getSnapshot()),a=i.useCallback(o=>{Ca.subscribeTask(n.current,o)},[]),r=i.useCallback(o=>{Ca.unsubscribeTask(n.current,o)},[]);return i.useEffect(()=>{Ca.setProjectId(e??null)},[e]),i.useEffect(()=>()=>{Ca.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:a,unsubscribeFromBadge:r}}function Ol(e,n,s,a){return e===void 0||!n?s:!a||n>=a?e??void 0:s}function kC({taskId:e,prInfo:n,issueInfo:s,updatedAt:a,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:d}=wb(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=Ol(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??a),f=Ol(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??a);return!h&&!f?null:t.jsx(yb,{prInfo:h,issueInfo:f})}const jC=i.memo(kC);jC.displayName="TaskCardBadge";const si={data:new Map,pendingPromise:null,lastFetchTime:null},NC=5e3;function Sl(e,n){return n?`${n}::${e}`:e}function SC(e,n){const s=si.data.get(Sl(e,n));if(!(!s||Date.now()-s.timestamp>NC))return s}function CC(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 vN(c,e)}catch(h){u=h instanceof Error?h:new Error(String(h));const f=Ce(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=si.data.get(Sl(f,e));return p&&p.timestamp>u})&&si.lastFetchTime&&si.lastFetchTime>u)return;if(a.current&&(clearTimeout(a.current),a.current=null),si.pendingPromise){s(!0);try{await si.pendingPromise}finally{s(!1)}return}s(!0);const h=r(c);si.pendingPromise=h;try{const f=await h,p=Date.now();for(const[g,x]of Object.entries(f))si.data.set(Sl(g,e),{result:x,timestamp:p});si.lastFetchTime=p}catch{}finally{si.pendingPromise=null,s(!1)}},[r,e]),l=i.useCallback(c=>si.data.get(Sl(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:si.lastFetchTime,getBatchData:l}}const Xd=new Map,EC=3e4;function kb(e,n,s,a){return`${e}:${n??""}:${s??""}:${a??""}`}function _C(e,n,s,a){const r=kb(e,n,s,a),o=Xd.get(r);return o?Date.now()>o.expiresAt?(Xd.delete(r),null):o.stats:null}function MC(e,n,s,a,r){const o=kb(e,n,s,a);Xd.set(o,{stats:r,expiresAt:Date.now()+EC})}function AC(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 v(k=!1){if(!k){const E=_C(e,a,x,w);if(E){b||(m(E),f(!1));return}}f(!0);try{const E=await nb(e,x,a);b||(m(E.stats),MC(e,a,x,w,E.stats))}catch{b||m(null)}finally{b||f(!1)}}v();let N;return d&&g&&(N=setInterval(()=>{v(!0)},d)),()=>{b=!0,N&&clearInterval(N)}},[e,n,s,a,o,l,c,d]),{stats:u,loading:h}}const RC=new Set(["failed","stuck-killed"]);function zl(e,n,s){if(e.column!=="in-progress"||e.status&&RC.has(e.status)||!n||n<=0)return!1;const a=new Date(e.updatedAt).getTime();return(s??Date.now())-a>n}function PC(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function IC(e){return e==="done"||e==="skipped"}function TC(e,n,s){const a=s?.get(e)?.trim();if(a)return a;const r=n?.workflowStepName?.trim();return r||e}function jb(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:TC(d,u,n),status:u?PC(u.status):"pending",source:"workflow",phase:u?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(d=>IC(d.status)).length;return{total:l,completed:c,items:o}}function $C(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 Nb(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:$C(n)}})}function Sb(e){if(!e||e.length===0)return null;let n=0,s=0;for(const a of Nb(e))typeof a.durationMs=="number"&&(n+=a.durationMs,s+=1);return s>0?n:null}function La(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function Cb(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=La(r.startedAt);if(o==null)continue;let l;if(r.completedAt){const c=La(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 Eb(e,n,s){const a=La(e);if(a==null)return null;const r=La(n),o=r!=null&&r>=a?r:s;return Math.max(0,o-a)}function Lu(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 Zd=new Map;async function DC(e,n){const s=Zd.get(e);if(s)return s;try{const a=await sb(e,n);return Zd.set(e,a.title),a.title}catch{return e}}const xh=12;function LC(e){return e.length<=xh?e:e.slice(0,xh-3)+"..."}const eu=new Map;async function OC(e,n){const s=eu.get(e);if(s)return s;try{const a=await Yd(e,n);return eu.set(e,a.name),a.name}catch{return e}}function zC(e){return typeof e=="string"&&da.includes(e)?e:Ms}function FC(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}function _b(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 BC(e){return e.sourceType==="agent_heartbeat"||e.sourceType==="automation"||!!_b(e)}const UC=new Set(["triage","todo"]),vh=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]),yh=new Set(["merging","merging-pr","merging-fix"]),HC={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},qC=new Set(["in-progress","in-review","done"]),VC=3e4;function WC(e){return e==="merging-fix"?"Merging fixes…":e}function KC(e){const n=La(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function wh(e,n){const s=La(e.columnMovedAt??e.updatedAt);return s==null?null:Math.max(0,n-s)}function no(e,n){return Eb(e.executionStartedAt,e.executionCompletedAt,n)}function GC(e){return e.column==="done"?KC(e):null}function Mb(e,n){const s=La(e.updatedAt);return s==null?null:Math.max(0,n-s)}function JC(e,n){const s=no(e,n);if(s!=null)return s;const a=Mb(e,n),r=so(e,n);return r!=null?r+(a??0):a}function so(e,n){if(typeof e.timedExecutionMs=="number")return e.timedExecutionMs;const s=Sb(e.log),a=Cb(e.workflowStepResults,n);return s==null&&a==null?null:(s??0)+(a??0)}function kh(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 jh(e){if(!e)return null;const n=e.trim();return n.length>0?n:null}function YC(e){const n=jh(e.branch),s=jh(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 Nh(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 Sh(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 QC(e,n){return e.length!==n.length?!1:e.every((s,a)=>s.name===n[a]?.name&&s.status===n[a]?.status)}function Oc(e,n){return e.length!==n.length?!1:e.every((s,a)=>s===n[a])}function XC(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>s===n[a])}function ZC(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function eE(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 tE(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 nE(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 sE(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&&Oc(e.fanout?.dependentIds??[],n.fanout?.dependentIds??[])&&Oc(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&&tE(s.attachments,a.attachments)&&nE(s.comments,a.comments)&&Oc(s.dependencies,a.dependencies)&&QC(s.steps,a.steps)&&XC(s.enabledWorkflowSteps,a.enabledWorkflowSteps)&&eE(s.workflowStepResults,a.workflowStepResults)&&Sh(s.prInfo,a.prInfo)&&Sh(s.issueInfo,a.issueInfo)}function iE({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:v}){const[N,k]=i.useState(!1),[E,y]=i.useState(!1),[j,P]=i.useState(!1),[F,_]=i.useState(e.description||""),[R,L]=i.useState(!1),[U,C]=i.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(_e=>_e.status==="done"||_e.status==="skipped")),[$,V]=i.useState(null),[Y,ne]=i.useState(null),[q,A]=i.useState(!1),[I,D]=i.useState(!1),[S,G]=i.useState(()=>Date.now()),he=i.useRef(null),Se=i.useRef(!1),Ue=i.useRef(null),ce=i.useRef(null),[Ae,X]=i.useState(!1),{badgeUpdates:Z,subscribeToBadge:ee,unsubscribeFromBadge:le}=wb(n),{confirm:K}=ci(),O=i.useRef(null),pe=i.useRef(!1),ve=i.useCallback(_e=>_e instanceof Element?!!_e.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);i.useEffect(()=>{_(e.description||"")},[e.id,e.description]),i.useEffect(()=>{if(!q)return;const _e=it=>{ce.current&&!ce.current.contains(it.target)&&A(!1)};return document.addEventListener("click",_e),()=>document.removeEventListener("click",_e)},[q]),i.useEffect(()=>{if(!e.missionId){V(null);return}const _e=Zd.get(e.missionId);if(_e){V(_e);return}let it=!1;return DC(e.missionId,n).then(bt=>{it||V(bt)}),()=>{it=!0}},[e.missionId,n]),i.useEffect(()=>{if(!e.assignedAgentId){ne(null);return}const _e=eu.get(e.assignedAgentId);if(_e){ne(_e);return}ne(null);let it=!1;return OC(e.assignedAgentId,n).then(bt=>{it||ne(bt)}),()=>{it=!0}},[e.assignedAgentId,n]),i.useEffect(()=>{if(j&&he.current){const _e=he.current;_e.focus(),_e.style.height="auto",_e.style.height=_e.scrollHeight+"px"}},[j]),i.useEffect(()=>{if(typeof IntersectionObserver>"u"){X(!0);return}const _e=Ue.current;if(!_e)return;const it=new IntersectionObserver(([bt])=>{X(bt?.isIntersecting??!0)},{rootMargin:"200px"});return it.observe(_e),()=>it.disconnect()},[j,e.id]);const B=i.useCallback(_e=>{_e.dataTransfer.setData("text/plain",e.id),_e.dataTransfer.effectAllowed="move",k(!0)},[e.id]),we=i.useCallback(()=>{k(!1)},[]),ze=i.useCallback(_e=>_e.dataTransfer.types.includes("Files"),[]),re=i.useCallback(_e=>{ze(_e)&&(_e.preventDefault(),_e.stopPropagation(),_e.dataTransfer.dropEffect="copy",y(!0))},[ze]),He=i.useCallback(_e=>{ze(_e)&&(_e.preventDefault(),_e.stopPropagation(),y(!1))},[ze]),Pe=i.useCallback(async _e=>{if(!ze(_e))return;_e.preventDefault(),_e.stopPropagation(),y(!1);const it=Array.from(_e.dataTransfer.files);for(const bt of it)try{await lc(e.id,bt,n),r(`Attached ${bt.name} to ${e.id}`,"success")}catch(Rt){r(`Failed to attach ${bt.name}: ${Ce(Rt)}`,"error")}},[e.id,ze,r]),tt=i.useCallback(()=>{j||a(e)},[e,a,j]),qe=i.useCallback(_e=>{if(Se.current){Se.current=!1;return}ve(_e.target)||tt()},[tt,ve]),de=i.useCallback(_e=>{const it=_e.touches[0];it&&(O.current={x:it.clientX,y:it.clientY,time:Date.now()},pe.current=!1)},[]),De=i.useCallback(_e=>{if(!O.current)return;const it=_e.touches[0];if(!it)return;const bt=Math.abs(it.clientX-O.current.x),Rt=Math.abs(it.clientY-O.current.y);(bt>Ch||Rt>Ch)&&(pe.current=!0)},[]),Te=i.useCallback(_e=>{if(ve(_e.target)||!O.current)return;const bt=Date.now()-O.current.time<aE,Rt=!pe.current;bt&&Rt&&(Se.current=!0,tt()),O.current=null,pe.current=!1},[tt,ve]),ct=i.useCallback(async(_e,it)=>{_e.stopPropagation();try{const bt=await $a(it,n);a(bt)}catch{r(`Failed to load dependency ${it}`,"error")}},[a,r]),Ve=e.status==="failed",me=e.paused===!0,oe=!!(e.paused&&e.pausedByAgentId),Me=zC(e.priority),Xe=Me!==Ms,rt=zl(e,f,x),ht=e.column==="triage"&&e.status==="awaiting-approval",yt=e.column==="archived",Re=!o&&!s&&!Ve&&!me&&!rt&&!ht&&(e.column==="in-progress"||vh.has(e.status)),Ge=!b&&!s&&!me&&!j&&!yt,at=UC.has(e.column)&&!Re&&!me&&!s&&l,ie=!!(e.prInfo||e.issueInfo),Ke=e.sourceType==="github_import",je=i.useMemo(()=>YC(e),[e.id,e.branch,e.baseBranch]),Fe=!!(je.branch||je.baseBranch),Be=ZC(e.sourceMetadata),St=BC(e),ye=_b(e),kt=ye?`Created by agent: ${ye}`:"Created by agent",It=!!(e.assignedAgentId&&Y===null),Ie=i.useMemo(()=>{const _e=[];return e.modelProvider&&_e.push(e.modelProvider),e.validatorModelProvider&&!_e.includes(e.validatorModelProvider)&&_e.push(e.validatorModelProvider),e.planningModelProvider&&!_e.includes(e.planningModelProvider)&&_e.push(e.planningModelProvider),_e},[e.modelProvider,e.validatorModelProvider,e.planningModelProvider]),be=i.useMemo(()=>jb(e,w),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,w]),ot=be.total>0&&(e.status==="executing"||e.column==="in-progress");i.useEffect(()=>{if(e.column!=="in-progress"&&e.column!=="in-review")return;const _e=e.status!=null&&yh.has(e.status);if(e.column==="in-progress"){const bt=no(e,Date.now()),Rt=wh(e,Date.now()),se=so(e,Date.now());if(bt==null&&Rt==null&&se==null)return}if(!_e&&e.column==="in-review"){const bt=no(e,Date.now()),Rt=so(e,Date.now());if(bt==null&&Rt==null)return}G(Date.now());const it=window.setInterval(()=>{G(Date.now())},VC);return()=>window.clearInterval(it)},[e.column,e.status,e.columnMovedAt,e.updatedAt,e.workflowStepResults,e.timedExecutionMs,e.executionStartedAt,e.executionCompletedAt]);const gt=i.useMemo(()=>{if(!qC.has(e.column))return null;if(e.status!=null&&yh.has(e.status)){const te=JC(e,S);if(te!=null){const Oe=Nh(te);if(Oe){const mt=Mb(e,S),Pt=mt==null?null:kh(mt),sn=Pt?`Execution time ${Oe}. Merge phase ${Pt}`:`Execution time ${Oe}. Merging`;return{label:Oe,title:sn,ariaLabel:sn}}}}if(e.column==="in-progress"){const te=no(e,S)??wh(e,S)??so(e,S);if(te==null)return null;const Oe=kh(te);return Oe?{label:Oe,title:`In progress ${Oe}`,ariaLabel:`In progress ${Oe}`}:null}const it=no(e,S)??so(e,S);if(it==null)return null;const bt=Nh(it);if(!bt)return null;const Rt=GC(e);if(Rt==null)return{label:bt,title:`Execution time ${bt}`,ariaLabel:`Execution time ${bt}`};const se=new Date(Rt).toLocaleString();return{label:bt,title:`Execution time ${bt}. Completed ${se}`,ariaLabel:`Execution time ${bt}. Completed ${se}`}},[e.column,e.status,e.columnMovedAt,e.timedExecutionMs,e.updatedAt,e.workflowStepResults,e.log,e.executionStartedAt,e.executionCompletedAt,S]);i.useEffect(()=>{if(!ie||!Ae){le(e.id);return}return ee(e.id),()=>{le(e.id)}},[ie,Ae,ee,e.id,le]);const xt=Z.get(`${n??"default"}:${e.id}`),jt=e.column==="in-progress"||e.column==="in-review",Bt=i.useMemo(()=>e.steps.map(_e=>`${_e.name}:${_e.status}`).join("|"),[e.steps]),{stats:Jt}=AC(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:Ae,worktree:e.worktree,stepVersion:jt?Bt:void 0,pollIntervalMs:jt?3e4:void 0}),Vt=i.useMemo(()=>SC(e.id,n),[e.id,n]),pn=i.useMemo(()=>{const _e=xt?.prInfo,it=xt?.timestamp,bt=Vt?.result?.prInfo,Rt=Vt?.timestamp?new Date(Vt.timestamp).toISOString():void 0,se=e.prInfo,te=e.prInfo?.lastCheckedAt??e.updatedAt;let Oe=Ol(_e,it,se,te);const mt=it&&it>=te?it:te;return bt&&Rt&&(!mt||Rt>mt)&&(Oe=bt),Oe},[xt,Vt,e.prInfo,e.updatedAt]),Xt=i.useMemo(()=>{const _e=xt?.issueInfo,it=xt?.timestamp,bt=Vt?.result?.issueInfo,Rt=Vt?.timestamp?new Date(Vt.timestamp).toISOString():void 0,se=e.issueInfo,te=e.issueInfo?.lastCheckedAt??e.updatedAt;let Oe=Ol(_e,it,se,te);const mt=it&&it>=te?it:te;return bt&&Rt&&(!mt||Rt>mt)&&(Oe=bt),Oe},[xt,Vt,e.issueInfo,e.updatedAt]),mn=i.useCallback(_e=>{_e?.stopPropagation(),!(!at||R)&&(P(!0),_(e.description||""))},[at,R,e.description]),Ht=i.useCallback(()=>{P(!1),_(e.description||"")},[e.description]),Zt=i.useCallback(()=>F!==(e.description||""),[F,e.description]),tn=i.useCallback(async()=>{if(!(!l||R)){if(!Zt()){Ht();return}L(!0);try{await l(e.id,{description:F.trim()||void 0}),r(`Updated ${e.id}`,"success"),P(!1)}catch(_e){r(`Failed to update ${e.id}: ${Ce(_e)}`,"error")}finally{L(!1)}}},[l,e.id,F,R,Zt,Ht,r]),dn=i.useCallback(_e=>{_e.key==="Enter"&&!_e.shiftKey?(_e.preventDefault(),tn()):_e.key==="Escape"&&(_e.preventDefault(),Ht())},[tn,Ht]),qt=i.useCallback(()=>{setTimeout(()=>{const _e=document.activeElement;_e===he.current||_e?.closest(".card-editing-content")||(Zt()?tn():Ht())},0)},[Zt,tn,Ht]),ke=i.useCallback(_e=>{at&&(_e.stopPropagation(),mn(_e))},[at,mn]),$e=i.useCallback(_e=>{_e.stopPropagation(),mn(_e)},[mn]),Ye=i.useCallback(_e=>{_(_e.target.value);const it=_e.target;it.style.height="auto",it.style.height=it.scrollHeight+"px"},[]),ut=i.useCallback(_e=>{_e.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch(it=>{r(`Failed to archive ${e.id}: ${Ce(it)}`,"error")})},[r,c,e.id]),We=i.useCallback(_e=>{_e.stopPropagation(),d&&d(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch(it=>{r(`Failed to unarchive ${e.id}: ${Ce(it)}`,"error")})},[r,d,e.id]),$t=i.useCallback(async _e=>{if(_e.stopPropagation(),!(!u||!await K({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0})))try{await u(e.id),r(`Deleted ${e.id}`,"success")}catch(bt){const Rt=Lu(bt);if(!Rt||Rt.dependentIds.length===0){r(`Failed to delete ${e.id}: ${Ce(bt)}`,"error");return}const se=Rt.dependentIds.join(", ");if(!await K({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(Oe){r(`Failed to delete ${e.id}: ${Ce(Oe)}`,"error")}}},[r,K,u,e.id]),At=i.useCallback(_e=>{_e.stopPropagation(),h?.(e,"changes")},[e,h]),wt=i.useCallback(_e=>{_e.stopPropagation(),C(it=>!it)},[]),zt=i.useCallback(_e=>{_e.stopPropagation(),e.missionId&&p&&p(e.missionId)},[e.missionId,p]),Lt=i.useCallback(_e=>{_e.stopPropagation(),A(it=>!it)},[]),Ot=i.useCallback(async(_e,it)=>{if(_e.stopPropagation(),A(!1),!!g)try{const bt=e.steps.some(te=>te.status!=="pending"),Rt=(it==="todo"||it==="triage")&&bt;let se;if(Rt){if(await K({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 K({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 ${cs[it]}`,"success")}catch(bt){r(`Failed to move ${e.id}: ${Ce(bt)}`,"error")}},[r,K,g,e.id,e.steps]),nn=i.useCallback(async _e=>{if(_e.stopPropagation(),!(!m||I)){D(!0);try{await m(e.id)}catch(it){r(`Failed to retry ${e.id}: ${Ce(it)}`,"error")}finally{D(!1)}}},[r,I,m,e.id]),Yt=`card${N?" dragging":""}${s?" queued":""}${Re?" agent-active":""}${Ve?" failed":""}${me?" paused":""}${rt?" stuck":""}${ht?" awaiting-approval":""}${E?" file-drop-target":""}${j?" card-editing":""}${R?" card-saving":""}`,rn=(()=>{if(e.column==="in-progress"){const _e=Jt?.filesChanged,it=_e==null||_e===0?e.modifiedFiles?.length:void 0,bt=_e!=null&&_e>0?_e:it;return bt==null||bt===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:At,disabled:!h,children:[t.jsx(ys,{size:12}),t.jsxs("span",{children:[bt," ",bt===1?"file":"files"," changed"]})]})}if(e.column==="in-review"){const _e=Jt?.filesChanged,it=_e==null||_e===0?e.modifiedFiles?.length:void 0,bt=_e!=null&&_e>0?_e:it;return bt==null||bt===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:At,disabled:!h,children:[t.jsx(ys,{size:12}),t.jsxs("span",{children:[bt," ",bt===1?"file":"files"," changed"]})]})}if(e.column==="done"){const _e=Jt?.filesChanged,it=e.mergeDetails?.filesChanged,bt=_e??it;if(bt!=null&&bt>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:At,disabled:!h,children:[t.jsx(ys,{size:12}),t.jsxs("span",{children:[bt," ",bt===1?"file":"files"," changed"]})]});const Rt=e.modifiedFiles?.length;if(Rt!=null&&Rt>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:At,disabled:!h,children:[t.jsx(ys,{size:12}),t.jsxs("span",{children:[Rt," ",Rt===1?"file":"files"," changed"]})]})}return null})();return j?t.jsx("div",{ref:Ue,className:Yt,"data-id":e.id,"data-column":e.column,onDoubleClick:ke,children:t.jsxs("div",{className:"card-editing-content",children:[t.jsx("textarea",{ref:he,className:"card-edit-desc-textarea",placeholder:"Task description",value:F,onChange:Ye,onKeyDown:dn,onBlur:qt,disabled:R,rows:4}),R&&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:Ue,className:Yt,"data-id":e.id,"data-column":e.column,draggable:Ge,onDragStart:Ge?B:void 0,onDragEnd:Ge?we:void 0,onDragOver:re,onDragLeave:He,onDrop:Pe,onClick:qe,onTouchStart:de,onTouchMove:De,onTouchEnd:Te,onDoubleClick:ke,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:oe?"paused by agent":"paused"}),!me&&e.status&&e.status!=="queued"&&t.jsx("span",{className:`card-status-badge card-status-badge--${e.column}${ht?" awaiting-approval":""}${vh.has(e.status)?" pulsing":""}${Ve?" failed":""}${rt?" stuck":""}`,children:rt?"Stuck":ht?"Awaiting Approval":WC(e.status)}),rt&&(me||!e.status||e.status==="queued")&&t.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),ie&&t.jsx(yb,{prInfo:pn,issueInfo:Xt}),St&&t.jsxs("span",{className:"card-agent-created-badge",title:kt,"aria-label":kt,children:[t.jsx(Vn,{size:11,"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:kt}),t.jsx("span",{"aria-hidden":"true",children:"Agent"})]}),Xe&&t.jsx("span",{className:`card-priority-badge card-priority-badge--${Me}`,children:Me}),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(is,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),e.missionId&&t.jsxs("span",{className:"card-mission-badge",onClick:zt,title:`Mission: ${$??e.missionId}`,role:p?"button":void 0,tabIndex:p?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.jsx(js,{size:11}),LC($??e.missionId)]}),t.jsxs("div",{className:"card-header-actions",children:[at&&t.jsx("button",{className:"card-edit-btn",onClick:$e,title:"Edit task","aria-label":"Edit task",children:t.jsx(Os,{size:12})}),e.column==="triage"&&u&&t.jsx("button",{className:"card-delete-btn",onClick:$t,title:"Delete task","aria-label":"Delete task",children:t.jsx(Sn,{size:12})}),e.column==="done"&&c&&t.jsx("button",{className:"card-archive-btn",onClick:ut,title:"Archive task","aria-label":"Archive task",children:"Archive"}),e.column==="archived"&&d&&t.jsx("button",{className:"card-unarchive-btn",onClick:We,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),e.column==="in-progress"&&g&&t.jsxs("div",{className:"card-send-back",ref:ce,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:Lt,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":q,children:["Send back",t.jsx(un,{size:10})]}),q&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:Qd["in-progress"].filter(_e=>_e!=="in-review").map(_e=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:it=>Ot(it,_e),children:cs[_e]},_e))})]}),e.column==="in-review"&&g&&t.jsxs("div",{className:"card-send-back",ref:ce,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:Lt,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":q,children:["Move",t.jsx(un,{size:10})]}),q&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:Qd["in-review"].map(_e=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:it=>Ot(it,_e),children:_e==="done"?"Done (no merge)":cs[_e]},_e))})]}),e.size&&t.jsx("span",{className:`card-size-badge size-${e.size.toLowerCase()}`,children:e.size})]})]}),Ve&&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:nn,disabled:I,children:[t.jsx(bk,{size:12}),I?"Retrying…":"Retry"]})]}),t.jsx("div",{className:"card-title",title:e.title||e.description||void 0,children:_h(e.title,Eh)||_h(e.description,Eh)||e.id}),Fe&&t.jsxs("div",{className:"card-branch-row","aria-label":"Branch metadata",children:[je.branch&&t.jsxs("span",{className:"card-branch-chip",title:je.branch,children:[t.jsx("span",{className:"card-branch-label",children:"Branch"}),t.jsx("span",{className:"card-branch-value",children:je.branch})]}),je.baseBranch&&t.jsxs("span",{className:"card-branch-chip",title:je.baseBranch,children:[t.jsx("span",{className:"card-branch-label",children:"Base"}),t.jsx("span",{className:"card-branch-value",children:je.baseBranch})]})]}),ot&&(()=>{const _e=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:`${_e}%`,backgroundColor:HC[e.column]}})}),t.jsxs("span",{className:"card-progress-label",children:[be.completed,"/",be.total]})]}),t.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:wt,"aria-expanded":U,"aria-label":U?"Hide steps":"Show steps",children:[t.jsxs("span",{children:[be.total," step",be.total===1?"":"s"]}),t.jsx(un,{size:14,className:`card-steps-toggle-icon${U?" expanded":""}`})]}),U&&t.jsx("div",{className:"card-steps-list",children:be.items.map(it=>{const bt=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}${bt?" 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)})})]})})(),(rn||gt||Ke)&&t.jsxs("div",{className:"card-footer-row",children:[rn,Ke&&t.jsx("span",{className:"card-source-provenance",title:Be?`Imported from GitHub: ${Be}`:"Imported from GitHub","aria-label":"Imported from GitHub",children:t.jsx(Tn,{provider:"github",size:"sm"})}),gt&&t.jsxs("span",{className:"card-time-indicator",title:gt.title,"aria-label":gt.ariaLabel,children:[t.jsx(Wi,{size:12}),t.jsx("span",{children:gt.label})]})]}),(e.dependencies&&e.dependencies.length>0||s||e.status==="queued"||e.blockedBy||v&&v.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(_e=>t.jsxs("span",{className:"card-dep-badge clickable",onClick:it=>void ct(it,_e),title:`Click to view ${_e}`,children:[t.jsx(pr,{size:12,style:{verticalAlign:"middle"}})," ",_e]},_e))}),e.blockedBy&&t.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${e.blockedBy} (file overlap)`,children:[t.jsx(Ia,{size:12,style:{verticalAlign:"middle"}})," ",e.blockedBy]}),v&&v.totalCount>0&&t.jsxs("span",{className:`card-fanout-badge${v.staleBlockedByDependentIds.length>0?" card-fanout-badge--stale":""}`,"data-tooltip":`Blocking ${v.totalCount} task(s); ${v.activeTodoCount} waiting in todo`,children:[t.jsx(Ps,{size:12,style:{verticalAlign:"middle"}}),t.jsxs("span",{children:["Blocks ",t.jsx("span",{className:"card-fanout-count",children:v.totalCount}),v.staleBlockedByDependentIds.length>0?` (${v.staleBlockedByDependentIds.length} stale)`:""]})]}),(s||e.status==="queued")&&e.column!=="in-progress"&&t.jsxs("span",{className:"queued-badge",children:[t.jsx(Wi,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),(e.assignedAgentId||Ie.length>0)&&t.jsxs("div",{className:"card-agent-row",children:[Ie.length>0&&t.jsx("span",{className:"card-provider-icons","data-testid":"card-provider-icons",children:Ie.map(_e=>t.jsx(Tn,{provider:_e,size:"sm"},_e))}),e.assignedAgentId&&t.jsxs("span",{className:`card-agent-badge${It?" card-agent-badge--loading":""}`,title:`Assigned to ${Y??e.assignedAgentId}`,children:[t.jsx(Vn,{size:11}),t.jsx("span",{className:"card-agent-badge-text","aria-hidden":"true",children:FC(Y??e.assignedAgentId,15)}),t.jsxs("span",{className:"visually-hidden",children:["Assigned to ",Y??e.assignedAgentId]})]})]}),t.jsx(ia,{slotId:"task-card-badge",projectId:n})]})}const Ch=10,aE=300,Eh=140;function _h(e,n){return e?e.length>n?e.slice(0,n)+"…":e:""}const yo=i.memo(iE,sE);yo.displayName="TaskCard";function rE({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(Iy,{size:14}):t.jsx(Ps,{size:14})}),t.jsx("span",{className:"worktree-label",children:e})]}),n.map(x=>t.jsx(yo,{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(yo,{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 Ab=i.memo(rE);Ab.displayName="WorktreeGroup";function Mh(e){return e.toLowerCase().replace(/[-_./]/g,"")}function oE(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 lE(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 cE(e,n){const s=Mh(e),a=Mh(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&&oE(s,o)||s.length>=4&&lE(s,o,1))return!0;return!1}function dE(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=>cE(o,r))})}function Ns({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,v]=i.useState(0),[N,k]=i.useState(null),[E,y]=i.useState(null),j=i.useRef(null),P=i.useRef(null),F=i.useRef(null),_=i.useRef(null),R=i.useRef(null),L=i.useMemo(()=>dE(e,x),[e,x]),U=i.useMemo(()=>L.reduce((ee,le)=>((ee[le.provider]??=[]).push(le),ee),{}),[L]),C=i.useMemo(()=>{const ee=[];for(const le of u){const K=le.indexOf("/");if(K===-1)continue;const O=le.slice(0,K),pe=le.slice(K+1),ve=L.find(B=>B.provider===O&&B.id===pe);ve&&ee.push({model:ve,fullId:le})}return ee},[u,L]),$=i.useMemo(()=>{const ee=Object.entries(U),le=new Set(c);return ee.sort(([K],[O])=>{const pe=le.has(K),ve=le.has(O);if(pe&&!ve)return-1;if(!pe&&ve)return 1;if(pe&&ve){const B=c.indexOf(K),we=c.indexOf(O);if(B!==we)return B-we}return K.localeCompare(O)})},[U,c]),V=typeof h=="string"&&h.length>0,Y=i.useMemo(()=>{if(!n||V&&n===h)return null;const ee=n.indexOf("/");return ee===-1?null:n.slice(0,ee)},[V,h,n]),ne=i.useMemo(()=>{const ee=[];return V&&ee.push({type:"no-change",value:h,label:f}),ee.push({type:"default",value:"",label:"Use default"}),ee},[V,f,h]),q=i.useMemo(()=>{const ee=[...ne];for(const{model:le,fullId:K}of C)ee.push({type:"favorite",value:K,label:le.name,provider:le.provider});return $.forEach(([le,K])=>{ee.push({type:"provider",value:`__group_${le}`,label:le,provider:le}),K.forEach(O=>{ee.push({type:"model",value:`${O.provider}/${O.id}`,label:O.name,provider:O.provider})})}),ee},[C,$,ne]),A=i.useMemo(()=>{if(V&&n===h)return f;if(!n)return"Use default";const ee=n.indexOf("/");if(ee===-1)return n;const le=n.slice(0,ee),K=n.slice(ee+1);return e.find(pe=>pe.provider===le&&pe.id===K)?.name||n},[V,f,h,n,e]),I=i.useMemo(()=>q.findIndex(ee=>ee.value===n),[q,n]),D=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}},[]),S=i.useCallback(()=>{const{height:ee}=D(),le=typeof window.matchMedia=="function",K=le?window.matchMedia("(max-width: 640px)").matches:!1,O=le?window.matchMedia("(max-width: 768px)").matches:!1;return ee<=0?320:K?Math.min(ee*.6,360):O?Math.min(ee*.7,420):320},[D]),G=i.useCallback(()=>{const ee=P.current;if(!ee)return;const le=ee.getBoundingClientRect(),{width:K,height:O,offsetTop:pe,offsetLeft:ve}=D(),B=16,we=16,ze=4,re=S(),He=le.bottom-pe,Pe=le.top-pe,tt=le.left-ve,qe=O-He,de=Pe,De=Math.max(qe-we-ze,160),Te=Math.max(de-we-ze,160),ct=qe<re&&de>qe,Ve=Math.max(Math.min(ct?Te:De,re),160),me=Math.min(le.width,K-B*2),oe=Math.min(Math.max(tt,B),K-B-me)+ve,Me=ct?Math.max(we+pe,Pe-Ve-ze+pe):Math.min(He+ze+pe,O+pe-we-Ve);k({top:Me,left:oe,width:me,maxHeight:Ve})},[D,S]);i.useEffect(()=>{y(document.body)},[]);const he=i.useRef(!1);i.useEffect(()=>{if(!p){he.current=!1;return}if(he.current||q.length===0)return;const ee=q.findIndex((le,K)=>K>=(I>=0?I:0)&&le.type!=="provider");v(ee>=0?ee:0),he.current=!0},[p,q,I]),i.useEffect(()=>{p&&he.current&&(v(0),R.current&&(R.current.scrollTop=0))},[x,p]),i.useEffect(()=>{if(!p)return;G();const ee=requestAnimationFrame(()=>_.current?.focus());return()=>cancelAnimationFrame(ee)},[p,G]),i.useEffect(()=>{if(!p)return;const ee=()=>G();window.addEventListener("resize",ee),window.addEventListener("scroll",ee,!0);const le=window.visualViewport;return le&&(le.addEventListener("resize",ee),le.addEventListener("scroll",ee)),()=>{window.removeEventListener("resize",ee),window.removeEventListener("scroll",ee,!0),le&&(le.removeEventListener("resize",ee),le.removeEventListener("scroll",ee))}},[p,G]),i.useEffect(()=>{if(!p)return;const ee=le=>{const K=le.target,O=j.current?.contains(K),pe=F.current?.contains(K);!O&&!pe&&(g(!1),w(""))};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[p]);const Se=i.useCallback(ee=>{switch(ee.key){case"ArrowDown":if(ee.preventDefault(),!p)g(!0);else{let le=b;for(let K=1;K<=q.length;K++){const O=(b+K)%q.length;if(q[O]?.type!=="provider"){le=O;break}}v(le)}break;case"ArrowUp":if(ee.preventDefault(),p){let le=b;for(let K=1;K<=q.length;K++){const O=(b-K+q.length)%q.length;if(q[O]?.type!=="provider"){le=O;break}}v(le)}break;case"Enter":if(ee.preventDefault(),p){const le=q[b];le&&le.type!=="provider"&&le.type!=="favorite"&&(s(le.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,q,s]),Ue=i.useCallback(ee=>{s(ee),g(!1),w("")},[s]),ce=i.useCallback(()=>{w(""),_.current?.focus()},[]),Ae=i.useCallback(()=>{r||g(ee=>!ee)},[r]);i.useEffect(()=>{if(p&&R.current){const ee=R.current.querySelector(`[data-index="${b}"]`);ee&&typeof ee.scrollIntoView=="function"&&ee.scrollIntoView({block:"nearest"})}},[b,p]);const X=x.length>0,Z=p&&N?t.jsxs("div",{ref:F,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:Se,style:{top:`${N.top}px`,left:`${N.left}px`,width:`${N.width}px`,maxHeight:`${N.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()}),X&&t.jsx("button",{type:"button",className:"model-combobox-clear",onClick:ce,"aria-label":"Clear filter",children:"×"})]}),t.jsxs("div",{className:"model-combobox-results-count",children:[L.length," model",L.length!==1?"s":""]}),t.jsxs("div",{ref:R,className:"model-combobox-list",children:[ne.map((ee,le)=>t.jsx("div",{"data-index":le,className:`model-combobox-option ${b===le?"model-combobox-option--highlighted":""} ${n===ee.value?"model-combobox-option--selected":""}`,onClick:()=>Ue(ee.value),onMouseEnter:()=>v(le),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}`)),C.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"model-combobox-divider"}),C.map(({model:ee,fullId:le},K)=>{const O=K+ne.length,pe=b===O,ve=n===le;return t.jsxs("div",{"data-index":O,className:`model-combobox-option model-combobox-option--favorite ${pe?"model-combobox-option--highlighted":""} ${ve?"model-combobox-option--selected":""}`,onClick:()=>Ue(le),onMouseEnter:()=>v(O),role:"option","aria-selected":ve,children:[t.jsxs("span",{className:"model-combobox-option-main",children:[t.jsx("span",{className:"model-combobox-option-icon",children:t.jsx(Tn,{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(le)},title:"Remove from favorites","aria-label":`Remove ${ee.name} from favorites`,children:"★"})]},le)}),t.jsx("div",{className:"model-combobox-divider"})]}),$.map(([ee,le])=>{const K=q.findIndex(ve=>ve.value===`__group_${ee}`),O=c.includes(ee),pe=le.filter(ve=>{const B=`${ve.provider}/${ve.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":K,children:[t.jsx(Tn,{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 ${O?"model-combobox-optgroup-favorite--active":""}`,onClick:ve=>{ve.stopPropagation(),d(ee)},title:O?"Remove from favorites":"Add to favorites","aria-label":O?`Remove ${ee} from favorites`:`Add ${ee} to favorites`,children:"★"})]}),pe.map(ve=>{const B=`${ve.provider}/${ve.id}`,we=q.findIndex(Pe=>Pe.value===B),ze=b===we,re=n===B,He=u.includes(B);return t.jsxs("div",{"data-index":we,className:`model-combobox-option ${ze?"model-combobox-option--highlighted":""} ${re?"model-combobox-option--selected":""}`,onClick:()=>Ue(B),onMouseEnter:()=>v(we),role:"option","aria-selected":re,children:[t.jsx("span",{className:"model-combobox-option-text",children:ve.name}),t.jsx("span",{className:"model-combobox-option-id",children:ve.id}),m&&t.jsx("button",{type:"button",className:`model-combobox-option-favorite ${He?"model-combobox-option-favorite--active":""}`,onClick:Pe=>{Pe.stopPropagation(),m(B)},title:He?"Remove from favorites":"Add to favorites","aria-label":He?`Remove ${ve.name} from favorites`:`Add ${ve.name} to favorites`,children:He?"★":"☆"})]},B)})]},ee)}),L.length===0&&X&&t.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",x,"'"]})]})]}):null;return t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:j,className:"model-combobox",onKeyDown:Se,children:t.jsxs("button",{ref:P,type:"button",id:o,className:"model-combobox-trigger",onClick:Ae,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":l,children:[Y&&t.jsx("span",{className:"model-combobox-trigger-icon",children:t.jsx(Tn,{provider:Y,size:"sm"})}),t.jsx("span",{className:"model-combobox-trigger-text",children:A||a}),t.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),E&&Z?_a.createPortal(Z,E):null]})}function Ou(e,n){return typeof n!="string"||n.length===0?e:`kb:${n}:${e}`}function Fn(e,n){if(typeof window>"u")return null;const s=window.localStorage?.getItem;return typeof s!="function"?null:s.call(window.localStorage,Ou(e,n))}function ds(e,n,s){if(typeof window>"u")return;const a=window.localStorage?.setItem;typeof a=="function"&&a.call(window.localStorage,Ou(e,s),n)}function vr(e,n){if(typeof window>"u")return;const s=window.localStorage?.removeItem;typeof s=="function"&&s.call(window.localStorage,Ou(e,n))}const uE=1e4,mE=1e3;function uc(){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 $l();n(b)}catch(b){o(b instanceof Error?b.message:"Failed to fetch nodes")}},[]);i.useEffect(()=>{let b=!1;async function v(){a(!0);try{const k=await $l();b||(n(k),o(null))}catch(k){b||o(k instanceof Error?k.message:"Failed to fetch nodes")}finally{b||a(!1)}}v();const N=()=>{if(document.visibilityState!=="visible")return;const k=Date.now();k-c.current<mE||(c.current=k,d())};return document.addEventListener("visibilitychange",N),()=>{b=!0,document.removeEventListener("visibilitychange",N)}},[d]),i.useEffect(()=>{if(!s)return l.current=setInterval(()=>{d()},uE),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,d]);const u=i.useCallback(async b=>{const{projectMappings:v,...N}=b,k=await US(N);if(v.length>0)try{await E0(k.id,v)}catch(E){const y=E instanceof Error?E.message:"Failed to persist project mappings";let j="";try{await Bm(k.id)}catch(P){j=P instanceof Error?P.message:"Failed to unregister node after mapping failure"}throw await d(),j?new Error(`${y}. Cleanup also failed: ${j}`):new Error(y)}return await d(),k},[d]),m=i.useCallback(async(b,v)=>{const N=await qS(b,v);return n(k=>k.map(E=>E.id===b?N:E)),N},[]),h=i.useCallback(async b=>{await Bm(b),n(v=>v.filter(N=>N.id!==b))},[]),f=i.useCallback(async b=>{const v=await GS(b);n(N=>N.map(k=>k.id===b?{...k,status:v.status,updatedAt:v.checkedAt}:k))},[]),p=i.useCallback(b=>VS(b),[]),g=i.useCallback(async(b,v)=>{const N=await WS(b,v);return n(k=>k.map(E=>E.id===b?{...E,dockerConfig:N}:E)),N},[]),x=i.useCallback(async b=>{const v=await KS(b);return"persistedVersion"in v?v:{persistedVersion:0,deployedVersion:null,needsRecreate:!1}},[]),w=i.useCallback(async b=>HS(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 Fr="kb-quick-entry-text",hE=["image/png","image/jpeg","image/gif","image/webp"];function pE(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function zc(e,n){return e&&n?`${e}/${n}`:""}function Fc(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 Rb({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"&&Fn(Fr,l)||""),[g,x]=i.useState(!1),[w,b]=i.useState(!1),[v,N]=i.useState(!1),k=i.useRef(null),E=i.useRef(null),y=i.useRef(!1),j=i.useRef(l),[P,F]=i.useState([]),_=i.useRef([]),[R,L]=i.useState([]),[U,C]=i.useState(!1),[$,V]=i.useState(""),[Y,ne]=i.useState(null),[q,A]=i.useState([]),[I,D]=i.useState(void 0),[S,G]=i.useState(!1),[he,Se]=i.useState(!1),[Ue,ce]=i.useState(!1),[Ae,X]=i.useState(!1),[Z,ee]=i.useState(!1),[le,K]=i.useState(null),[O,pe]=i.useState(void 0),[ve,B]=i.useState(void 0),[we,ze]=i.useState(void 0),[re,He]=i.useState(void 0),[Pe,tt]=i.useState(void 0),[qe,de]=i.useState(void 0),De=i.useRef(null),Te=i.useRef(null),ct=i.useRef(null),Ve=i.useRef(null),me=i.useRef(null),oe=i.useRef(null),Me=i.useRef(null),Xe=i.useRef(null),[rt,ht]=i.useState(null),[yt,Re]=i.useState(null),[Ge,at]=i.useState(null),[ie,Ke]=i.useState(null),je=i.useRef(null),Fe=i.useRef(null),[Be,St]=i.useState(null),[ye]=i.useState(()=>typeof document<"u"?document.body:null),[kt,It]=i.useState(!1),[Ie,be]=i.useState(null),[ot,gt]=i.useState(a??[]),[xt,jt]=i.useState([]),[Bt,Jt]=i.useState([]),[Vt,pn]=i.useState(null),[Xt,mn]=i.useState(void 0),[Ht,Zt]=i.useState(!1),[tn,dn]=i.useState(Ms),[qt,ke]=i.useState(void 0),{nodes:$e}=uc(),[Ye,ut]=i.useState(!1),[We,$t]=i.useState(!1),At=i.useRef(null),wt=i.useRef(null),[zt,Lt]=i.useState(null),Ot=d??xt,nn=u??Bt,Yt=!e;i.useEffect(()=>{if(a)gt(a),It(!1),be(null);else{let Q=!1;return It(!0),be(null),Fs().then(M=>{Q||(gt(M.models),d||jt(M.favoriteProviders),u||Jt(M.favoriteModels))}).catch(M=>{Q||be(Ce(M)||"Failed to load models")}).finally(()=>{Q||It(!1)}),oc(l).then(M=>{Q||pn(M)}).catch(()=>{}),()=>{Q=!0}}},[a,d,u,l]);const rn=zc(O,ve),_e=zc(we,re),it=zc(Pe,qe),bt=!!(O&&ve),Rt=!!(we&&re),se=!!(Pe&&qe),te=Number(bt)+Number(Rt)+Number(se),Oe=Xt?Vt?.modelPresets?.find(Q=>Q.id===Xt)?.name??"Models":te>0?`${te} model${te===1?"":"s"}`:"Models",mt=i.useCallback((Q,M)=>{if(!Q||!M)return"Using default";const ue=ot.find(Ee=>Ee.provider===Q&&Ee.id===M);return ue?`${ue.provider}/${ue.id}`:`${Q}/${M}`},[ot]);i.useEffect(()=>{p(Fn(Fr,l)||"")},[l]),i.useEffect(()=>{typeof window<"u"&&ds(Fr,f,l)},[f,l]),i.useEffect(()=>{j.current!==l&&(j.current=l,A([]),D(void 0),ne(null),G(!1),ht(null))},[l]),i.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),i.useEffect(()=>{_.current=P},[P]),i.useEffect(()=>()=>{_.current.forEach(Q=>URL.revokeObjectURL(Q.previewUrl))},[]);const Pt=i.useCallback(()=>{const Q=k.current;if(!Q)return;Q.style.height="auto";const M=Math.min(Q.scrollHeight,200);Q.style.height=`${M}px`},[]);i.useEffect(()=>{w&&Pt()},[f,w,Pt]),i.useEffect(()=>{if(!g&&f===""&&k.current){const Q=setTimeout(()=>{k.current?.focus()},0);return()=>clearTimeout(Q)}},[g,f]),i.useEffect(()=>{U||V("")},[U]),i.useEffect(()=>{if(!Ye)return;const Q=M=>{const ue=M.target,Ee=At.current?.contains(ue),z=wt.current?.contains(ue);!Ee&&!z&&ut(!1)};return document.addEventListener("mousedown",Q),()=>document.removeEventListener("mousedown",Q)},[Ye]),i.useEffect(()=>{if(!Z)return;const Q=M=>{const ue=M.target,Ee=De.current?.contains(ue),z=Te.current?.contains(ue),ge=ue instanceof Element&&ue.closest?.(".model-combobox-dropdown--portal")!=null;!Ee&&!z&&!ge&&(ee(!1),K(null))};return document.addEventListener("mousedown",Q),()=>document.removeEventListener("mousedown",Q)},[Z]),i.useEffect(()=>{if(!he)return;const Q=M=>{const ue=M.target;me.current?.contains(ue)||oe.current?.contains(ue)||(Se(!1),Re(null))};return document.addEventListener("mousedown",Q),()=>document.removeEventListener("mousedown",Q)},[he]),i.useEffect(()=>{if(!S)return;const Q=M=>{const ue=M.target;ct.current?.contains(ue)||Ve.current?.contains(ue)||(G(!1),ht(null))};return document.addEventListener("mousedown",Q),()=>document.removeEventListener("mousedown",Q)},[S]),i.useEffect(()=>{if(!Ue)return;const Q=M=>{const ue=M.target;Me.current?.contains(ue)||Xe.current?.contains(ue)||(ce(!1),at(null))};return document.addEventListener("mousedown",Q),()=>document.removeEventListener("mousedown",Q)},[Ue]);const sn=i.useCallback(()=>{P.forEach(Q=>URL.revokeObjectURL(Q.previewUrl)),F([]),E.current&&(E.current.value=""),p(""),L([]),ne(null),G(!1),ht(null),Se(!1),Re(null),ce(!1),at(null),pe(void 0),B(void 0),ze(void 0),He(void 0),tt(void 0),de(void 0),mn(void 0),Zt(!1),dn(Ms),ke(void 0),C(!1),ee(!1),Ke(null),K(null),ut(!1),$t(!1),b(!1),N(!1),y.current=!0,k.current&&(k.current.style.height="auto"),typeof window<"u"&&vr(Fr,l)},[P,l]),In=i.useCallback(Q=>{if(!Q||Q.length===0)return;const M=[];for(let ue=0;ue<Q.length;ue++){const Ee=Q[ue];hE.includes(Ee.type)&&M.push({file:Ee,previewUrl:URL.createObjectURL(Ee)})}M.length>0&&F(ue=>[...ue,...M])},[]),fe=i.useCallback(Q=>{g||In(Q.clipboardData?.files)},[In,g]),ft=i.useCallback(Q=>{F(M=>{const ue=M[Q];return ue&&URL.revokeObjectURL(ue.previewUrl),M.filter((Ee,z)=>z!==Q)})},[]),lt=i.useCallback(async()=>{const Q=f.trim();if(!Q||g||!e)return;const M=f;x(!0),p("");try{const ue=await e({description:Q,column:"triage",dependencies:R.length?R:void 0,...Y?{assignedAgentId:Y}:{},modelPresetId:Xt,modelProvider:bt?O:void 0,modelId:bt?ve:void 0,validatorModelProvider:Rt?we:void 0,validatorModelId:Rt?re:void 0,planningModelProvider:se?Pe:void 0,planningModelId:se?qe:void 0,...Ht?{executionMode:"fast"}:{},priority:tn,nodeId:qt});if(ue&&P.length>0){const Ee=[];for(const z of P)try{await lc(ue.id,z.file,l)}catch{Ee.push(z.file.name)}Ee.length>0&&n(`Failed to upload: ${Ee.join(", ")}`,"error")}sn()}catch(ue){p(M),n(Ce(ue)||"Failed to create task","error")}finally{x(!1)}},[f,g,e,R,Y,bt,O,ve,Rt,we,re,se,Pe,qe,P,l,n,sn,Ht,tn,qt]),vt=i.useCallback(Q=>{if(Q.key==="Enter"){if(Q.shiftKey&&w)return;Q.preventDefault(),lt()}else if(Q.key==="Escape"){if(Q.preventDefault(),le){K(null);return}if(Z){ee(!1),Ke(null);return}if(U){C(!1);return}if(Ye){ut(!1);return}if(he){Se(!1),Re(null);return}if(Ue){ce(!1),at(null);return}if(S){G(!1),ht(null);return}f.trim()&&(p(""),k.current&&(k.current.style.height="auto"),typeof window<"u"&&vr(Fr,l)),b(!1),N(!1),k.current?.blur()}},[lt,f,w,U,S,he,Z,le,Ye,Ue,l,N]),et=i.useCallback(()=>{y.current&&(y.current=!1)},[]),_t=i.useCallback(()=>{c&&b(!0)},[c]),Gt=i.useCallback(Q=>{L(M=>M.includes(Q)?M.filter(ue=>ue!==Q):[...M,Q])},[]),ae=i.useCallback(()=>{const Q=window.visualViewport;return Q&&Q.width>0&&Q.height>0?{width:Q.width,height:Q.height,offsetTop:Q.offsetTop,offsetLeft:Q.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),pt=i.useCallback(()=>{const Q=De.current;if(!Q)return;const M=Q.getBoundingClientRect(),{width:ue,height:Ee,offsetTop:z,offsetLeft:ge}=ae(),xe=16,dt=16,Tt=4,Wt=ue<=768,bn=Math.min(Wt?Ee*.6:Ee*.5,360),Mn=Math.max(M.width*1.35,320),Zn=Wt?Math.min(ue-xe*2,360):Mn,On=Math.min(Zn,Math.max(ue-xe*2,240)),Un=M.top-z,rs=M.bottom-z,ts=M.left-ge,xn=Ee-rs,Jn=Un,Hn=Math.max(xn-dt-Tt,160),ws=Math.max(Jn-dt-Tt,160),ns=xn<bn&&Jn>xn,es=Math.max(Math.min(ns?ws:Hn,bn),160),Bs=Math.min(Math.max(ts,xe),ue-xe-On)+ge,Ds=ns?Math.max(dt+z,Un-es-Tt+z):Math.min(rs+Tt+z,Ee+z-dt-es);Ke({top:Ds,left:Bs,width:On,maxHeight:es})},[ae]),gn=i.useCallback(()=>{const Q=At.current?.querySelector(".refine-button");if(!Q)return;const M=Q.getBoundingClientRect(),{width:ue,height:Ee,offsetTop:z,offsetLeft:ge}=ae(),xe=8,dt=12,Tt=4,Wt=Math.min(200,Math.max(Ee-dt*2,160)),bn=Math.min(200,ue-xe*2),Mn=M.top-z,Zn=M.bottom-z,On=M.left-ge,Un=Ee-Zn,rs=Mn,ts=Un<Wt&&rs>Un,xn=Math.min(Math.max(On,xe),ue-xe-bn)+ge,Jn=ts?Math.max(dt+z,Mn-Wt-Tt+z):Math.min(Zn+Tt+z,Ee+z-dt-Wt);Lt({top:Jn,left:xn})},[ae]),us=i.useCallback(()=>{const Q=je.current;if(!Q)return;const M=Q.getBoundingClientRect(),{width:ue,height:Ee,offsetTop:z,offsetLeft:ge}=ae(),xe=16,dt=16,Tt=4,Wt=ue<=768,bn=Math.min(Wt?Ee*.6:Ee*.5,320),Mn=Wt?Math.min(ue-xe*2,360):Math.max(M.width,280),Zn=Math.min(Mn,Math.max(ue-xe*2,240)),On=M.top-z,Un=M.bottom-z,rs=M.left-ge,ts=Ee-Un,xn=On,Jn=Math.max(ts-dt-Tt,200),Hn=Math.max(xn-dt-Tt,200),ws=ts<bn&&xn>ts,ns=Math.max(Math.min(ws?Hn:Jn,bn),200),es=Math.min(Math.max(rs,xe),ue-xe-Zn)+ge,Bs=ws?Math.max(dt+z,On-ns-Tt+z):Math.min(Un+Tt+z,Ee+z-dt-ns);St({top:Bs,left:es,width:Zn,maxHeight:ns})},[ae]),Kn=i.useCallback(()=>{const Q=ct.current?.querySelector("button");if(!Q)return;const M=Q.getBoundingClientRect(),{width:ue,height:Ee,offsetTop:z,offsetLeft:ge}=ae(),xe=16,dt=16,Tt=4,Wt=ue<=768,bn=Math.min(Wt?Ee*.6:Ee*.5,320),Mn=Wt?Math.min(ue-xe*2,280):Math.max(M.width,240),Zn=Math.min(Mn,Math.max(ue-xe*2,200)),On=M.top-z,Un=M.bottom-z,rs=M.left-ge,ts=Ee-Un,xn=On,Jn=Math.max(ts-dt-Tt,160),Hn=Math.max(xn-dt-Tt,160),ws=ts<bn&&xn>ts,ns=Math.max(Math.min(ws?Hn:Jn,bn),160),es=Math.min(Math.max(rs,xe),ue-xe-Zn)+ge,Bs=ws?Math.max(dt+z,On-ns-Tt+z):Math.min(Un+Tt+z,Ee+z-dt-ns);ht({top:Bs,left:es,width:Zn,maxHeight:ns})},[ae]),_n=i.useCallback(()=>{const Q=me.current?.querySelector("button");if(!Q)return;const M=Q.getBoundingClientRect(),{width:ue,height:Ee,offsetTop:z,offsetLeft:ge}=ae(),xe=16,dt=16,Tt=4,Wt=ue<=768,bn=Math.min(Wt?Ee*.6:Ee*.5,320),Mn=Wt?Math.min(ue-xe*2,280):Math.max(M.width,240),Zn=Math.min(Mn,Math.max(ue-xe*2,200)),On=M.top-z,Un=M.bottom-z,rs=M.left-ge,ts=Ee-Un,xn=On,Jn=Math.max(ts-dt-Tt,160),Hn=Math.max(xn-dt-Tt,160),ws=ts<bn&&xn>ts,ns=Math.max(Math.min(ws?Hn:Jn,bn),160),es=Math.min(Math.max(rs,xe),ue-xe-Zn)+ge,Bs=ws?Math.max(dt+z,On-ns-Tt+z):Math.min(Un+Tt+z,Ee+z-dt-ns);Re({top:Bs,left:es,width:Zn,maxHeight:ns})},[ae]),$n=i.useCallback(()=>{const Q=Me.current?.querySelector("button");if(!Q)return;const M=Q.getBoundingClientRect(),{width:ue,height:Ee,offsetTop:z,offsetLeft:ge}=ae(),xe=16,dt=16,Tt=4,Wt=220,bn=Math.min(Math.max(M.width,200),Math.max(ue-xe*2,200)),Mn=M.top-z,Zn=M.bottom-z,On=M.left-ge,Un=Ee-Zn,rs=Mn,ts=Math.max(Un-dt-Tt,160),xn=Math.max(rs-dt-Tt,160),Jn=Un<Wt&&rs>Un,Hn=Math.max(Math.min(Jn?xn:ts,Wt),160),ws=Math.min(Math.max(On,xe),ue-xe-bn)+ge,ns=Jn?Math.max(dt+z,Mn-Hn-Tt+z):Math.min(Zn+Tt+z,Ee+z-dt-Hn);at({top:ns,left:ws,width:bn,maxHeight:Hn})},[ae]);i.useEffect(()=>{if(!Z)return;const Q=()=>pt();window.addEventListener("resize",Q),window.addEventListener("scroll",Q,!0);const M=window.visualViewport;return M&&(M.addEventListener("resize",Q),M.addEventListener("scroll",Q)),()=>{window.removeEventListener("resize",Q),window.removeEventListener("scroll",Q,!0),M&&(M.removeEventListener("resize",Q),M.removeEventListener("scroll",Q))}},[Z,pt]),i.useEffect(()=>{if(!Ye)return;const Q=()=>gn();window.addEventListener("resize",Q),window.addEventListener("scroll",Q,!0);const M=window.visualViewport;return M&&(M.addEventListener("resize",Q),M.addEventListener("scroll",Q)),()=>{window.removeEventListener("resize",Q),window.removeEventListener("scroll",Q,!0),M&&(M.removeEventListener("resize",Q),M.removeEventListener("scroll",Q))}},[Ye,gn]),i.useEffect(()=>{if(!U)return;const Q=()=>us();window.addEventListener("resize",Q),window.addEventListener("scroll",Q,!0);const M=window.visualViewport;return M&&(M.addEventListener("resize",Q),M.addEventListener("scroll",Q)),()=>{window.removeEventListener("resize",Q),window.removeEventListener("scroll",Q,!0),M&&(M.removeEventListener("resize",Q),M.removeEventListener("scroll",Q))}},[U,us]),i.useEffect(()=>{if(!S)return;const Q=()=>Kn();window.addEventListener("resize",Q),window.addEventListener("scroll",Q,!0);const M=window.visualViewport;return M&&(M.addEventListener("resize",Q),M.addEventListener("scroll",Q)),()=>{window.removeEventListener("resize",Q),window.removeEventListener("scroll",Q,!0),M&&(M.removeEventListener("resize",Q),M.removeEventListener("scroll",Q))}},[S,Kn]),i.useEffect(()=>{if(!he)return;const Q=()=>_n();window.addEventListener("resize",Q),window.addEventListener("scroll",Q,!0);const M=window.visualViewport;return M&&(M.addEventListener("resize",Q),M.addEventListener("scroll",Q)),()=>{window.removeEventListener("resize",Q),window.removeEventListener("scroll",Q,!0),M&&(M.removeEventListener("resize",Q),M.removeEventListener("scroll",Q))}},[he,_n]),i.useEffect(()=>{if(!Ue)return;const Q=()=>$n();window.addEventListener("resize",Q),window.addEventListener("scroll",Q,!0);const M=window.visualViewport;return M&&(M.addEventListener("resize",Q),M.addEventListener("scroll",Q)),()=>{window.removeEventListener("resize",Q),window.removeEventListener("scroll",Q,!0),M&&(M.removeEventListener("resize",Q),M.removeEventListener("scroll",Q))}},[Ue,$n]);const hn=i.useCallback(Q=>{const M=Fc(Q);tt(M.provider),de(M.modelId)},[]),Ut=i.useCallback(Q=>{const M=Fc(Q);pe(M.provider),B(M.modelId)},[]),Dn=i.useCallback(Q=>{const M=Fc(Q);ze(M.provider),He(M.modelId)},[]),as=i.useCallback(async Q=>{if(m){m(Q);return}const M=xt,Ee=M.includes(Q)?M.filter(z=>z!==Q):[Q,...M];jt(Ee);try{await Pn({favoriteProviders:Ee,favoriteModels:Bt})}catch{jt(M)}},[xt,Bt,m]),Rn=i.useCallback(async Q=>{if(h){h(Q);return}const M=Bt,Ee=M.includes(Q)?M.filter(z=>z!==Q):[Q,...M];Jt(Ee);try{await Pn({favoriteProviders:xt,favoriteModels:Ee})}catch{Jt(M)}},[Bt,xt,h]),ms=i.useCallback(()=>{const Q=f.trim();if(!Q){n("Enter a description first","error");return}r?.(Q),sn()},[f,r,n,sn]),Xn=i.useCallback(()=>{const Q=f.trim();if(!Q){n("Enter a description first","error");return}o?.(Q),sn()},[f,o,n,sn]),vs=i.useCallback(()=>{lt()},[lt]),Gn=i.useCallback(async Q=>{const M=f.trim();if(!(!M||We)){ut(!1),$t(!0);try{const ue=await Qg(M,Q,l);p(ue),n("Description refined with AI","success"),k.current&&(k.current.style.height="auto",k.current.style.height=`${Math.min(k.current.scrollHeight,200)}px`)}catch(ue){const Ee=Xg(ue);n(Ee,"error")}finally{$t(!1)}}},[f,We,n,l]),hs=(Q,M)=>Q.length>M?Q.slice(0,M)+"…":Q,Ln=i.useCallback(async()=>{if(a){gt(a),be(null),It(!1);return}It(!0),be(null);try{const Q=await Fs();gt(Q.models),d||jt(Q.favoriteProviders),u||Jt(Q.favoriteModels)}catch(Q){be(Ce(Q)||"Failed to load models")}finally{It(!1)}},[a,d,u]),En=i.useCallback(async()=>{if(q.length>0&&I===l){G(!0),Kn();return}X(!0);try{const Q=await Mr(void 0,l);A(Q),D(l),G(!0),Kn()}catch(Q){const M=Ce(Q);n(M?`Failed to load agents: ${M}`:"Failed to load agents","error"),G(!1)}finally{X(!1)}},[q.length,I,l,n,Kn]),Nn=(Y?q.find(Q=>Q.id===Y):void 0)?.name??Y,As=qt?$e.find(Q=>Q.id===qt):void 0,Cs=v,Es=i.useCallback(()=>{N(Q=>{const M=!Q;return b(M),M})},[]);return t.jsxs("div",{className:`quick-entry-box ${v?"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:k,className:`quick-entry-input ${w?"quick-entry-input--expanded":""}`,placeholder:g?"Creating...":"Add a task...",value:f,onChange:Q=>p(Q.target.value),onKeyDown:vt,onPaste:fe,onFocus:_t,onBlur:et,disabled:g||Yt,"data-testid":"quick-entry-input",rows:2,"aria-controls":"quick-entry-controls","aria-expanded":v})}),t.jsx("button",{type:"button",className:"btn btn-sm quick-entry-toggle",onClick:Es,"aria-expanded":v,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:v?"Collapse":"Expand",children:v?t.jsx(Ri,{size:14}):t.jsx(un,{size:14})})]})}),t.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!Cs,"aria-hidden":!Cs,children:[Cs&&!g&&t.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:ms,onMouseDown:Q=>Q.preventDefault(),disabled:!f.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[t.jsx(Pi,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:Xn,onMouseDown:Q=>Q.preventDefault(),disabled:!f.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[t.jsx(ic,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),t.jsxs("div",{className:"refine-trigger-wrap",ref:At,children:[t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${We?"refine-button--loading":""}`,onClick:()=>{ut(Q=>{const M=!Q;return M?gn():Lt(null),M})},disabled:!f.trim()||We,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(xs,{size:12,style:{verticalAlign:"middle"}}),We?"Refining...":"Refine"]}),Ye&&ye&&zt&&_a.createPortal(t.jsxs("div",{ref:wt,className:"refine-menu refine-menu--portal",onMouseDown:Q=>Q.preventDefault(),style:{position:"fixed",top:`${zt.top}px`,left:`${zt.left}px`},children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>Gn("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:()=>Gn("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:()=>Gn("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:()=>Gn("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"})]})]}),ye)]}),t.jsx("div",{className:"dep-trigger-wrap",children:t.jsxs("button",{ref:je,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{C(Q=>{const M=!Q;return M?(ee(!1),Ke(null),K(null),G(!1),ht(null),Se(!1),Re(null),ce(!1),at(null),us()):St(null),M})},children:[t.jsx(pr,{size:12,style:{verticalAlign:"middle"}}),R.length>0?`${R.length} deps`:"Deps"]})}),U&&ye&&Be&&(()=>{const Q=$.toLowerCase(),M=(Q?s.filter(ue=>ue.id.toLowerCase().includes(Q)||ue.title&&ue.title.toLowerCase().includes(Q)||ue.description&&ue.description.toLowerCase().includes(Q)):[...s]).sort((ue,Ee)=>{const z=Ee.createdAt.localeCompare(ue.createdAt);if(z!==0)return z;const ge=parseInt(ue.id.slice(ue.id.lastIndexOf("-")+1),10)||0;return(parseInt(Ee.id.slice(Ee.id.lastIndexOf("-")+1),10)||0)-ge});return _a.createPortal(t.jsxs("div",{ref:Fe,className:"dep-dropdown dep-dropdown--portal",onMouseDown:ue=>ue.preventDefault(),style:{position:"fixed",top:`${Be.top}px`,left:`${Be.left}px`,width:`${Be.width}px`,maxHeight:Be.maxHeight?`${Be.maxHeight}px`:void 0,overflowY:Be.maxHeight?"auto":void 0},children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:$,onChange:ue=>V(ue.target.value),onClick:ue=>ue.stopPropagation()}),M.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):M.map(ue=>t.jsxs("div",{className:`dep-dropdown-item${R.includes(ue.id)?" selected":""}`,onMouseDown:Ee=>Ee.preventDefault(),onClick:()=>Gt(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))]}),ye)})(),t.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>E.current?.click(),children:[t.jsx(Fg,{size:12,style:{verticalAlign:"middle"}}),P.length>0?`Attach (${P.length})`:"Attach"]}),t.jsxs("button",{ref:De,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{C(!1),G(!1),ht(null),Se(!1),Re(null),ce(!1),at(null),K(null),ee(!0),pt()},children:[t.jsx(go,{size:12,style:{verticalAlign:"middle"}}),Oe]}),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:()=>{C(!1),G(!1),ht(null),ee(!1),Ke(null),K(null),ce(!1),at(null),Se(Q=>{const M=!Q;return M?_n():Re(null),M})},children:[t.jsx(bo,{size:12,style:{verticalAlign:"middle"}}),` ${As?.name??"Node"}`,As&&t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(Da,{status:As.status,showLabel:!0})})]})}),he&&ye&&yt&&_a.createPortal(t.jsxs("div",{ref:oe,className:"dep-dropdown node-picker-dropdown node-picker-dropdown--portal",onMouseDown:Q=>Q.preventDefault(),style:{position:"fixed",top:`${yt.top}px`,left:`${yt.left}px`,width:`${yt.width}px`,maxHeight:yt.maxHeight?`${yt.maxHeight}px`:void 0,overflowY:yt.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${qt==null?" selected":""}`,onMouseDown:Q=>Q.preventDefault(),onClick:()=>{ke(void 0),Se(!1),Re(null)},children:t.jsx("span",{className:"node-picker-item-name",children:"Project default / local"})}),$e.map(Q=>t.jsxs("div",{className:`dep-dropdown-item node-picker-item${qt===Q.id?" selected":""}`,onMouseDown:M=>M.preventDefault(),onClick:()=>{ke(Q.id),Se(!1),Re(null)},children:[t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(Da,{status:Q.status})}),t.jsx("span",{className:"node-picker-item-name",children:Q.name}),t.jsx("span",{className:"node-picker-item-status",children:pE(Q.status)})]},Q.id))]}),ye),t.jsx("div",{className:"agent-trigger-wrap",ref:ct,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{S?(G(!1),ht(null)):(Se(!1),Re(null),ce(!1),at(null),En())},"data-testid":"quick-entry-agent-button",children:[t.jsx(Vn,{size:12,style:{verticalAlign:"middle"}}),Nn?` ${Nn}`:" Agent"]})}),S&&ye&&rt&&_a.createPortal(t.jsxs("div",{ref:Ve,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:Q=>Q.preventDefault(),style:{position:"fixed",top:`${rt.top}px`,left:`${rt.left}px`,width:`${rt.width}px`,maxHeight:rt.maxHeight?`${rt.maxHeight}px`:void 0,overflowY:rt.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),Ae&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!Ae&&q.map(Q=>t.jsxs("div",{className:`dep-dropdown-item${Y===Q.id?" selected":""}`,onMouseDown:M=>M.preventDefault(),onClick:()=>{ne(Q.id===Y?null:Q.id),G(!1),ht(null)},children:[t.jsx(Vn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:Q.role}),t.jsx("span",{className:"dep-dropdown-title",children:Q.name})]},Q.id)),!Ae&&q.length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),Y&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:Q=>Q.preventDefault(),onClick:()=>{ne(null),G(!1),ht(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),ye),t.jsx("div",{className:"priority-trigger-wrap",ref:Me,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-priority-button",onClick:()=>{C(!1),G(!1),ht(null),Se(!1),Re(null),ee(!1),Ke(null),K(null),ce(Q=>{const M=!Q;return M?$n():at(null),M})},children:[t.jsx(ow,{size:12,style:{verticalAlign:"middle"}}),` ${tn[0].toUpperCase()}${tn.slice(1)}`]})}),Ue&&ye&&Ge&&_a.createPortal(t.jsxs("div",{ref:Xe,className:"dep-dropdown priority-picker-dropdown priority-picker-dropdown--portal",onMouseDown:Q=>Q.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("div",{className:"dep-dropdown-search-header",children:"Select priority"}),da.map(Q=>{const M=`${Q[0].toUpperCase()}${Q.slice(1)}`;return t.jsx("div",{className:`dep-dropdown-item${tn===Q?" selected":""}`,"data-testid":`quick-entry-priority-option-${Q}`,onMouseDown:ue=>ue.preventDefault(),onClick:()=>{dn(Q),ce(!1),at(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:M})},Q)})]}),ye),t.jsx("button",{type:"button",className:`btn btn-sm ${Ht?"btn-primary":""}`,onClick:()=>Zt(Q=>!Q),onMouseDown:Q=>Q.preventDefault(),"aria-pressed":Ht,"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:Q=>Q.preventDefault(),disabled:!f.trim()||g,"data-testid":"quick-entry-save",title:"Create task",children:[t.jsx(Ug,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),P.length>0&&t.jsx("div",{className:"inline-create-previews",children:P.map((Q,M)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:Q.previewUrl,alt:Q.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>ft(M),disabled:g,title:"Remove image","data-testid":`quick-entry-preview-remove-${M}`,children:"×"})]},Q.previewUrl))}),Z&&ye&&ie&&_a.createPortal(t.jsx("div",{ref:Te,className:"model-nested-menu model-nested-menu--portal",onMouseDown:Q=>Q.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${ie.top}px`,left:`${ie.left}px`,width:`${ie.width}px`,maxHeight:ie.maxHeight?`${ie.maxHeight}px`:void 0,overflowY:ie.maxHeight?"auto":void 0},children:le===null?t.jsxs("div",{className:"model-menu-items",children:[t.jsxs("button",{type:"button",className:`model-menu-item ${se?"model-menu-item--active":""}`,onClick:()=>K("plan"),"data-testid":"model-menu-plan",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Pi,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),t.jsx("span",{className:"model-menu-item-value",children:se?mt(Pe,qe):"Using default"}),t.jsx(zn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${bt?"model-menu-item--active":""}`,onClick:()=>K("executor"),"data-testid":"model-menu-executor",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(xs,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),t.jsx("span",{className:"model-menu-item-value",children:bt?mt(O,ve):"Using default"}),t.jsx(zn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${Rt?"model-menu-item--active":""}`,onClick:()=>K("validator"),"data-testid":"model-menu-validator",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(go,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Reviewer"]}),t.jsx("span",{className:"model-menu-item-value",children:Rt?mt(we,re):"Using default"}),t.jsx(zn,{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:()=>K(null),"data-testid":"model-submenu-back",children:[t.jsx(un,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),t.jsxs("div",{className:"model-submenu-header",children:[le==="plan"&&"Plan Model",le==="executor"&&"Executor Model",le==="validator"&&"Reviewer Model"]}),t.jsx(Ns,{models:ot,value:le==="plan"?it:le==="executor"?rn:_e,onChange:le==="plan"?hn:le==="executor"?Ut:Dn,placeholder:"Using default",disabled:kt,id:`model-${le}-select`,label:`${le} model`,favoriteProviders:Ot,onToggleFavorite:as,favoriteModels:nn,onToggleModelFavorite:Rn}),Ie&&t.jsxs("div",{className:"model-submenu-error",children:[t.jsx("span",{children:Ie}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:Ln,children:"Retry"})]})]})}),ye)]}),t.jsx("input",{ref:E,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:Q=>{In(Q.target.files),Q.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),t.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function fE(e){return Tu(e)||e}function gE(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 bE(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=gE(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:fE(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 Ah=100,Bc=50,Rh=25;function xE({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:v,collapsed:N,onToggleCollapse:k,allTasks:E,availableModels:y,onPlanningMode:j,onSubtaskBreakdown:P,onOpenDetailWithTab:F,favoriteProviders:_,favoriteModels:R,onToggleFavorite:L,onToggleModelFavorite:U,isSearchActive:C,taskStuckTimeoutMs:$,onOpenMission:V,lastFetchTimeMs:Y,workflowStepNameLookup:ne,blockerFanoutMap:q}){const[A,I]=i.useState(!1),[D,S]=i.useState(Bc),[G,he]=i.useState(!1),[Se,Ue]=i.useState(!1),[ce,Ae]=i.useState(!1),[X,Z]=i.useState(!1),ee=i.useRef(null),le=gC(n.length),{confirm:K}=ci();i.useEffect(()=>{if(!G)return;function Me(rt){ee.current?.contains(rt.target)||he(!1)}function Xe(rt){rt.key==="Escape"&&he(!1)}return document.addEventListener("mousedown",Me),document.addEventListener("keydown",Xe),()=>{document.removeEventListener("mousedown",Me),document.removeEventListener("keydown",Xe)}},[G]);const O=e==="archived",pe=O&&N,ve=!O&&!C&&e!=="in-progress"&&n.length>Ah;i.useEffect(()=>{S(Me=>e==="in-progress"||O||n.length<=Ah?Bc:Math.min(Math.max(Me,Bc),n.length))},[e,O,n.length]);const B=i.useCallback(Me=>{O||(Me.preventDefault(),Me.dataTransfer.dropEffect="move",I(!0))},[O]),we=i.useCallback(Me=>{Me.currentTarget.contains(Me.relatedTarget)||I(!1)},[]),ze=i.useCallback(async Me=>{Me.preventDefault(),I(!1);const Xe=Me.dataTransfer.getData("text/plain");if(!Xe)return;const rt=n.find(ht=>ht.id===Xe);if(!(rt&&rt.column===e))try{const yt=(E?.find(at=>at.id===Xe)??rt)?.steps.some(at=>at.status!=="pending")??!1,Re=(e==="todo"||e==="triage")&&yt;let Ge;if(Re){if(await K({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Ge={preserveProgress:!0};else if(!await K({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await r(Xe,e,Ge)}catch(ht){c(Ce(ht),"error")}},[c,E,e,K,r,n]),re=i.useMemo(()=>e!=="in-progress"?[]:bE(n,n,a),[e,n,a]),He=i.useMemo(()=>ve?n.slice(0,D):n,[ve,n,D]),Pe=Math.max(0,n.length-He.length),tt=i.useCallback(()=>{S(Me=>Math.min(Me+Rh,n.length))},[n.length]),qe=i.useCallback(async()=>{if(he(!1),!(n.length===0||!await K({title:"Replan All Tasks",message:`Move all ${n.length} todo task${n.length===1?"":"s"} back to planning to be replanned?`}))){Ue(!0);try{const Xe=await Promise.allSettled(n.map(yt=>r(yt.id,"triage"))),rt=Xe.filter(yt=>yt.status==="rejected").length,ht=Xe.length-rt;rt===0?c(`Moved ${ht} task${ht===1?"":"s"} to planning for replanning`,"success"):c(`Moved ${ht} of ${Xe.length} tasks; ${rt} failed`,"error")}finally{Ue(!1)}}},[n,r,c,K]),de=i.useMemo(()=>n.filter(Me=>!Me.paused&&!Me.assignedAgentId),[n]),De=de.length,Te=e==="todo"||e==="in-progress"||e==="in-review",ct=Se||ce||X,Ve=i.useCallback(async()=>{if(!(!o||(he(!1),De===0)||!await K({title:"Stop All Tasks",message:`Stop all ${De} ${cs[e].toLowerCase()} task${De===1?"":"s"}?`,danger:!0}))){Ae(!0);try{const Xe=await Promise.allSettled(de.map(yt=>o(yt.id))),rt=Xe.filter(yt=>yt.status==="rejected").length,ht=Xe.length-rt;rt===0?c(`Stopped ${ht} task${ht===1?"":"s"}`,"success"):c(`Stopped ${ht} of ${Xe.length} tasks; ${rt} failed`,"error")}finally{Ae(!1)}}},[o,De,e,de,c,K]),me=i.useCallback(async()=>{if(he(!1),n.length===0||!await K({title:"Move All to Todo",message:`Move all ${n.length} ${cs[e].toLowerCase()} task${n.length===1?"":"s"} to Todo?`}))return;const Xe=n.some(ht=>ht.steps.some(yt=>yt.status!=="pending"));let rt=!1;if(Xe){if(await K({title:"Preserve Progress?",message:"Some tasks have completed steps. Keep progress before moving to Todo?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))rt=!0;else if(!await K({title:"Reset Progress?",message:"Reset step progress for tasks before moving to Todo?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}Z(!0);try{const ht=await Promise.allSettled(n.map(Ge=>r(Ge.id,"todo",rt?{preserveProgress:!0}:void 0))),yt=ht.filter(Ge=>Ge.status==="rejected").length,Re=ht.length-yt;yt===0?c(`Moved ${Re} task${Re===1?"":"s"} to Todo`,"success"):c(`Moved ${Re} of ${ht.length} tasks to Todo; ${yt} failed`,"error")}finally{Z(!1)}},[n,e,r,c,K]),oe=i.useCallback(async()=>{if(!(!v||n.length===0||!await K({title:"Archive All Done",message:`Archive all ${n.length} done tasks?`,danger:!0})))try{const Xe=await v();c(`Archived ${Xe.length} tasks`,"success")}catch(Xe){c(Ce(Xe)||"Failed to archive tasks","error")}},[v,n.length,c,K]);return t.jsxs("div",{className:`column${A?" drag-over":""}${O?" column-archived":""}${pe?" column-collapsed":""}`,"data-column":e,onDragOver:B,onDragLeave:we,onDrop:ze,children:[t.jsxs("div",{className:"column-header",children:[t.jsx("div",{className:`column-dot dot-${e}`}),t.jsx("h2",{children:cs[e]}),t.jsx("span",{className:`column-count${le?" 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"&&v&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:oe,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:t.jsx(So,{})}),O&&k&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:k,title:N?"Expand archived tasks":"Collapse archived tasks","aria-label":N?"Expand archived tasks":"Collapse archived tasks",children:N?t.jsx(un,{size:16}):t.jsx(Ri,{size:16})}),Te&&t.jsxs("div",{className:"column-menu",ref:ee,children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>he(Me=>!Me),"aria-haspopup":"menu","aria-expanded":G,"aria-label":`${cs[e]} column actions`,title:"Column actions",disabled:ct,children:t.jsx(Uy,{})}),G&&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 qe(),disabled:n.length===0||Se,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 Ve(),disabled:De===0||ce||!o,children:["Stop All",t.jsx("span",{className:"column-menu-item-hint",children:n.length===0?"No tasks in this column":De===0?"No manually pausable tasks":`Pause ${De} active unassigned task${De===1?"":"s"}`})]}),t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void me(),disabled:n.length===0||X,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:pC[e]}),!pe&&t.jsxs("div",{className:"column-body",children:[e==="triage"&&d&&t.jsx(Rb,{onCreate:d,addToast:c,tasks:E??[],availableModels:y,onPlanningMode:j,onSubtaskBreakdown:P,projectId:s,autoExpand:!1,favoriteProviders:_,favoriteModels:R,onToggleFavorite:L,onToggleModelFavorite:U}),e==="in-progress"?re.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):re.map(Me=>t.jsx(Ab,{label:Me.label,activeTasks:Me.activeTasks,queuedTasks:Me.queuedTasks,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onOpenDetailWithTab:F,taskStuckTimeoutMs:$,onOpenMission:V,lastFetchTimeMs:Y,workflowStepNameLookup:ne,blockerFanoutMap:q},Me.label)):n.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):t.jsxs(t.Fragment,{children:[He.map(Me=>t.jsx(yo,{task:Me,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:x,onUnarchiveTask:w,onDeleteTask:b,onOpenDetailWithTab:F,taskStuckTimeoutMs:$,onOpenMission:V,onMoveTask:r,lastFetchTimeMs:Y,workflowStepNameLookup:ne,fanout:q?.get(Me.id)},Me.id)),ve&&Pe>0&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:tt,children:["Load ",Math.min(Rh,Pe)," more (",Pe," remaining)"]})]}),t.jsx(ia,{slotId:"board-column-footer",projectId:s})]})]})}const Pb=i.memo(xE);Pb.displayName="Column";const vE=3,yE=new Set(["triage","todo","in-progress","in-review"]);function wE(e){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)>=vE}function Ib(e){const n=new Map(e.map(o=>[o.id,o])),s=new Map,a=o=>{let l=s.get(o);return l||(l={dependentIds:[],blockedByDependentIds:[],activeCount:0,activeTodoCount:0},s.set(o,l)),l};for(const o of e){const l=yE.has(o.column),c=o.column==="todo",d=o.dependencies??[];for(const u of d){if(!u)continue;const m=a(u);m.dependentIds.push(o.id),l&&(m.activeCount+=1),c&&(m.activeTodoCount+=1)}if(o.blockedBy){const u=a(o.blockedBy);u.dependentIds.push(o.id),u.blockedByDependentIds.push(o.id),l&&(u.activeCount+=1),c&&(u.activeTodoCount+=1)}}const r=new Map;for(const[o,l]of s){const c=n.get(o),d=wE(c)?[...l.blockedByDependentIds]:[];r.set(o,{totalCount:l.activeCount,activeTodoCount:l.activeTodoCount,dependentIds:l.dependentIds,staleBlockedByDependentIds:d})}return r}function kE(e){return i.useMemo(()=>Ib(e),[e])}function jE(e,n){return e.length!==n.length?!1:e.every((s,a)=>s===n[a])}const Ph=new Map;function NE(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 SE({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:v,searchQuery:N="",availableModels:k,onPlanningMode:E,onSubtaskBreakdown:y,onOpenDetailWithTab:j,favoriteProviders:P,favoriteModels:F,onToggleFavorite:_,onToggleModelFavorite:R,taskStuckTimeoutMs:L,onOpenMission:U,lastFetchTimeMs:C}){const[$,V]=i.useState(!0),Y=i.useRef(!1),{fetchBatch:ne}=CC(n),q=i.useRef(null),[A,I]=i.useState(Ph),D=kE(e),S=N.trim()!=="",G=i.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),he=i.useCallback(()=>{V(ce=>{const Ae=!ce;return!Ae&&!Y.current&&v&&(Y.current=!0,v()),Ae})},[v]),Se=i.useMemo(()=>{const ce={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};for(const Z of e){const ee=Du(Z.column)?Z.column:Ll;(ce[ee]??ce[Ll]).push(Z)}const Ae=G.current,X={};for(const Z of sa){const ee=xb(ce[Z],Z);X[Z]=jE(Ae[Z],ee)?Ae[Z]:ee}return G.current=X,X},[e]);i.useEffect(()=>{let ce=!1;return $o(n).then(Ae=>{if(ce)return;const X=new Map(Ae.map(Z=>[Z.id,Z.name]));I(Z=>NE(Z,X)?Z:X)}).catch(()=>{ce||I(Ae=>Ae.size===0?Ae:Ph)}),()=>{ce=!0}},[n]);const Ue=i.useMemo(()=>e.filter(ce=>ce.prInfo||ce.issueInfo).map(ce=>ce.id),[e]);return i.useEffect(()=>{if(Ue.length!==0)return q.current&&clearTimeout(q.current),q.current=setTimeout(()=>{const ce=[];for(let Ae=0;Ae<Ue.length;Ae+=50)ce.push(Ue.slice(Ae,Ae+50));ce.forEach(Ae=>{ne(Ae)})},500),()=>{q.current&&clearTimeout(q.current)}},[Ue,ne]),t.jsx(t.Fragment,{children:t.jsx("main",{className:"board",id:"board",children:sa.map(ce=>t.jsx(Pb,{column:ce,tasks:Se[ce],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:k,onOpenDetailWithTab:j,favoriteProviders:P,favoriteModels:F,onToggleFavorite:_,onToggleModelFavorite:R,isSearchActive:S,taskStuckTimeoutMs:L,onOpenMission:U,lastFetchTimeMs:C,workflowStepNameLookup:A,blockerFanoutMap:D,...ce==="triage"?{onQuickCreate:c,onNewTask:d,onPlanningMode:E,onSubtaskBreakdown:y}:{},...ce==="in-review"?{autoMerge:u,onToggleAutoMerge:m}:{},...ce==="done"?{onArchiveAllDone:b}:{},...ce==="archived"?{collapsed:$,onToggleCollapse:he}:{}},ce))})})}function Ti(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 CE(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let mr=0,mo=null;function EE(){if(typeof window>"u")return;if(mr>0){mr+=1;return}const e=document.documentElement,n=document.body;mo={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=`-${mo.scrollY}px`,n.style.left="0",n.style.right="0",n.style.width="100%",n.style.overflow="hidden",mr=1}function _E(){if(typeof window>"u"||mr===0||(mr-=1,mr>0||!mo))return;const e=document.documentElement,n=document.body,{htmlOverflow:s,bodyPosition:a,bodyTop:r,bodyLeft:o,bodyRight:l,bodyWidth:c,bodyOverflow:d,scrollY:u}=mo;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,mo=null,window.scrollTo(0,0)}function ji(e){i.useEffect(()=>{if(!(!e||!CE()))return EE(),()=>{_E()}},[e])}function Gi(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 ME(e,n){const s={};return(e[e.length-1]===""?[...e,""]:e).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const AE=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,RE=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,PE={};function Ih(e,n){return(PE.jsx?RE:AE).test(e)}const IE=/[ \t\n\f\r]/g;function TE(e){return typeof e=="object"?e.type==="text"?Th(e.value):!1:Th(e)}function Th(e){return e.replace(IE,"")===""}class Fo{constructor(n,s,a){this.normal=s,this.property=n,a&&(this.space=a)}}Fo.prototype.normal={};Fo.prototype.property={};Fo.prototype.space=void 0;function Tb(e,n){const s={},a={};for(const r of e)Object.assign(s,r.property),Object.assign(a,r.normal);return new Fo(s,a,n)}function tu(e){return e.toLowerCase()}class Ws{constructor(n,s){this.attribute=s,this.property=n}}Ws.prototype.attribute="";Ws.prototype.booleanish=!1;Ws.prototype.boolean=!1;Ws.prototype.commaOrSpaceSeparated=!1;Ws.prototype.commaSeparated=!1;Ws.prototype.defined=!1;Ws.prototype.mustUseProperty=!1;Ws.prototype.number=!1;Ws.prototype.overloadedBoolean=!1;Ws.prototype.property="";Ws.prototype.spaceSeparated=!1;Ws.prototype.space=void 0;let $E=0;const cn=Ba(),gs=Ba(),nu=Ba(),Et=Ba(),qn=Ba(),hr=Ba(),Gs=Ba();function Ba(){return 2**++$E}const su=Object.freeze(Object.defineProperty({__proto__:null,boolean:cn,booleanish:gs,commaOrSpaceSeparated:Gs,commaSeparated:hr,number:Et,overloadedBoolean:nu,spaceSeparated:qn},Symbol.toStringTag,{value:"Module"})),Uc=Object.keys(su);class zu extends Ws{constructor(n,s,a,r){let o=-1;if(super(n,s),$h(this,"space",r),typeof a=="number")for(;++o<Uc.length;){const l=Uc[o];$h(this,Uc[o],(a&su[l])===su[l])}}}zu.prototype.defined=!0;function $h(e,n,s){s&&(e[n]=s)}function Rr(e){const n={},s={};for(const[a,r]of Object.entries(e.properties)){const o=new zu(a,e.transform(e.attributes||{},a),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(a)&&(o.mustUseProperty=!0),n[a]=o,s[tu(a)]=a,s[tu(o.attribute)]=a}return new Fo(n,s,e.space)}const $b=Rr({properties:{ariaActiveDescendant:null,ariaAtomic:gs,ariaAutoComplete:null,ariaBusy:gs,ariaChecked:gs,ariaColCount:Et,ariaColIndex:Et,ariaColSpan:Et,ariaControls:qn,ariaCurrent:null,ariaDescribedBy:qn,ariaDetails:null,ariaDisabled:gs,ariaDropEffect:qn,ariaErrorMessage:null,ariaExpanded:gs,ariaFlowTo:qn,ariaGrabbed:gs,ariaHasPopup:null,ariaHidden:gs,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:qn,ariaLevel:Et,ariaLive:null,ariaModal:gs,ariaMultiLine:gs,ariaMultiSelectable:gs,ariaOrientation:null,ariaOwns:qn,ariaPlaceholder:null,ariaPosInSet:Et,ariaPressed:gs,ariaReadOnly:gs,ariaRelevant:null,ariaRequired:gs,ariaRoleDescription:qn,ariaRowCount:Et,ariaRowIndex:Et,ariaRowSpan:Et,ariaSelected:gs,ariaSetSize:Et,ariaSort:null,ariaValueMax:Et,ariaValueMin:Et,ariaValueNow:Et,ariaValueText:null,role:null},transform(e,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function Db(e,n){return n in e?e[n]:n}function Lb(e,n){return Db(e,n.toLowerCase())}const DE=Rr({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:hr,acceptCharset:qn,accessKey:qn,action:null,allow:null,allowFullScreen:cn,allowPaymentRequest:cn,allowUserMedia:cn,alt:null,as:null,async:cn,autoCapitalize:null,autoComplete:qn,autoFocus:cn,autoPlay:cn,blocking:qn,capture:null,charSet:null,checked:cn,cite:null,className:qn,cols:Et,colSpan:null,content:null,contentEditable:gs,controls:cn,controlsList:qn,coords:Et|hr,crossOrigin:null,data:null,dateTime:null,decoding:null,default:cn,defer:cn,dir:null,dirName:null,disabled:cn,download:nu,draggable:gs,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:cn,formTarget:null,headers:qn,height:Et,hidden:nu,high:Et,href:null,hrefLang:null,htmlFor:qn,httpEquiv:qn,id:null,imageSizes:null,imageSrcSet:null,inert:cn,inputMode:null,integrity:null,is:null,isMap:cn,itemId:null,itemProp:qn,itemRef:qn,itemScope:cn,itemType:qn,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:cn,low:Et,manifest:null,max:null,maxLength:Et,media:null,method:null,min:null,minLength:Et,multiple:cn,muted:cn,name:null,nonce:null,noModule:cn,noValidate:cn,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:cn,optimum:Et,pattern:null,ping:qn,placeholder:null,playsInline:cn,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:cn,referrerPolicy:null,rel:qn,required:cn,reversed:cn,rows:Et,rowSpan:Et,sandbox:qn,scope:null,scoped:cn,seamless:cn,selected:cn,shadowRootClonable:cn,shadowRootDelegatesFocus:cn,shadowRootMode:null,shape:null,size:Et,sizes:null,slot:null,span:Et,spellCheck:gs,src:null,srcDoc:null,srcLang:null,srcSet:null,start:Et,step:null,style:null,tabIndex:Et,target:null,title:null,translate:null,type:null,typeMustMatch:cn,useMap:null,value:gs,width:Et,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:qn,axis:null,background:null,bgColor:null,border:Et,borderColor:null,bottomMargin:Et,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:cn,declare:cn,event:null,face:null,frame:null,frameBorder:null,hSpace:Et,leftMargin:Et,link:null,longDesc:null,lowSrc:null,marginHeight:Et,marginWidth:Et,noResize:cn,noHref:cn,noShade:cn,noWrap:cn,object:null,profile:null,prompt:null,rev:null,rightMargin:Et,rules:null,scheme:null,scrolling:gs,standby:null,summary:null,text:null,topMargin:Et,valueType:null,version:null,vAlign:null,vLink:null,vSpace:Et,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:cn,disableRemotePlayback:cn,prefix:null,property:null,results:Et,security:null,unselectable:null},space:"html",transform:Lb}),LE=Rr({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:Gs,accentHeight:Et,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:Et,amplitude:Et,arabicForm:null,ascent:Et,attributeName:null,attributeType:null,azimuth:Et,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:Et,by:null,calcMode:null,capHeight:Et,className:qn,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:Et,diffuseConstant:Et,direction:null,display:null,dur:null,divisor:Et,dominantBaseline:null,download:cn,dx:null,dy:null,edgeMode:null,editable:null,elevation:Et,enableBackground:null,end:null,event:null,exponent:Et,externalResourcesRequired:null,fill:null,fillOpacity:Et,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:hr,g2:hr,glyphName:hr,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:Et,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:Et,horizOriginX:Et,horizOriginY:Et,id:null,ideographic:Et,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:Et,k:Et,k1:Et,k2:Et,k3:Et,k4:Et,kernelMatrix:Gs,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:Et,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:Et,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:Et,overlineThickness:Et,paintOrder:null,panose1:null,path:null,pathLength:Et,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:qn,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:Et,pointsAtY:Et,pointsAtZ:Et,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Gs,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Gs,rev:Gs,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Gs,requiredFeatures:Gs,requiredFonts:Gs,requiredFormats:Gs,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:Et,specularExponent:Et,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:Et,strikethroughThickness:Et,string:null,stroke:null,strokeDashArray:Gs,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:Et,strokeOpacity:Et,strokeWidth:null,style:null,surfaceScale:Et,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Gs,tabIndex:Et,tableValues:null,target:null,targetX:Et,targetY:Et,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Gs,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:Et,underlineThickness:Et,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:Et,values:null,vAlphabetic:Et,vMathematical:Et,vectorEffect:null,vHanging:Et,vIdeographic:Et,version:null,vertAdvY:Et,vertOriginX:Et,vertOriginY:Et,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:Et,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Db}),Ob=Rr({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()}}),zb=Rr({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Lb}),Fb=Rr({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),OE={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"},zE=/[A-Z]/g,Dh=/-[a-z]/g,FE=/^data[-\w.:]+$/i;function BE(e,n){const s=tu(n);let a=n,r=Ws;if(s in e.normal)return e.property[e.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&FE.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(Dh,HE);a="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!Dh.test(o)){let l=o.replace(zE,UE);l.charAt(0)!=="-"&&(l="-"+l),n="data"+l}}r=zu}return new r(a,n)}function UE(e){return"-"+e.toLowerCase()}function HE(e){return e.charAt(1).toUpperCase()}const qE=Tb([$b,DE,Ob,zb,Fb],"html"),Fu=Tb([$b,LE,Ob,zb,Fb],"svg");function VE(e){return e.join(" ").trim()}var er={},Hc,Lh;function WE(){if(Lh)return Hc;Lh=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 v=1,N=1;function k(C){var $=C.match(n);$&&(v+=$.length);var V=C.lastIndexOf(d);N=~V?C.length-V:N+C.length}function E(){var C={line:v,column:N};return function($){return $.position=new y(C),F(),$}}function y(C){this.start=C,this.end={line:v,column:N},this.source=b.source}y.prototype.content=w;function j(C){var $=new Error(b.source+":"+v+":"+N+": "+C);if($.reason=C,$.filename=b.source,$.line=v,$.column=N,$.source=w,!b.silent)throw $}function P(C){var $=C.exec(w);if($){var V=$[0];return k(V),w=w.slice(V.length),$}}function F(){P(s)}function _(C){var $;for(C=C||[];$=R();)$!==!1&&C.push($);return C}function R(){var C=E();if(!(u!=w.charAt(0)||m!=w.charAt(1))){for(var $=2;h!=w.charAt($)&&(m!=w.charAt($)||u!=w.charAt($+1));)++$;if($+=2,h===w.charAt($-1))return j("End of comment missing");var V=w.slice(2,$-2);return N+=2,k(V),w=w.slice($),N+=2,C({type:f,comment:V})}}function L(){var C=E(),$=P(a);if($){if(R(),!P(r))return j("property missing ':'");var V=P(o),Y=C({type:p,property:x($[0].replace(e,h)),value:V?x(V[0].replace(e,h)):h});return P(l),Y}}function U(){var C=[];_(C);for(var $;$=L();)$!==!1&&(C.push($),_(C));return C}return F(),U()}function x(w){return w?w.replace(c,h):h}return Hc=g,Hc}var Oh;function KE(){if(Oh)return er;Oh=1;var e=er&&er.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(er,"__esModule",{value:!0}),er.default=s;const n=e(WE());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 er}var Br={},zh;function GE(){if(zh)return Br;zh=1,Object.defineProperty(Br,"__esModule",{value:!0}),Br.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 Br.camelCase=d,Br}var Ur,Fh;function JE(){if(Fh)return Ur;Fh=1;var e=Ur&&Ur.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=e(KE()),s=GE();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,Ur=a,Ur}var YE=JE();const QE=Mg(YE),Bb=Ub("end"),Bu=Ub("start");function Ub(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 XE(e){const n=Bu(e),s=Bb(e);if(n&&s)return{start:n,end:s}}function ho(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Bh(e.position):"start"in e||"end"in e?Bh(e):"line"in e||"column"in e?iu(e):""}function iu(e){return Uh(e&&e.line)+":"+Uh(e&&e.column)}function Bh(e){return iu(e&&e.start)+"-"+iu(e&&e.end)}function Uh(e){return e&&typeof e=="number"?e:1}class $s 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=ho(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}}$s.prototype.file="";$s.prototype.name="";$s.prototype.reason="";$s.prototype.message="";$s.prototype.stack="";$s.prototype.column=void 0;$s.prototype.line=void 0;$s.prototype.ancestors=void 0;$s.prototype.cause=void 0;$s.prototype.fatal=void 0;$s.prototype.place=void 0;$s.prototype.ruleId=void 0;$s.prototype.source=void 0;const Uu={}.hasOwnProperty,ZE=new Map,e2=/[A-Z]/g,t2=new Set(["table","tbody","thead","tfoot","tr"]),n2=new Set(["td","th"]),Hb="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function s2(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=u2(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=d2(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"?Fu:qE,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=qb(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function qb(e,n,s){if(n.type==="element")return i2(e,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return a2(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return o2(e,n,s);if(n.type==="mdxjsEsm")return r2(e,n);if(n.type==="root")return l2(e,n,s);if(n.type==="text")return c2(e,n)}function i2(e,n,s){const a=e.schema;let r=a;n.tagName.toLowerCase()==="svg"&&a.space==="html"&&(r=Fu,e.schema=r),e.ancestors.push(n);const o=Wb(e,n.tagName,!1),l=m2(e,n);let c=qu(e,n);return t2.has(n.tagName)&&(c=c.filter(function(d){return typeof d=="string"?!TE(d):!0})),Vb(e,l,o,n),Hu(l,c),e.ancestors.pop(),e.schema=a,e.create(n,o,l,s)}function a2(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)}wo(e,n.position)}function r2(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);wo(e,n.position)}function o2(e,n,s){const a=e.schema;let r=a;n.name==="svg"&&a.space==="html"&&(r=Fu,e.schema=r),e.ancestors.push(n);const o=n.name===null?e.Fragment:Wb(e,n.name,!0),l=h2(e,n),c=qu(e,n);return Vb(e,l,o,n),Hu(l,c),e.ancestors.pop(),e.schema=a,e.create(n,o,l,s)}function l2(e,n,s){const a={};return Hu(a,qu(e,n)),e.create(n,e.Fragment,a,s)}function c2(e,n){return n.value}function Vb(e,n,s,a){typeof s!="string"&&s!==e.Fragment&&e.passNode&&(n.node=a)}function Hu(e,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(e.children=s)}}function d2(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 u2(e,n){return s;function s(a,r,o,l){const c=Array.isArray(o.children),d=Bu(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 m2(e,n){const s={};let a,r;for(r in n.properties)if(r!=="children"&&Uu.call(n.properties,r)){const o=p2(e,r,n.properties[r]);if(o){const[l,c]=o;e.tableCellAlignToStyle&&l==="align"&&typeof c=="string"&&n2.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 h2(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 wo(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 wo(e,n.position);else o=a.value===null?!0:a.value;s[r]=o}return s}function qu(e,n){const s=[];let a=-1;const r=e.passKeys?new Map:ZE;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=qb(e,o,l);c!==void 0&&s.push(c)}return s}function p2(e,n,s){const a=BE(e.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=a.commaSeparated?ME(s):VE(s)),a.property==="style"){let r=typeof s=="object"?s:f2(e,String(s));return e.stylePropertyNameCase==="css"&&(r=g2(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&a.space?OE[a.property]||a.property:a.attribute,s]}}function f2(e,n){try{return QE(n,{reactCompat:!0})}catch(s){if(e.ignoreInvalidStyle)return{};const a=s,r=new $s("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=Hb+"#cannot-parse-style-attribute",r}}function Wb(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=Ih(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=Ih(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(a.type==="Literal"){const r=a.value;return Uu.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(a);wo(e)}function wo(e,n){const s=new $s("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=Hb+"#cannot-handle-mdx-estrees-without-createevaluater",s}function g2(e){const n={};let s;for(s in e)Uu.call(e,s)&&(n[b2(s)]=e[s]);return n}function b2(e){let n=e.replace(e2,x2);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function x2(e){return"-"+e.toLowerCase()}const qc={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"]},v2={};function Vu(e,n){const s=v2,a=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return Kb(e,a,r)}function Kb(e,n,s){if(y2(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 Hh(e.children,n,s)}return Array.isArray(e)?Hh(e,n,s):""}function Hh(e,n,s){const a=[];let r=-1;for(;++r<e.length;)a[r]=Kb(e[r],n,s);return a.join("")}function y2(e){return!!(e&&typeof e=="object")}const qh=document.createElement("i");function Wu(e){const n="&"+e+";";qh.innerHTML=n;const s=qh.textContent;return s.charCodeAt(s.length-1)===59&&e!=="semi"||s===n?!1:s}function Qs(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 ri(e,n){return e.length>0?(Qs(e,e.length,0,n),e):n}const Vh={}.hasOwnProperty;function Gb(e){const n={};let s=-1;for(;++s<e.length;)w2(n,e[s]);return n}function w2(e,n){let s;for(s in n){const r=(Vh.call(e,s)?e[s]:void 0)||(e[s]={}),o=n[s];let l;if(o)for(l in o){Vh.call(r,l)||(r[l]=[]);const c=o[l];k2(r[l],Array.isArray(c)?c:c?[c]:[])}}}function k2(e,n){let s=-1;const a=[];for(;++s<n.length;)(n[s].add==="after"?e:a).push(n[s]);Qs(e,0,0,a)}function Jb(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 vi(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const zs=ua(/[A-Za-z]/),Is=ua(/[\dA-Za-z]/),j2=ua(/[#-'*+\--9=?A-Z^-~]/);function Fl(e){return e!==null&&(e<32||e===127)}const au=ua(/\d/),N2=ua(/[\dA-Fa-f]/),S2=ua(/[!-/:-@[-`{-~]/);function Qt(e){return e!==null&&e<-2}function Bn(e){return e!==null&&(e<0||e===32)}function yn(e){return e===-2||e===-1||e===32}const mc=ua(/\p{P}|\p{S}/u),Oa=ua(/\s/);function ua(e){return n;function n(s){return s!==null&&s>-1&&e.test(String.fromCharCode(s))}}function Pr(e){const n=[];let s=-1,a=0,r=0;for(;++s<e.length;){const o=e.charCodeAt(s);let l="";if(o===37&&Is(e.charCodeAt(s+1))&&Is(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 jn(e,n,s,a){const r=a?a-1:Number.POSITIVE_INFINITY;let o=0;return l;function l(d){return yn(d)?(e.enter(s),c(d)):n(d)}function c(d){return yn(d)&&o++<r?(e.consume(d),c):(e.exit(s),n(d))}}const C2={tokenize:E2};function E2(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"),jn(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 Qt(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),l)}}const _2={tokenize:M2},Wh={tokenize:A2};function M2(e){const n=this,s=[];let a=0,r,o,l;return c;function c(N){if(a<s.length){const k=s[a];return n.containerState=k[1],e.attempt(k[0].continuation,d,u)(N)}return u(N)}function d(N){if(a++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&v();const k=n.events.length;let E=k,y;for(;E--;)if(n.events[E][0]==="exit"&&n.events[E][1].type==="chunkFlow"){y=n.events[E][1].end;break}b(a);let j=k;for(;j<n.events.length;)n.events[j][1].end={...y},j++;return Qs(n.events,E+1,0,n.events.slice(k)),n.events.length=j,u(N)}return c(N)}function u(N){if(a===s.length){if(!r)return f(N);if(r.currentConstruct&&r.currentConstruct.concrete)return g(N);n.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return n.containerState={},e.check(Wh,m,h)(N)}function m(N){return r&&v(),b(a),f(N)}function h(N){return n.parser.lazy[n.now().line]=a!==s.length,l=n.now().offset,g(N)}function f(N){return n.containerState={},e.attempt(Wh,p,g)(N)}function p(N){return a++,s.push([n.currentConstruct,n.containerState]),f(N)}function g(N){if(N===null){r&&v(),b(0),e.consume(N);return}return r=r||n.parser.flow(n.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:o}),x(N)}function x(N){if(N===null){w(e.exit("chunkFlow"),!0),b(0),e.consume(N);return}return Qt(N)?(e.consume(N),w(e.exit("chunkFlow")),a=0,n.interrupt=void 0,c):(e.consume(N),x)}function w(N,k){const E=n.sliceStream(N);if(k&&E.push(null),N.previous=o,o&&(o.next=N),o=N,r.defineSkip(N.start),r.write(E),n.parser.lazy[N.start.line]){let y=r.events.length;for(;y--;)if(r.events[y][1].start.offset<l&&(!r.events[y][1].end||r.events[y][1].end.offset>l))return;const j=n.events.length;let P=j,F,_;for(;P--;)if(n.events[P][0]==="exit"&&n.events[P][1].type==="chunkFlow"){if(F){_=n.events[P][1].end;break}F=!0}for(b(a),y=j;y<n.events.length;)n.events[y][1].end={..._},y++;Qs(n.events,P+1,0,n.events.slice(j)),n.events.length=y}}function b(N){let k=s.length;for(;k-- >N;){const E=s[k];n.containerState=E[1],E[0].exit.call(n,e)}s.length=N}function v(){r.write([null]),o=void 0,r=void 0,n.containerState._closeFlow=void 0}}function A2(e,n,s){return jn(e,e.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function yr(e){if(e===null||Bn(e)||Oa(e))return 1;if(mc(e))return 2}function hc(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 ru={name:"attention",resolveAll:R2,tokenize:P2};function R2(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};Kh(h,-d),Kh(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=ri(u,[["enter",e[a][1],n],["exit",e[a][1],n]])),u=ri(u,[["enter",r,n],["enter",l,n],["exit",l,n],["enter",o,n]]),u=ri(u,hc(n.parser.constructs.insideSpan.null,e.slice(a+1,s),n)),u=ri(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=ri(u,[["enter",e[s][1],n],["exit",e[s][1],n]])):m=0,Qs(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 P2(e,n){const s=this.parser.constructs.attentionMarkers.null,a=this.previous,r=yr(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=yr(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 Kh(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const I2={name:"autolink",tokenize:T2};function T2(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 zs(p)?(e.consume(p),l):p===64?s(p):u(p)}function l(p){return p===43||p===45||p===46||Is(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||Is(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||Fl(p)?s(p):(e.consume(p),d)}function u(p){return p===64?(e.consume(p),m):j2(p)?(e.consume(p),u):s(p)}function m(p){return Is(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||Is(p))&&a++<63){const g=p===45?f:h;return e.consume(p),g}return s(p)}}const Bo={partial:!0,tokenize:$2};function $2(e,n,s){return a;function a(o){return yn(o)?jn(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||Qt(o)?n(o):s(o)}}const Yb={continuation:{tokenize:L2},exit:O2,name:"blockQuote",tokenize:D2};function D2(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 yn(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(l))}}function L2(e,n,s){const a=this;return r;function r(l){return yn(l)?jn(e,o,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(Yb,n,s)(l)}}function O2(e){e.exit("blockQuote")}const Qb={name:"characterEscape",tokenize:z2};function z2(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 S2(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):s(o)}}const Xb={name:"characterReference",tokenize:F2};function F2(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=Is,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=N2,m):(e.enter("characterReferenceValue"),o=7,l=au,m(h))}function m(h){if(h===59&&r){const f=e.exit("characterReferenceValue");return l===Is&&!Wu(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 Gh={partial:!0,tokenize:U2},Jh={concrete:!0,name:"codeFenced",tokenize:B2};function B2(e,n,s){const a=this,r={partial:!0,tokenize:E};let o=0,l=0,c;return d;function d(y){return u(y)}function u(y){const j=a.events[a.events.length-1];return o=j&&j[1].type==="linePrefix"?j[2].sliceSerialize(j[1],!0).length:0,c=y,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),m(y)}function m(y){return y===c?(l++,e.consume(y),m):l<3?s(y):(e.exit("codeFencedFenceSequence"),yn(y)?jn(e,h,"whitespace")(y):h(y))}function h(y){return y===null||Qt(y)?(e.exit("codeFencedFence"),a.interrupt?n(y):e.check(Gh,x,k)(y)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(y))}function f(y){return y===null||Qt(y)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(y)):yn(y)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),jn(e,p,"whitespace")(y)):y===96&&y===c?s(y):(e.consume(y),f)}function p(y){return y===null||Qt(y)?h(y):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(y))}function g(y){return y===null||Qt(y)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),h(y)):y===96&&y===c?s(y):(e.consume(y),g)}function x(y){return e.attempt(r,k,w)(y)}function w(y){return e.enter("lineEnding"),e.consume(y),e.exit("lineEnding"),b}function b(y){return o>0&&yn(y)?jn(e,v,"linePrefix",o+1)(y):v(y)}function v(y){return y===null||Qt(y)?e.check(Gh,x,k)(y):(e.enter("codeFlowValue"),N(y))}function N(y){return y===null||Qt(y)?(e.exit("codeFlowValue"),v(y)):(e.consume(y),N)}function k(y){return e.exit("codeFenced"),n(y)}function E(y,j,P){let F=0;return _;function _($){return y.enter("lineEnding"),y.consume($),y.exit("lineEnding"),R}function R($){return y.enter("codeFencedFence"),yn($)?jn(y,L,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)($):L($)}function L($){return $===c?(y.enter("codeFencedFenceSequence"),U($)):P($)}function U($){return $===c?(F++,y.consume($),U):F>=l?(y.exit("codeFencedFenceSequence"),yn($)?jn(y,C,"whitespace")($):C($)):P($)}function C($){return $===null||Qt($)?(y.exit("codeFencedFence"),j($)):P($)}}}function U2(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 Vc={name:"codeIndented",tokenize:q2},H2={partial:!0,tokenize:V2};function q2(e,n,s){const a=this;return r;function r(u){return e.enter("codeIndented"),jn(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):Qt(u)?e.attempt(H2,l,d)(u):(e.enter("codeFlowValue"),c(u))}function c(u){return u===null||Qt(u)?(e.exit("codeFlowValue"),l(u)):(e.consume(u),c)}function d(u){return e.exit("codeIndented"),n(u)}}function V2(e,n,s){const a=this;return r;function r(l){return a.parser.lazy[a.now().line]?s(l):Qt(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r):jn(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):Qt(l)?r(l):s(l)}}const W2={name:"codeText",previous:G2,resolve:K2,tokenize:J2};function K2(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 G2(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function J2(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)):Qt(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||Qt(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 Y2{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&&Hr(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),Hr(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),Hr(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);Hr(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);Hr(this.left,s.reverse())}}}function Hr(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 Zb(e){const n={};let s=-1,a,r,o,l,c,d,u;const m=new Y2(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,Q2(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 Qs(e,0,Number.POSITIVE_INFINITY,m.slice(0)),!u}function Q2(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]),v=o.pop();d.push([v,v+b.length-1]),e.splice(v,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 X2={resolve:e_,tokenize:t_},Z2={partial:!0,tokenize:n_};function e_(e){return Zb(e),e}function t_(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):Qt(c)?e.check(Z2,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 n_(e,n,s){const a=this;return r;function r(l){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),jn(e,o,"linePrefix")}function o(l){if(l===null||Qt(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 ex(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||Fl(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||Qt(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||Fl(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 tx(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):Qt(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||Qt(p)||c++>999?(e.exit("chunkString"),m(p)):(e.consume(p),d||(d=!yn(p)),p===92?f:h)}function f(p){return p===91||p===92||p===93?(e.consume(p),c++,h):h(p)}}function nx(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):Qt(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),jn(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),m(f))}function m(f){return f===l||f===null||Qt(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 po(e,n){let s;return a;function a(r){return Qt(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s=!0,a):yn(r)?jn(e,a,s?"linePrefix":"lineSuffix")(r):n(r)}}const s_={name:"definition",tokenize:a_},i_={partial:!0,tokenize:r_};function a_(e,n,s){const a=this;let r;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return tx.call(a,e,c,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function c(p){return r=vi(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)?po(e,u)(p):u(p)}function u(p){return ex(e,m,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function m(p){return e.attempt(i_,h,h)(p)}function h(p){return yn(p)?jn(e,f,"whitespace")(p):f(p)}function f(p){return p===null||Qt(p)?(e.exit("definition"),a.parser.defined.push(r),n(p)):s(p)}}function r_(e,n,s){return a;function a(c){return Bn(c)?po(e,r)(c):s(c)}function r(c){return nx(e,o,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return yn(c)?jn(e,l,"whitespace")(c):l(c)}function l(c){return c===null||Qt(c)?n(c):s(c)}}const o_={name:"hardBreakEscape",tokenize:l_};function l_(e,n,s){return a;function a(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return Qt(o)?(e.exit("hardBreakEscape"),n(o)):s(o)}}const c_={name:"headingAtx",resolve:d_,tokenize:u_};function d_(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"},Qs(e,a,s-a+1,[["enter",r,n],["enter",o,n],["exit",o,n],["exit",r,n]])),e}function u_(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||Qt(m)?(e.exit("atxHeading"),n(m)):yn(m)?jn(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 m_=["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"],Yh=["pre","script","style","textarea"],h_={concrete:!0,name:"htmlFlow",resolveTo:g_,tokenize:b_},p_={partial:!0,tokenize:v_},f_={partial:!0,tokenize:x_};function g_(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 b_(e,n,s){const a=this;let r,o,l,c,d;return u;function u(S){return m(S)}function m(S){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(S),h}function h(S){return S===33?(e.consume(S),f):S===47?(e.consume(S),o=!0,x):S===63?(e.consume(S),r=3,a.interrupt?n:A):zs(S)?(e.consume(S),l=String.fromCharCode(S),w):s(S)}function f(S){return S===45?(e.consume(S),r=2,p):S===91?(e.consume(S),r=5,c=0,g):zs(S)?(e.consume(S),r=4,a.interrupt?n:A):s(S)}function p(S){return S===45?(e.consume(S),a.interrupt?n:A):s(S)}function g(S){const G="CDATA[";return S===G.charCodeAt(c++)?(e.consume(S),c===G.length?a.interrupt?n:L:g):s(S)}function x(S){return zs(S)?(e.consume(S),l=String.fromCharCode(S),w):s(S)}function w(S){if(S===null||S===47||S===62||Bn(S)){const G=S===47,he=l.toLowerCase();return!G&&!o&&Yh.includes(he)?(r=1,a.interrupt?n(S):L(S)):m_.includes(l.toLowerCase())?(r=6,G?(e.consume(S),b):a.interrupt?n(S):L(S)):(r=7,a.interrupt&&!a.parser.lazy[a.now().line]?s(S):o?v(S):N(S))}return S===45||Is(S)?(e.consume(S),l+=String.fromCharCode(S),w):s(S)}function b(S){return S===62?(e.consume(S),a.interrupt?n:L):s(S)}function v(S){return yn(S)?(e.consume(S),v):_(S)}function N(S){return S===47?(e.consume(S),_):S===58||S===95||zs(S)?(e.consume(S),k):yn(S)?(e.consume(S),N):_(S)}function k(S){return S===45||S===46||S===58||S===95||Is(S)?(e.consume(S),k):E(S)}function E(S){return S===61?(e.consume(S),y):yn(S)?(e.consume(S),E):N(S)}function y(S){return S===null||S===60||S===61||S===62||S===96?s(S):S===34||S===39?(e.consume(S),d=S,j):yn(S)?(e.consume(S),y):P(S)}function j(S){return S===d?(e.consume(S),d=null,F):S===null||Qt(S)?s(S):(e.consume(S),j)}function P(S){return S===null||S===34||S===39||S===47||S===60||S===61||S===62||S===96||Bn(S)?E(S):(e.consume(S),P)}function F(S){return S===47||S===62||yn(S)?N(S):s(S)}function _(S){return S===62?(e.consume(S),R):s(S)}function R(S){return S===null||Qt(S)?L(S):yn(S)?(e.consume(S),R):s(S)}function L(S){return S===45&&r===2?(e.consume(S),V):S===60&&r===1?(e.consume(S),Y):S===62&&r===4?(e.consume(S),I):S===63&&r===3?(e.consume(S),A):S===93&&r===5?(e.consume(S),q):Qt(S)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(p_,D,U)(S)):S===null||Qt(S)?(e.exit("htmlFlowData"),U(S)):(e.consume(S),L)}function U(S){return e.check(f_,C,D)(S)}function C(S){return e.enter("lineEnding"),e.consume(S),e.exit("lineEnding"),$}function $(S){return S===null||Qt(S)?U(S):(e.enter("htmlFlowData"),L(S))}function V(S){return S===45?(e.consume(S),A):L(S)}function Y(S){return S===47?(e.consume(S),l="",ne):L(S)}function ne(S){if(S===62){const G=l.toLowerCase();return Yh.includes(G)?(e.consume(S),I):L(S)}return zs(S)&&l.length<8?(e.consume(S),l+=String.fromCharCode(S),ne):L(S)}function q(S){return S===93?(e.consume(S),A):L(S)}function A(S){return S===62?(e.consume(S),I):S===45&&r===2?(e.consume(S),A):L(S)}function I(S){return S===null||Qt(S)?(e.exit("htmlFlowData"),D(S)):(e.consume(S),I)}function D(S){return e.exit("htmlFlow"),n(S)}}function x_(e,n,s){const a=this;return r;function r(l){return Qt(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 v_(e,n,s){return a;function a(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(Bo,n,s)}}const y_={name:"htmlText",tokenize:w_};function w_(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),E):A===63?(e.consume(A),N):zs(A)?(e.consume(A),P):s(A)}function u(A){return A===45?(e.consume(A),m):A===91?(e.consume(A),o=0,g):zs(A)?(e.consume(A),v):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):Qt(A)?(l=h,Y(A)):(e.consume(A),h)}function f(A){return A===45?(e.consume(A),p):h(A)}function p(A){return A===62?V(A):A===45?f(A):h(A)}function g(A){const I="CDATA[";return A===I.charCodeAt(o++)?(e.consume(A),o===I.length?x:g):s(A)}function x(A){return A===null?s(A):A===93?(e.consume(A),w):Qt(A)?(l=x,Y(A)):(e.consume(A),x)}function w(A){return A===93?(e.consume(A),b):x(A)}function b(A){return A===62?V(A):A===93?(e.consume(A),b):x(A)}function v(A){return A===null||A===62?V(A):Qt(A)?(l=v,Y(A)):(e.consume(A),v)}function N(A){return A===null?s(A):A===63?(e.consume(A),k):Qt(A)?(l=N,Y(A)):(e.consume(A),N)}function k(A){return A===62?V(A):N(A)}function E(A){return zs(A)?(e.consume(A),y):s(A)}function y(A){return A===45||Is(A)?(e.consume(A),y):j(A)}function j(A){return Qt(A)?(l=j,Y(A)):yn(A)?(e.consume(A),j):V(A)}function P(A){return A===45||Is(A)?(e.consume(A),P):A===47||A===62||Bn(A)?F(A):s(A)}function F(A){return A===47?(e.consume(A),V):A===58||A===95||zs(A)?(e.consume(A),_):Qt(A)?(l=F,Y(A)):yn(A)?(e.consume(A),F):V(A)}function _(A){return A===45||A===46||A===58||A===95||Is(A)?(e.consume(A),_):R(A)}function R(A){return A===61?(e.consume(A),L):Qt(A)?(l=R,Y(A)):yn(A)?(e.consume(A),R):F(A)}function L(A){return A===null||A===60||A===61||A===62||A===96?s(A):A===34||A===39?(e.consume(A),r=A,U):Qt(A)?(l=L,Y(A)):yn(A)?(e.consume(A),L):(e.consume(A),C)}function U(A){return A===r?(e.consume(A),r=void 0,$):A===null?s(A):Qt(A)?(l=U,Y(A)):(e.consume(A),U)}function C(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),C)}function $(A){return A===47||A===62||Bn(A)?F(A):s(A)}function V(A){return A===62?(e.consume(A),e.exit("htmlTextData"),e.exit("htmlText"),n):s(A)}function Y(A){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(A),e.exit("lineEnding"),ne}function ne(A){return yn(A)?jn(e,q,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(A):q(A)}function q(A){return e.enter("htmlTextData"),l(A)}}const Ku={name:"labelEnd",resolveAll:S_,resolveTo:C_,tokenize:E_},k_={tokenize:__},j_={tokenize:M_},N_={tokenize:A_};function S_(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&&Qs(e,0,e.length,s),e}function C_(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=ri(c,e.slice(o+1,o+a+3)),c=ri(c,[["enter",m,n]]),c=ri(c,hc(n.parser.constructs.insideSpan.null,e.slice(o+a+4,l-3),n)),c=ri(c,[["exit",m,n],e[l-2],e[l-1],["exit",u,n]]),c=ri(c,e.slice(l+1)),c=ri(c,[["exit",d,n]]),Qs(e,o,e.length,c),e}function E_(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(vi(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(k_,m,l?m:h)(f):f===91?e.attempt(j_,m,l?u:h)(f):l?m(f):h(f)}function u(f){return e.attempt(N_,m,h)(f)}function m(f){return n(f)}function h(f){return o._balanced=!0,s(f)}}function __(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)?po(e,o)(h):o(h)}function o(h){return h===41?m(h):ex(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function l(h){return Bn(h)?po(e,d)(h):m(h)}function c(h){return s(h)}function d(h){return h===34||h===39||h===40?nx(e,u,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):m(h)}function u(h){return Bn(h)?po(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 M_(e,n,s){const a=this;return r;function r(c){return tx.call(a,e,o,l,"reference","referenceMarker","referenceString")(c)}function o(c){return a.parser.defined.includes(vi(a.sliceSerialize(a.events[a.events.length-1][1]).slice(1,-1)))?n(c):s(c)}function l(c){return s(c)}}function A_(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 R_={name:"labelStartImage",resolveAll:Ku.resolveAll,tokenize:P_};function P_(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 I_={name:"labelStartLink",resolveAll:Ku.resolveAll,tokenize:T_};function T_(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 Wc={name:"lineEnding",tokenize:$_};function $_(e,n){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),jn(e,n,"linePrefix")}}const Cl={name:"thematicBreak",tokenize:D_};function D_(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||Qt(u))?(e.exit("thematicBreak"),n(u)):s(u)}function d(u){return u===r?(e.consume(u),a++,d):(e.exit("thematicBreakSequence"),yn(u)?jn(e,c,"whitespace")(u):c(u))}}const Hs={continuation:{tokenize:F_},exit:U_,name:"list",tokenize:z_},L_={partial:!0,tokenize:H_},O_={partial:!0,tokenize:B_};function z_(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:au(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(Cl,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 au(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(Bo,a.interrupt?s:m,e.attempt(L_,f,h))}function m(p){return a.containerState.initialBlankLine=!0,o++,f(p)}function h(p){return yn(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 F_(e,n,s){const a=this;return a.containerState._closeFlow=void 0,e.check(Bo,r,o);function r(c){return a.containerState.furtherBlankLines=a.containerState.furtherBlankLines||a.containerState.initialBlankLine,jn(e,n,"listItemIndent",a.containerState.size+1)(c)}function o(c){return a.containerState.furtherBlankLines||!yn(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(O_,n,l)(c))}function l(c){return a.containerState._closeFlow=!0,a.interrupt=void 0,jn(e,e.attempt(Hs,n,s),"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function B_(e,n,s){const a=this;return jn(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 U_(e){e.exit(this.containerState.type)}function H_(e,n,s){const a=this;return jn(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!yn(o)&&l&&l[1].type==="listItemPrefixWhitespace"?n(o):s(o)}}const Qh={name:"setextUnderline",resolveTo:q_,tokenize:V_};function q_(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 V_(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"),yn(u)?jn(e,d,"lineSuffix")(u):d(u))}function d(u){return u===null||Qt(u)?(e.exit("setextHeadingLine"),n(u)):s(u)}}const W_={tokenize:K_};function K_(e){const n=this,s=e.attempt(Bo,a,e.attempt(this.parser.constructs.flowInitial,r,jn(e,e.attempt(this.parser.constructs.flow,r,e.attempt(X2,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 G_={resolveAll:ix()},J_=sx("string"),Y_=sx("text");function sx(e){return{resolveAll:ix(e==="text"?Q_: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 ix(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 Q_(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 X_={42:Hs,43:Hs,45:Hs,48:Hs,49:Hs,50:Hs,51:Hs,52:Hs,53:Hs,54:Hs,55:Hs,56:Hs,57:Hs,62:Yb},Z_={91:s_},eM={[-2]:Vc,[-1]:Vc,32:Vc},tM={35:c_,42:Cl,45:[Qh,Cl],60:h_,61:Qh,95:Cl,96:Jh,126:Jh},nM={38:Xb,92:Qb},sM={[-5]:Wc,[-4]:Wc,[-3]:Wc,33:R_,38:Xb,42:ru,60:[I2,y_],91:I_,92:[o_,Qb],93:Ku,95:ru,96:W2},iM={null:[ru,G_]},aM={null:[42,95]},rM={null:[]},oM=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:aM,contentInitial:Z_,disable:rM,document:X_,flow:tM,flowInitial:eM,insideSpan:iM,string:nM,text:sM},Symbol.toStringTag,{value:"Module"}));function lM(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:j(E),check:j(y),consume:v,enter:N,exit:k,interrupt:j(y,{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(R){return l=ri(l,R),w(),l[l.length-1]!==null?[]:(P(n,0),u.events=hc(o,u.events,u),u.events)}function f(R,L){return dM(p(R),L)}function p(R){return cM(l,R)}function g(){const{_bufferIndex:R,_index:L,line:U,column:C,offset:$}=a;return{_bufferIndex:R,_index:L,line:U,column:C,offset:$}}function x(R){r[R.line]=R.column,_()}function w(){let R;for(;a._index<l.length;){const L=l[a._index];if(typeof L=="string")for(R=a._index,a._bufferIndex<0&&(a._bufferIndex=0);a._index===R&&a._bufferIndex<L.length;)b(L.charCodeAt(a._bufferIndex));else b(L)}}function b(R){m=m(R)}function v(R){Qt(R)?(a.line++,a.column=1,a.offset+=R===-3?2:1,_()):R!==-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=R}function N(R,L){const U=L||{};return U.type=R,U.start=g(),u.events.push(["enter",U,u]),c.push(U),U}function k(R){const L=c.pop();return L.end=g(),u.events.push(["exit",L,u]),L}function E(R,L){P(R,L.from)}function y(R,L){L.restore()}function j(R,L){return U;function U(C,$,V){let Y,ne,q,A;return Array.isArray(C)?D(C):"tokenize"in C?D([C]):I(C);function I(Se){return Ue;function Ue(ce){const Ae=ce!==null&&Se[ce],X=ce!==null&&Se.null,Z=[...Array.isArray(Ae)?Ae:Ae?[Ae]:[],...Array.isArray(X)?X:X?[X]:[]];return D(Z)(ce)}}function D(Se){return Y=Se,ne=0,Se.length===0?V:S(Se[ne])}function S(Se){return Ue;function Ue(ce){return A=F(),q=Se,Se.partial||(u.currentConstruct=Se),Se.name&&u.parser.constructs.disable.null.includes(Se.name)?he():Se.tokenize.call(L?Object.assign(Object.create(u),L):u,d,G,he)(ce)}}function G(Se){return R(q,A),$}function he(Se){return A.restore(),++ne<Y.length?S(Y[ne]):V}}}function P(R,L){R.resolveAll&&!o.includes(R)&&o.push(R),R.resolve&&Qs(u.events,L,u.events.length-L,R.resolve(u.events.slice(L),u)),R.resolveTo&&(u.events=R.resolveTo(u.events,u))}function F(){const R=g(),L=u.previous,U=u.currentConstruct,C=u.events.length,$=Array.from(c);return{from:C,restore:V};function V(){a=R,u.previous=L,u.currentConstruct=U,u.events.length=C,c=$,_()}}function _(){a.line in r&&a.column<2&&(a.column=r[a.line],a.offset+=r[a.line]-1)}}function cM(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 dM(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 uM(e){const a={constructs:Gb([oM,...(e||{}).extensions||[]]),content:r(C2),defined:[],document:r(_2),flow:r(W_),lazy:{},string:r(J_),text:r(Y_)};return a;function r(o){return l;function l(c){return lM(a,o,c)}}}function mM(e){for(;!Zb(e););return e}const Xh=/[\0\t\n\r]/g;function hM(){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(Xh.lastIndex=h,u=Xh.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 pM=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function fM(e){return e.replace(pM,gM)}function gM(e,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),o=r===120||r===88;return Jb(s.slice(o?2:1),o?16:10)}return Wu(s)||e}const ax={}.hasOwnProperty;function bM(e,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),xM(s)(mM(uM(s).document().write(hM()(e,n,!0))))}function xM(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(we),autolinkProtocol:F,autolinkEmail:F,atxHeading:o(O),blockQuote:o(X),characterEscape:F,characterReference:F,codeFenced:o(Z),codeFencedFenceInfo:l,codeFencedFenceMeta:l,codeIndented:o(Z,l),codeText:o(ee,l),codeTextData:F,data:F,codeFlowValue:F,definition:o(le),definitionDestinationString:l,definitionLabelString:l,definitionTitleString:l,emphasis:o(K),hardBreakEscape:o(pe),hardBreakTrailing:o(pe),htmlFlow:o(ve,l),htmlFlowData:F,htmlText:o(ve,l),htmlTextData:F,image:o(B),label:l,link:o(we),listItem:o(re),listItemValue:f,listOrdered:o(ze,h),listUnordered:o(ze),paragraph:o(He),reference:S,referenceString:l,resourceDestinationString:l,resourceTitleString:l,setextHeading:o(O),strong:o(Pe),thematicBreak:o(qe)},exit:{atxHeading:d(),atxHeadingSequence:E,autolink:d(),autolinkEmail:Ae,autolinkProtocol:ce,blockQuote:d(),characterEscapeValue:_,characterReferenceMarkerHexadecimal:he,characterReferenceMarkerNumeric:he,characterReferenceValue:Se,characterReference:Ue,codeFenced:d(w),codeFencedFence:x,codeFencedFenceInfo:p,codeFencedFenceMeta:g,codeFlowValue:_,codeIndented:d(b),codeText:d($),codeTextData:_,data:_,definition:d(),definitionDestinationString:k,definitionLabelString:v,definitionTitleString:N,emphasis:d(),hardBreakEscape:d(L),hardBreakTrailing:d(L),htmlFlow:d(U),htmlFlowData:_,htmlText:d(C),htmlTextData:_,image:d(Y),label:q,labelText:ne,lineEnding:R,link:d(V),listItem:d(),listOrdered:d(),listUnordered:d(),paragraph:d(),referenceString:G,resourceDestinationString:A,resourceTitleString:I,resource:D,setextHeading:d(P),setextHeadingLineSequence:j,setextHeadingText:y,strong:d(),thematicBreak:d()}};rx(n,(e||{}).mdastExtensions||[]);const s={};return a;function a(de){let De={type:"root",children:[]};const Te={stack:[De],tokenStack:[],config:n,enter:c,exit:u,buffer:l,resume:m,data:s},ct=[];let Ve=-1;for(;++Ve<de.length;)if(de[Ve][1].type==="listOrdered"||de[Ve][1].type==="listUnordered")if(de[Ve][0]==="enter")ct.push(Ve);else{const me=ct.pop();Ve=r(de,me,Ve)}for(Ve=-1;++Ve<de.length;){const me=n[de[Ve][0]];ax.call(me,de[Ve][1].type)&&me[de[Ve][1].type].call(Object.assign({sliceSerialize:de[Ve][2].sliceSerialize},Te),de[Ve][1])}if(Te.tokenStack.length>0){const me=Te.tokenStack[Te.tokenStack.length-1];(me[1]||Zh).call(Te,void 0,me[0])}for(De.position={start:Zi(de.length>0?de[0][1].start:{line:1,column:1,offset:0}),end:Zi(de.length>0?de[de.length-2][1].end:{line:1,column:1,offset:0})},Ve=-1;++Ve<n.transforms.length;)De=n.transforms[Ve](De)||De;return De}function r(de,De,Te){let ct=De-1,Ve=-1,me=!1,oe,Me,Xe,rt;for(;++ct<=Te;){const ht=de[ct];switch(ht[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{ht[0]==="enter"?Ve++:Ve--,rt=void 0;break}case"lineEndingBlank":{ht[0]==="enter"&&(oe&&!rt&&!Ve&&!Xe&&(Xe=ct),rt=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:rt=void 0}if(!Ve&&ht[0]==="enter"&&ht[1].type==="listItemPrefix"||Ve===-1&&ht[0]==="exit"&&(ht[1].type==="listUnordered"||ht[1].type==="listOrdered")){if(oe){let yt=ct;for(Me=void 0;yt--;){const Re=de[yt];if(Re[1].type==="lineEnding"||Re[1].type==="lineEndingBlank"){if(Re[0]==="exit")continue;Me&&(de[Me][1].type="lineEndingBlank",me=!0),Re[1].type="lineEnding",Me=yt}else if(!(Re[1].type==="linePrefix"||Re[1].type==="blockQuotePrefix"||Re[1].type==="blockQuotePrefixWhitespace"||Re[1].type==="blockQuoteMarker"||Re[1].type==="listItemIndent"))break}Xe&&(!Me||Xe<Me)&&(oe._spread=!0),oe.end=Object.assign({},Me?de[Me][1].start:ht[1].end),de.splice(Me||ct,0,["exit",oe,ht[2]]),ct++,Te++}if(ht[1].type==="listItemPrefix"){const yt={type:"listItem",_spread:!1,start:Object.assign({},ht[1].start),end:void 0};oe=yt,de.splice(ct,0,["enter",yt,ht[2]]),ct++,Te++,Xe=void 0,rt=!0}}}return de[De][1]._spread=me,Te}function o(de,De){return Te;function Te(ct){c.call(this,de(ct),ct),De&&De.call(this,ct)}}function l(){this.stack.push({type:"fragment",children:[]})}function c(de,De,Te){this.stack[this.stack.length-1].children.push(de),this.stack.push(de),this.tokenStack.push([De,Te||void 0]),de.position={start:Zi(De.start),end:void 0}}function d(de){return De;function De(Te){de&&de.call(this,Te),u.call(this,Te)}}function u(de,De){const Te=this.stack.pop(),ct=this.tokenStack.pop();if(ct)ct[0].type!==de.type&&(De?De.call(this,de,ct[0]):(ct[1]||Zh).call(this,de,ct[0]));else throw new Error("Cannot close `"+de.type+"` ("+ho({start:de.start,end:de.end})+"): it’s not open");Te.position.end=Zi(de.end)}function m(){return Vu(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function f(de){if(this.data.expectingFirstListItemValue){const De=this.stack[this.stack.length-2];De.start=Number.parseInt(this.sliceSerialize(de),10),this.data.expectingFirstListItemValue=void 0}}function p(){const de=this.resume(),De=this.stack[this.stack.length-1];De.lang=de}function g(){const de=this.resume(),De=this.stack[this.stack.length-1];De.meta=de}function x(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function w(){const de=this.resume(),De=this.stack[this.stack.length-1];De.value=de.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function b(){const de=this.resume(),De=this.stack[this.stack.length-1];De.value=de.replace(/(\r?\n|\r)$/g,"")}function v(de){const De=this.resume(),Te=this.stack[this.stack.length-1];Te.label=De,Te.identifier=vi(this.sliceSerialize(de)).toLowerCase()}function N(){const de=this.resume(),De=this.stack[this.stack.length-1];De.title=de}function k(){const de=this.resume(),De=this.stack[this.stack.length-1];De.url=de}function E(de){const De=this.stack[this.stack.length-1];if(!De.depth){const Te=this.sliceSerialize(de).length;De.depth=Te}}function y(){this.data.setextHeadingSlurpLineEnding=!0}function j(de){const De=this.stack[this.stack.length-1];De.depth=this.sliceSerialize(de).codePointAt(0)===61?1:2}function P(){this.data.setextHeadingSlurpLineEnding=void 0}function F(de){const Te=this.stack[this.stack.length-1].children;let ct=Te[Te.length-1];(!ct||ct.type!=="text")&&(ct=tt(),ct.position={start:Zi(de.start),end:void 0},Te.push(ct)),this.stack.push(ct)}function _(de){const De=this.stack.pop();De.value+=this.sliceSerialize(de),De.position.end=Zi(de.end)}function R(de){const De=this.stack[this.stack.length-1];if(this.data.atHardBreak){const Te=De.children[De.children.length-1];Te.position.end=Zi(de.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(De.type)&&(F.call(this,de),_.call(this,de))}function L(){this.data.atHardBreak=!0}function U(){const de=this.resume(),De=this.stack[this.stack.length-1];De.value=de}function C(){const de=this.resume(),De=this.stack[this.stack.length-1];De.value=de}function $(){const de=this.resume(),De=this.stack[this.stack.length-1];De.value=de}function V(){const de=this.stack[this.stack.length-1];if(this.data.inReference){const De=this.data.referenceType||"shortcut";de.type+="Reference",de.referenceType=De,delete de.url,delete de.title}else delete de.identifier,delete de.label;this.data.referenceType=void 0}function Y(){const de=this.stack[this.stack.length-1];if(this.data.inReference){const De=this.data.referenceType||"shortcut";de.type+="Reference",de.referenceType=De,delete de.url,delete de.title}else delete de.identifier,delete de.label;this.data.referenceType=void 0}function ne(de){const De=this.sliceSerialize(de),Te=this.stack[this.stack.length-2];Te.label=fM(De),Te.identifier=vi(De).toLowerCase()}function q(){const de=this.stack[this.stack.length-1],De=this.resume(),Te=this.stack[this.stack.length-1];if(this.data.inReference=!0,Te.type==="link"){const ct=de.children;Te.children=ct}else Te.alt=De}function A(){const de=this.resume(),De=this.stack[this.stack.length-1];De.url=de}function I(){const de=this.resume(),De=this.stack[this.stack.length-1];De.title=de}function D(){this.data.inReference=void 0}function S(){this.data.referenceType="collapsed"}function G(de){const De=this.resume(),Te=this.stack[this.stack.length-1];Te.label=De,Te.identifier=vi(this.sliceSerialize(de)).toLowerCase(),this.data.referenceType="full"}function he(de){this.data.characterReferenceType=de.type}function Se(de){const De=this.sliceSerialize(de),Te=this.data.characterReferenceType;let ct;Te?(ct=Jb(De,Te==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):ct=Wu(De);const Ve=this.stack[this.stack.length-1];Ve.value+=ct}function Ue(de){const De=this.stack.pop();De.position.end=Zi(de.end)}function ce(de){_.call(this,de);const De=this.stack[this.stack.length-1];De.url=this.sliceSerialize(de)}function Ae(de){_.call(this,de);const De=this.stack[this.stack.length-1];De.url="mailto:"+this.sliceSerialize(de)}function X(){return{type:"blockquote",children:[]}}function Z(){return{type:"code",lang:null,meta:null,value:""}}function ee(){return{type:"inlineCode",value:""}}function le(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function K(){return{type:"emphasis",children:[]}}function O(){return{type:"heading",depth:0,children:[]}}function pe(){return{type:"break"}}function ve(){return{type:"html",value:""}}function B(){return{type:"image",title:null,url:"",alt:null}}function we(){return{type:"link",title:null,url:"",children:[]}}function ze(de){return{type:"list",ordered:de.type==="listOrdered",start:null,spread:de._spread,children:[]}}function re(de){return{type:"listItem",spread:de._spread,checked:null,children:[]}}function He(){return{type:"paragraph",children:[]}}function Pe(){return{type:"strong",children:[]}}function tt(){return{type:"text",value:""}}function qe(){return{type:"thematicBreak"}}}function Zi(e){return{line:e.line,column:e.column,offset:e.offset}}function rx(e,n){let s=-1;for(;++s<n.length;){const a=n[s];Array.isArray(a)?rx(e,a):vM(e,a)}}function vM(e,n){let s;for(s in n)if(ax.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 Zh(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+ho({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+ho({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+ho({start:n.start,end:n.end})+") is still open")}function yM(e){const n=this;n.parser=s;function s(a){return bM(a,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function wM(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 kM(e,n){const s={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,s),[e.applyData(n,s),{type:"text",value:`
655
- `}]}function jM(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 NM(e,n){const s={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function SM(e,n){const s={type:"element",tagName:"em",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function CM(e,n){const s=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",a=String(n.identifier).toUpperCase(),r=Pr(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 EM(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 _M(e,n){if(e.options.allowDangerousHtml){const s={type:"raw",value:n.value};return e.patch(n,s),e.applyData(n,s)}}function ox(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 MM(e,n){const s=String(n.identifier).toUpperCase(),a=e.definitionById.get(s);if(!a)return ox(e,n);const r={src:Pr(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 AM(e,n){const s={src:Pr(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 RM(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 PM(e,n){const s=String(n.identifier).toUpperCase(),a=e.definitionById.get(s);if(!a)return ox(e,n);const r={href:Pr(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 IM(e,n){const s={href:Pr(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 TM(e,n,s){const a=e.all(n),r=s?$M(s):lx(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 $M(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=lx(s[a])}return n}function lx(e){const n=e.spread;return n??e.children.length>1}function DM(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 LM(e,n){const s={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function OM(e,n){const s={type:"root",children:e.wrap(e.all(n))};return e.patch(n,s),e.applyData(n,s)}function zM(e,n){const s={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function FM(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=Bu(n.children[1]),d=Bb(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 BM(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 UM(e,n){const s={type:"element",tagName:"td",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}const ep=9,tp=32;function HM(e){const n=String(e),s=/\r?\n|\r/g;let a=s.exec(n),r=0;const o=[];for(;a;)o.push(np(n.slice(r,a.index),r>0,!0),a[0]),r=a.index+a[0].length,a=s.exec(n);return o.push(np(n.slice(r),r>0,!1)),o.join("")}function np(e,n,s){let a=0,r=e.length;if(n){let o=e.codePointAt(a);for(;o===ep||o===tp;)a++,o=e.codePointAt(a)}if(s){let o=e.codePointAt(r-1);for(;o===ep||o===tp;)r--,o=e.codePointAt(r-1)}return r>a?e.slice(a,r):""}function qM(e,n){const s={type:"text",value:HM(String(n.value))};return e.patch(n,s),e.applyData(n,s)}function VM(e,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,s),e.applyData(n,s)}const WM={blockquote:wM,break:kM,code:jM,delete:NM,emphasis:SM,footnoteReference:CM,heading:EM,html:_M,imageReference:MM,image:AM,inlineCode:RM,linkReference:PM,link:IM,listItem:TM,list:DM,paragraph:LM,root:OM,strong:zM,table:FM,tableCell:UM,tableRow:BM,text:qM,thematicBreak:VM,toml:Qo,yaml:Qo,definition:Qo,footnoteDefinition:Qo};function Qo(){}const cx=-1,pc=0,fo=1,Bl=2,Gu=3,Ju=4,Yu=5,Qu=6,dx=7,ux=8,sp=typeof self=="object"?self:globalThis,KM=(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 pc:case cx:return s(l,r);case fo:{const c=s([],r);for(const d of l)c.push(a(d));return c}case Bl:{const c=s({},r);for(const[d,u]of l)c[a(d)]=a(u);return c}case Gu:return s(new Date(l),r);case Ju:{const{source:c,flags:d}=l;return s(new RegExp(c,d),r)}case Yu:{const c=s(new Map,r);for(const[d,u]of l)c.set(a(d),a(u));return c}case Qu:{const c=s(new Set,r);for(const d of l)c.add(a(d));return c}case dx:{const{name:c,message:d}=l;return s(new sp[c](d),r)}case ux: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 sp[o](l),r)};return a},ip=e=>KM(new Map,e)(0),tr="",{toString:GM}={},{keys:JM}=Object,qr=e=>{const n=typeof e;if(n!=="object"||!e)return[pc,n];const s=GM.call(e).slice(8,-1);switch(s){case"Array":return[fo,tr];case"Object":return[Bl,tr];case"Date":return[Gu,tr];case"RegExp":return[Ju,tr];case"Map":return[Yu,tr];case"Set":return[Qu,tr];case"DataView":return[fo,s]}return s.includes("Array")?[fo,s]:s.includes("Error")?[dx,s]:[Bl,s]},Xo=([e,n])=>e===pc&&(n==="function"||n==="symbol"),YM=(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]=qr(l);switch(c){case pc:{let m=l;switch(d){case"bigint":c=ux,m=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+d);m=null;break;case"undefined":return r([cx],l)}return r([c,m],l)}case fo:{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 Bl:{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 JM(l))(e||!Xo(qr(l[f])))&&m.push([o(f),o(l[f])]);return h}case Gu:return r([c,l.toISOString()],l);case Ju:{const{source:m,flags:h}=l;return r([c,{source:m,flags:h}],l)}case Yu:{const m=[],h=r([c,m],l);for(const[f,p]of l)(e||!(Xo(qr(f))||Xo(qr(p))))&&m.push([o(f),o(p)]);return h}case Qu:{const m=[],h=r([c,m],l);for(const f of l)(e||!Xo(qr(f)))&&m.push(o(f));return h}}const{message:u}=l;return r([c,{name:d,message:u}],l)};return o},ap=(e,{json:n,lossy:s}={})=>{const a=[];return YM(!(n||s),!!n,new Map,a)(e),a},Ul=typeof structuredClone=="function"?(e,n)=>n&&("json"in n||"lossy"in n)?ip(ap(e,n)):structuredClone(e):(e,n)=>ip(ap(e,n));function QM(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 XM(e,n){return"Back to reference "+(e+1)+(n>1?"-"+n:"")}function ZM(e){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=e.options.footnoteBackContent||QM,a=e.options.footnoteBackLabel||XM,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=Pr(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 v=typeof s=="string"?s:s(d,p);typeof v=="string"&&(v={type:"text",value:v}),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(v)?v:[v]})}const w=m[m.length-1];if(w&&w.type==="element"&&w.tagName==="p"){const v=w.children[w.children.length-1];v&&v.type==="text"?v.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:{...Ul(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 fc=(function(e){if(e==null)return sA;if(typeof e=="function")return gc(e);if(typeof e=="object")return Array.isArray(e)?eA(e):tA(e);if(typeof e=="string")return nA(e);throw new Error("Expected function, string, or object as test")});function eA(e){const n=[];let s=-1;for(;++s<e.length;)n[s]=fc(e[s]);return gc(a);function a(...r){let o=-1;for(;++o<n.length;)if(n[o].apply(this,r))return!0;return!1}}function tA(e){const n=e;return gc(s);function s(a){const r=a;let o;for(o in e)if(r[o]!==n[o])return!1;return!0}}function nA(e){return gc(n);function n(s){return s&&s.type===e}}function gc(e){return n;function n(s,a,r){return!!(iA(s)&&e.call(this,s,typeof a=="number"?a:void 0,r||void 0))}}function sA(){return!0}function iA(e){return e!==null&&typeof e=="object"&&"type"in e}const mx=[],aA=!0,ou=!1,rA="skip";function hx(e,n,s,a){let r;typeof n=="function"&&typeof s!="function"?(a=s,s=n):r=n;const o=fc(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=mx,g,x,w;if((!n||o(d,u,m[m.length-1]||void 0))&&(p=oA(s(d,m)),p[0]===ou))return p;if("children"in d&&d.children){const b=d;if(b.children&&p[0]!==rA)for(x=(a?b.children.length:-1)+l,w=m.concat(b);x>-1&&x<b.children.length;){const v=b.children[x];if(g=c(v,x,w)(),g[0]===ou)return g;x=typeof g[1]=="number"?g[1]:x+l}}return p}}}function oA(e){return Array.isArray(e)?e:typeof e=="number"?[aA,e]:e==null?mx:[e]}function Xu(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),hx(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 lu={}.hasOwnProperty,lA={};function cA(e,n){const s=n||lA,a=new Map,r=new Map,o=new Map,l={...WM,...s.handlers},c={all:u,applyData:uA,definitionById:a,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:l,one:d,options:s,patch:dA,wrap:hA};return Xu(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(lu.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=Ul(w);return b.children=c.all(m),b}return Ul(m)}return(c.options.unknownHandler||mA)(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=rp(g.value)),!Array.isArray(g)&&g.type==="element")){const x=g.children[0];x&&x.type==="text"&&(x.value=rp(x.value))}Array.isArray(g)?h.push(...g):h.push(g)}}}return h}}function dA(e,n){e.position&&(n.position=XE(e))}function uA(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,Ul(o)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function mA(e,n){const s=n.data||{},a="value"in n&&!(lu.call(s,"hProperties")||lu.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 hA(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 rp(e){let n=0,s=e.charCodeAt(n);for(;s===9||s===32;)n++,s=e.charCodeAt(n);return e.slice(n)}function op(e,n){const s=cA(e,n),a=s.one(e,void 0),r=ZM(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 pA(e,n){return e&&"run"in e?async function(s,a){const r=op(s,{file:a,...n});await e.run(r,a)}:function(s,a){return op(s,{file:a,...e||n})}}function lp(e){if(e)throw e}var Kc,cp;function fA(){if(cp)return Kc;cp=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 Kc=function d(){var u,m,h,f,p,g,x=arguments[0],w=1,b=arguments.length,v=!1;for(typeof x=="boolean"&&(v=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&&(v&&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(v,g,f)})):typeof f<"u"&&l(x,{name:m,newValue:f}));return x},Kc}var gA=fA();const Gc=Mg(gA);function cu(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 bA(){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?xA(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 xA(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 _i={basename:vA,dirname:yA,extname:wA,join:kA,sep:"/"};function vA(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');Uo(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 yA(e){if(Uo(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 wA(e){Uo(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 kA(...e){let n=-1,s;for(;++n<e.length;)Uo(e[n]),e[n]&&(s=s===void 0?e[n]:s+"/"+e[n]);return s===void 0?".":jA(s)}function jA(e){Uo(e);const n=e.codePointAt(0)===47;let s=NA(e,!n);return s.length===0&&!n&&(s="."),s.length>0&&e.codePointAt(e.length-1)===47&&(s+="/"),n?"/"+s:s}function NA(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 Uo(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const SA={cwd:CA};function CA(){return"/"}function du(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function EA(e){if(typeof e=="string")e=new URL(e);else if(!du(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 _A(e)}function _A(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 Jc=["history","path","basename","stem","extname","dirname"];class px{constructor(n){let s;n?du(n)?s={path:n}:typeof n=="string"||MA(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":SA.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let a=-1;for(;++a<Jc.length;){const o=Jc[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)Jc.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?_i.basename(this.path):void 0}set basename(n){Qc(n,"basename"),Yc(n,"basename"),this.path=_i.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?_i.dirname(this.path):void 0}set dirname(n){dp(this.basename,"dirname"),this.path=_i.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?_i.extname(this.path):void 0}set extname(n){if(Yc(n,"extname"),dp(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=_i.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){du(n)&&(n=EA(n)),Qc(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?_i.basename(this.path,this.extname):void 0}set stem(n){Qc(n,"stem"),Yc(n,"stem"),this.path=_i.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 $s(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 Yc(e,n){if(e&&e.includes(_i.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+_i.sep+"`")}function Qc(e,n){if(!e)throw new Error("`"+n+"` cannot be empty")}function dp(e,n){if(!e)throw new Error("Setting `"+n+"` requires `path` to be set too")}function MA(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const AA=(function(e){const a=this.constructor.prototype,r=a[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,a),o}),RA={}.hasOwnProperty;class Zu extends AA{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=bA()}copy(){const n=new Zu;let s=-1;for(;++s<this.attachers.length;){const a=this.attachers[s];n.use(...a)}return n.data(Gc(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(ed("data",this.frozen),this.namespace[n]=s,this):RA.call(this.namespace,n)&&this.namespace[n]||void 0:n?(ed("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=Zo(n),a=this.parser||this.Parser;return Xc("parse",a),a(String(s),s)}process(n,s){const a=this;return this.freeze(),Xc("process",this.parser||this.Parser),Zc("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(o,l){const c=Zo(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);TA(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(),Xc("processSync",this.parser||this.Parser),Zc("processSync",this.compiler||this.Compiler),this.process(n,r),mp("processSync","process",s),a;function r(o,l){s=!0,lp(o),a=l}}run(n,s,a){up(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=Zo(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),mp("runSync","run",a),r;function o(l,c){lp(l),r=c,a=!0}}stringify(n,s){this.freeze();const a=Zo(s),r=this.compiler||this.Compiler;return Zc("stringify",r),up(n),r(n,a)}use(n,...s){const a=this.attachers,r=this.namespace;if(ed("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=Gc(!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];cu(x)&&cu(p)&&(p=Gc(!0,x,p)),a[f]=[u,p,...g]}}}}const PA=new Zu().freeze();function Xc(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Zc(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function ed(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 up(e){if(!cu(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function mp(e,n,s){if(!s)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function Zo(e){return IA(e)?e:new px(e)}function IA(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function TA(e){return typeof e=="string"||$A(e)}function $A(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const DA="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",hp=[],pp={allowDangerousHtml:!0},LA=/^(https?|ircs?|mailto|xmpp)$/i,OA=[{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 wi(e){const n=zA(e),s=FA(e);return BA(n.runSync(n.parse(s),s),e)}function zA(e){const n=e.rehypePlugins||hp,s=e.remarkPlugins||hp,a=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...pp}:pp;return PA().use(yM).use(s).use(pA,a).use(n)}function FA(e){const n=e.children||"",s=new px;return typeof n=="string"&&(s.value=n),s}function BA(e,n){const s=n.allowedElements,a=n.allowElement,r=n.components,o=n.disallowedElements,l=n.skipHtml,c=n.unwrapDisallowed,d=n.urlTransform||UA;for(const m of OA)Object.hasOwn(n,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+DA+m.id,void 0);return Xu(e,u),s2(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 qc)if(Object.hasOwn(qc,p)&&Object.hasOwn(m.properties,p)){const g=m.properties[p],x=qc[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 UA(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||LA.test(e.slice(0,n))?e:""}function fp(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 HA(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function qA(e,n,s){const r=fc((s||{}).ignore||[]),o=VA(n);let l=-1;for(;++l<o.length;)hx(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,v=[];f.lastIndex=0;let N=f.exec(u.value);for(;N;){const k=N.index,E={index:N.index,input:N.input,stack:[...m,u]};let y=p(...N,E);if(typeof y=="string"&&(y=y.length>0?{type:"text",value:y}:void 0),y===!1?f.lastIndex=k+1:(g!==k&&v.push({type:"text",value:u.value.slice(g,k)}),Array.isArray(y)?v.push(...y):y&&v.push(y),g=k+N[0].length,b=!0),!f.global)break;N=f.exec(u.value)}return b?(g<u.value.length&&v.push({type:"text",value:u.value.slice(g)}),h.children.splice(w,1,...v)):v=[u],w+v.length}}function VA(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([WA(r[0]),KA(r[1])])}return n}function WA(e){return typeof e=="string"?new RegExp(HA(e),"g"):e}function KA(e){return typeof e=="function"?e:function(){return e}}const td="phrasing",nd=["autolink","link","image","label"];function GA(){return{transforms:[tR],enter:{literalAutolink:YA,literalAutolinkEmail:sd,literalAutolinkHttp:sd,literalAutolinkWww:sd},exit:{literalAutolink:eR,literalAutolinkEmail:ZA,literalAutolinkHttp:QA,literalAutolinkWww:XA}}}function JA(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:td,notInConstruct:nd},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:td,notInConstruct:nd},{character:":",before:"[ps]",after:"\\/",inConstruct:td,notInConstruct:nd}]}}function YA(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function sd(e){this.config.enter.autolinkProtocol.call(this,e)}function QA(e){this.config.exit.autolinkProtocol.call(this,e)}function XA(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 ZA(e){this.config.exit.autolinkEmail.call(this,e)}function eR(e){this.exit(e)}function tR(e){qA(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,nR],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,sR]],{ignore:["link","linkReference"]})}function nR(e,n,s,a,r){let o="";if(!fx(r)||(/^w/i.test(n)&&(s=n+s,n="",o="http://"),!iR(s)))return!1;const l=aR(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 sR(e,n,s,a){return!fx(a,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function iR(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 aR(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=fp(e,"(");let o=fp(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 fx(e,n){const s=e.input.charCodeAt(e.index-1);return(e.index===0||Oa(s)||mc(s))&&(!n||s!==47)}gx.peek=pR;function rR(){this.buffer()}function oR(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function lR(){this.buffer()}function cR(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function dR(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=vi(this.sliceSerialize(e)).toLowerCase(),s.label=n}function uR(e){this.exit(e)}function mR(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=vi(this.sliceSerialize(e)).toLowerCase(),s.label=n}function hR(e){this.exit(e)}function pR(){return"["}function gx(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 fR(){return{enter:{gfmFootnoteCallString:rR,gfmFootnoteCall:oR,gfmFootnoteDefinitionLabelString:lR,gfmFootnoteDefinition:cR},exit:{gfmFootnoteCallString:dR,gfmFootnoteCall:uR,gfmFootnoteDefinitionLabelString:mR,gfmFootnoteDefinition:hR}}}function gR(e){let n=!1;return e&&e.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:gx},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?bx:bR))),u(),d}}function bR(e,n,s){return n===0?e:bx(e,n,s)}function bx(e,n,s){return(s?"":" ")+e}const xR=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];xx.peek=jR;function vR(){return{canContainEols:["delete"],enter:{strikethrough:wR},exit:{strikethrough:kR}}}function yR(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:xR}],handlers:{delete:xx}}}function wR(e){this.enter({type:"delete",children:[]},e)}function kR(e){this.exit(e)}function xx(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 jR(){return"~"}function NR(e){return e.length}function SR(e,n){const s=n||{},a=(s.align||[]).concat(),r=s.stringLength||NR,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 v=CR(e[m][b]);if(s.alignDelimiters!==!1){const N=r(v);w[b]=N,(d[b]===void 0||N>d[b])&&(d[b]=N)}x.push(v)}l[m]=x,c[m]=w}let h=-1;if(typeof a=="object"&&"length"in a)for(;++h<u;)o[h]=gp(a[h]);else{const x=gp(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 v=s.alignDelimiters===!1?1:Math.max(1,d[h]-w.length-b.length);const N=w+"-".repeat(v)+b;s.alignDelimiters!==!1&&(v=w.length+v+b.length,v>d[h]&&(d[h]=v),p[h]=v),f[h]=N}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 v=x[h]||"";let N="",k="";if(s.alignDelimiters!==!1){const E=d[h]-(w[h]||0),y=o[h];y===114?N=" ".repeat(E):y===99?E%2?(N=" ".repeat(E/2+.5),k=" ".repeat(E/2-.5)):(N=" ".repeat(E/2),k=N):k=" ".repeat(E)}s.delimiterStart!==!1&&!h&&b.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&v==="")&&(s.delimiterStart!==!1||h)&&b.push(" "),s.alignDelimiters!==!1&&b.push(N),b.push(v),s.alignDelimiters!==!1&&b.push(k),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 CR(e){return e==null?"":String(e)}function gp(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 ER(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()),_R);return r(),l}function _R(e,n,s){return">"+(s?"":" ")+e}function MR(e,n){return bp(e,n.inConstruct,!0)&&!bp(e,n.notInConstruct,!1)}function bp(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 xp(e,n,s,a){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
667
- `&&MR(s.stack,s.unsafe[r]))return/[ \t]/.test(a.before)?"":" ";return`\\
668
- `}function AR(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 RR(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 PR(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 IR(e,n,s,a){const r=PR(s),o=e.value||"",l=r==="`"?"GraveAccent":"Tilde";if(RR(e,s)){const h=s.enter("codeIndented"),f=s.indentLines(o,TR);return h(),f}const c=s.createTracker(a),d=r.repeat(Math.max(AR(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 TR(e,n,s){return(s?"":" ")+e}function em(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 $R(e,n,s,a){const r=em(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 DR(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 ko(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Hl(e,n,s){const a=yr(e),r=yr(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}}vx.peek=LR;function vx(e,n,s,a){const r=DR(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=Hl(a.before.charCodeAt(a.before.length-1),u,r);m.inside&&(d=ko(u)+d.slice(1));const h=d.charCodeAt(d.length-1),f=Hl(a.after.charCodeAt(0),h,r);f.inside&&(d=d.slice(0,-1)+ko(h));const p=l.move(r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+d+p}function LR(e,n,s){return s.options.emphasis||"*"}function OR(e,n){let s=!1;return Xu(e,function(a){if("value"in a&&/\r?\n|\r/.test(a.value)||a.type==="break")return s=!0,ou}),!!((!e.depth||e.depth<3)&&Vu(e)&&(n.options.setext||s))}function zR(e,n,s,a){const r=Math.max(Math.min(6,e.depth||1),1),o=s.createTracker(a);if(OR(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=ko(u.charCodeAt(0))+u.slice(1)),u=u?l+" "+u:l,s.options.closeAtx&&(u+=" "+l),d(),c(),u}yx.peek=FR;function yx(e){return e.value||""}function FR(){return"<"}wx.peek=BR;function wx(e,n,s,a){const r=em(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 BR(){return"!"}kx.peek=UR;function kx(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 UR(){return"!"}jx.peek=HR;function jx(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 HR(){return"`"}function Nx(e,n){const s=Vu(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))}Sx.peek=qR;function Sx(e,n,s,a){const r=em(s),o=r==='"'?"Quote":"Apostrophe",l=s.createTracker(a);let c,d;if(Nx(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 qR(e,n,s){return Nx(e,s)?"<":"["}Cx.peek=VR;function Cx(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 VR(){return"["}function tm(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 WR(e){const n=tm(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 KR(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 Ex(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 GR(e,n,s,a){const r=s.enter("list"),o=s.bulletCurrent;let l=e.ordered?KR(s):tm(s);const c=e.ordered?l==="."?")":".":WR(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),Ex(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 JR(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 YR(e,n,s,a){const r=JR(s);let o=s.bulletCurrent||tm(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 QR(e,n,s,a){const r=s.enter("paragraph"),o=s.enter("phrasing"),l=s.containerPhrasing(e,a);return o(),r(),l}const XR=fc(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function ZR(e,n,s,a){return(e.children.some(function(l){return XR(l)})?s.containerPhrasing:s.containerFlow).call(s,e,a)}function eP(e){const n=e.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}_x.peek=tP;function _x(e,n,s,a){const r=eP(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=Hl(a.before.charCodeAt(a.before.length-1),u,r);m.inside&&(d=ko(u)+d.slice(1));const h=d.charCodeAt(d.length-1),f=Hl(a.after.charCodeAt(0),h,r);f.inside&&(d=d.slice(0,-1)+ko(h));const p=l.move(r+r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+d+p}function tP(e,n,s){return s.options.strong||"*"}function nP(e,n,s,a){return s.safe(e.value,a)}function sP(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 iP(e,n,s){const a=(Ex(s)+(s.options.ruleSpaces?" ":"")).repeat(sP(s));return s.options.ruleSpaces?a.slice(0,-1):a}const Mx={blockquote:ER,break:xp,code:IR,definition:$R,emphasis:vx,hardBreak:xp,heading:zR,html:yx,image:wx,imageReference:kx,inlineCode:jx,link:Sx,linkReference:Cx,list:GR,listItem:YR,paragraph:QR,root:ZR,strong:_x,text:nP,thematicBreak:iP};function aP(){return{enter:{table:rP,tableData:vp,tableHeader:vp,tableRow:lP},exit:{codeText:cP,table:oP,tableData:id,tableHeader:id,tableRow:id}}}function rP(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 oP(e){this.exit(e),this.data.inTable=void 0}function lP(e){this.enter({type:"tableRow",children:[]},e)}function id(e){this.exit(e)}function vp(e){this.enter({type:"tableCell",children:[]},e)}function cP(e){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,dP));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(e)}function dP(e,n){return n==="|"?n:e}function uP(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),v=u([b]);return v.slice(0,v.indexOf(`
679
- `))}function d(p,g,x,w){const b=x.enter("tableCell"),v=x.enter("phrasing"),N=x.containerPhrasing(p,{...w,before:o,after:o});return v(),b(),N}function u(p,g){return SR(p,{align:g,alignDelimiters:a,padding:s,stringLength:r})}function m(p,g,x){const w=p.children;let b=-1;const v=[],N=g.enter("table");for(;++b<w.length;)v[b]=h(w[b],g,x);return N(),v}function h(p,g,x){const w=p.children;let b=-1;const v=[],N=g.enter("tableRow");for(;++b<w.length;)v[b]=d(w[b],p,g,x);return N(),v}function f(p,g,x){let w=Mx.inlineCode(p,g,x);return x.stack.includes("tableCell")&&(w=w.replace(/\|/g,"\\$&")),w}}function mP(){return{exit:{taskListCheckValueChecked:yp,taskListCheckValueUnchecked:yp,paragraph:pP}}}function hP(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:fP}}}function yp(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function pP(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 fP(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=Mx.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 gP(){return[GA(),fR(),vR(),aP(),mP()]}function bP(e){return{extensions:[JA(),gR(e),yR(),uP(e),hP()]}}const xP={tokenize:NP,partial:!0},Ax={tokenize:SP,partial:!0},Rx={tokenize:CP,partial:!0},Px={tokenize:EP,partial:!0},vP={tokenize:_P,partial:!0},Ix={name:"wwwAutolink",tokenize:kP,previous:$x},Tx={name:"protocolAutolink",tokenize:jP,previous:Dx},Ji={name:"emailAutolink",tokenize:wP,previous:Lx},$i={};function yP(){return{text:$i}}let Ea=48;for(;Ea<123;)$i[Ea]=Ji,Ea++,Ea===58?Ea=65:Ea===91&&(Ea=97);$i[43]=Ji;$i[45]=Ji;$i[46]=Ji;$i[95]=Ji;$i[72]=[Ji,Tx];$i[104]=[Ji,Tx];$i[87]=[Ji,Ix];$i[119]=[Ji,Ix];function wP(e,n,s){const a=this;let r,o;return l;function l(h){return!uu(h)||!Lx.call(a,a.previous)||nm(a.events)?s(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(h))}function c(h){return uu(h)?(e.consume(h),c):h===64?(e.consume(h),d):s(h)}function d(h){return h===46?e.check(vP,m,u)(h):h===45||h===95||Is(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&&zs(a.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),n(h)):s(h)}}function kP(e,n,s){const a=this;return r;function r(l){return l!==87&&l!==119||!$x.call(a,a.previous)||nm(a.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(xP,e.attempt(Ax,e.attempt(Rx,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function jP(e,n,s){const a=this;let r="",o=!1;return l;function l(h){return(h===72||h===104)&&Dx.call(a,a.previous)&&!nm(a.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),e.consume(h),c):s(h)}function c(h){if(zs(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||Fl(h)||Bn(h)||Oa(h)||mc(h)?s(h):e.attempt(Ax,e.attempt(Rx,m),s)(h)}function m(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(h)}}function NP(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 SP(e,n,s){let a,r,o;return l;function l(u){return u===46||u===95?e.check(Px,d,c)(u):u===null||Bn(u)||Oa(u)||u!==45&&mc(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 CP(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(Px,n,o)(l):l===null||Bn(l)||Oa(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&a++,e.consume(l),r}}function EP(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)||Oa(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||Bn(c)||Oa(c)?n(c):a(c)}function o(c){return zs(c)?l(c):s(c)}function l(c){return c===59?(e.consume(c),a):zs(c)?(e.consume(c),l):s(c)}}function _P(e,n,s){return a;function a(o){return e.consume(o),r}function r(o){return Is(o)?s(o):n(o)}}function $x(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||Bn(e)}function Dx(e){return!zs(e)}function Lx(e){return!(e===47||uu(e))}function uu(e){return e===43||e===45||e===46||e===95||Is(e)}function nm(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 MP={tokenize:LP,partial:!0};function AP(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:TP,continuation:{tokenize:$P},exit:DP}},text:{91:{name:"gfmFootnoteCall",tokenize:IP},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:RP,resolveTo:PP}}}}function RP(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=vi(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 PP(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 IP(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(vi(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 TP(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=vi(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),jn(e,p,"gfmFootnoteDefinitionWhitespace")):s(g)}function p(g){return n(g)}}function $P(e,n,s){return e.check(Bo,n,e.attempt(MP,n,s))}function DP(e){e.exit("gfmFootnoteDefinition")}function LP(e,n,s){const a=this;return jn(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 OP(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&&Qs(f,f.length,0,hc(p,l.slice(u+1,d),c)),Qs(f,f.length,0,[["exit",h,c],["enter",l[d][1],c],["exit",l[d][1],c],["exit",m,c]]),Qs(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=yr(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=yr(g);return w._open=!b||b===2&&!!x,w._close=!x||x===2&&!!b,c(g)}}}class zP{constructor(){this.map=[]}add(n,s,a){FP(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 FP(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 BP(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 UP(){return{flow:{null:{name:"table",tokenize:HP,resolveAll:qP}}}}function HP(e,n,s){const a=this;let r=0,o=0,l;return c;function c(_){let R=a.events.length-1;for(;R>-1;){const C=a.events[R][1].type;if(C==="lineEnding"||C==="linePrefix")R--;else break}const L=R>-1?a.events[R][1].type:null,U=L==="tableHead"||L==="tableRow"?y:d;return U===y&&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(_):Qt(_)?o>1?(o=0,a.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(_),e.exit("lineEnding"),p):s(_):yn(_)?jn(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,yn(_)?jn(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):E(_)}function x(_){return yn(_)?jn(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||Qt(_)?k(_):E(_)}function b(_){return _===45?(e.enter("tableDelimiterFiller"),v(_)):E(_)}function v(_){return _===45?(e.consume(_),v):_===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(_),e.exit("tableDelimiterMarker"),N):(e.exit("tableDelimiterFiller"),N(_))}function N(_){return yn(_)?jn(e,k,"whitespace")(_):k(_)}function k(_){return _===124?g(_):_===null||Qt(_)?!l||r!==o?E(_):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(_)):E(_)}function E(_){return s(_)}function y(_){return e.enter("tableRow"),j(_)}function j(_){return _===124?(e.enter("tableCellDivider"),e.consume(_),e.exit("tableCellDivider"),j):_===null||Qt(_)?(e.exit("tableRow"),n(_)):yn(_)?jn(e,j,"whitespace")(_):(e.enter("data"),P(_))}function P(_){return _===null||_===124||Bn(_)?(e.exit("data"),j(_)):(e.consume(_),_===92?F:P)}function F(_){return _===92||_===124?(e.consume(_),P):P(_)}}function qP(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 zP;for(;++s<e.length;){const p=e[s],g=p[1];p[0]==="enter"?g.type==="tableHead"?(c=!1,d!==0&&(wp(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=el(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=el(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=el(f,n,o,r,s,h)):l[1]!==0&&(h=el(f,n,l,r,s,h)),r=0):r&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(l[3]=s)}for(d!==0&&wp(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=BP(n.events,s))}return e}function el(e,n,s,a,r,o){const l=a===1?"tableHeader":a===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},lr(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const d=lr(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=lr(n.events,s[2]),m=lr(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({},lr(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function wp(e,n,s,a,r){const o=[],l=lr(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 lr(e,n){const s=e[n],a=s[0]==="enter"?"start":"end";return s[1][a]}const VP={name:"tasklistCheck",tokenize:KP};function WP(){return{text:{91:VP}}}function KP(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 Qt(d)?n(d):yn(d)?e.check({tokenize:GP},n,s)(d):s(d)}}function GP(e,n,s){return jn(e,a,"whitespace");function a(r){return r===null?s(r):n(r)}}function JP(e){return Gb([yP(),AP(),OP(e),UP(),WP()])}const YP={};function ki(e){const n=this,s=e||YP,a=n.data(),r=a.micromarkExtensions||(a.micromarkExtensions=[]),o=a.fromMarkdownExtensions||(a.fromMarkdownExtensions=[]),l=a.toMarkdownExtensions||(a.toMarkdownExtensions=[]);r.push(JP(s)),o.push(gP()),l.push(bP(s))}const QP=45e3,XP=3e3,ZP=2e3,eI=1500,kp="fusion:sse-client-id";let nr=null;const aa=new Map;function jp(){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 Ox(){if(!(typeof window>"u")){if(nr)return nr;try{const e=window.sessionStorage.getItem(kp);if(e)return nr=e,e;const n=jp();return window.sessionStorage.setItem(kp,n),nr=n,n}catch{return nr=jp(),nr}}}function zx(e){if(!(typeof window>"u"))try{return{parsed:new URL(e,window.location.origin),preserveRelativePath:e.startsWith("/")}}catch{return}}function Fx(e){return e.origin===window.location.origin&&e.pathname==="/api/events"}function tI(e){const n=Ox();if(!n)return e;const s=zx(e);return!s||!Fx(s.parsed)?e:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function sm(e,n){const s=Ox();if(!s)return;const a=zx(e);if(!a||!Fx(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),Ii(`${r.pathname}${r.search}${r.hash}`)}function nI(e){if(typeof window>"u")return;const n=sm(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 bc(e){e.keepaliveTimer&&(clearInterval(e.keepaliveTimer),e.keepaliveTimer=null)}function Np(e){if(typeof window>"u"||typeof window.fetch!="function")return;const n=sm(e.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,a=s?window.setTimeout(()=>s.abort(),eI):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{a!==null&&window.clearTimeout(a)})}function sI(e){bc(e),sm(e.url,"keepalive")&&(Np(e),e.keepaliveTimer=window.setInterval(()=>{Np(e)},ZP))}if(typeof window<"u"){const e=()=>{for(const s of Array.from(aa.values()))if(!s.closed){if(bc(s),nI(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(aa.values()))a.subscribers.size!==0&&(a.closed=!1,im(a))};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("pageshow",n)}function io(e){e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),e.heartbeatTimer=setTimeout(()=>{Bx(e)},QP)}function Bx(e){if(e.heartbeatTimer&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=null),e.es&&(e.es.close(),e.es=null),bc(e),e.nativeListeners.clear(),e.closed||e.subscribers.size===0||e.reconnectTimer)return;const n=aa.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=aa.get(e.url);s&&s===e&&e.subscribers.size>0&&im(e)},XP)}}function im(e){if(e.es||e.closed)return;e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);const n=new EventSource(Ii(tI(e.url)));e.es=n,sI(e),n.addEventListener("open",()=>{io(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);Bx(e)}),n.addEventListener("message",()=>io(e)),n.addEventListener("heartbeat",()=>io(e)),Ux(e),io(e)}function Ux(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=>{io(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 iI(e){e.closed=!0,e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),bc(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.es&&e.es.close(),e.es=null,e.nativeListeners.clear(),aa.delete(e.url)}function li(e,n={}){let s=aa.get(e);s||(s={url:e,es:null,subscribers:new Set,nativeListeners:new Map,heartbeatTimer:null,keepaliveTimer:null,reconnectTimer:null,hasOpenedOnce:!1,closed:!1},aa.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;im(s),Ux(s),r&&queueMicrotask(()=>{s.subscribers.has(a)&&a.onOpen?.()});let o=!0;return()=>{if(!o)return;o=!1;const l=aa.get(e);l&&(l.subscribers.delete(a),l.subscribers.size===0&&iI(l))}}const Sp=100;function Hx(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),v=i.useRef(n),N=i.useRef(0);(w.current!==e||b.current!==s||v.current!==n)&&(w.current=e,b.current=s,v.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 j=x.current,P=++N.current;g.current=!1;const F=e,_=s;async function R(){if(!F)return;l(!0),f(!1);try{const U=await Cm(F,_,{limit:Sp});if(g.current||x.current!==j||N.current!==P)return;r(U.entries),d(U.hasMore),m(U.total)}catch{if(g.current||x.current!==j||N.current!==P)return;r([]),d(!1),m(null)}finally{!g.current&&x.current===j&&N.current===P&&l(!1)}const L=_?`?projectId=${encodeURIComponent(_)}`:"";p.current=li(`/api/tasks/${F}/logs/stream${L}`,{events:{"agent:log":U=>{if(!(g.current||x.current!==j))try{const C=JSON.parse(U.data);r($=>[...$,C]),m($=>$!==null?$+1:null)}catch{}}}})}return R(),()=>{g.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const E=i.useCallback(async()=>{if(!e||h)return;const j=x.current,P=a.length,F=e;f(!0);try{const _=await Cm(F,s,{limit:Sp,offset:P});if(g.current||x.current!==j)return;r(R=>[..._.entries,...R]),d(_.hasMore),m(_.total)}catch{}finally{f(!1)}},[e,s,a.length,h]),y=i.useCallback(()=>r([]),[]);return{entries:a,loading:o,clear:y,loadMore:E,hasMore:c,total:u,loadingMore:h}}const Cp="fn-agent-log-markdown",Ep="fn-agent-log-tool-output";function _p(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 Mp(e,n){if(!(typeof window>"u"))try{window.localStorage.setItem(e,n?"true":"false")}catch{}}function aI(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 Ap={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})},qx=50,rI={triage:"Plan"};function Rp(e){return e.scrollHeight-(e.scrollTop+e.clientHeight)<=qx}function mu(e){return[e.taskId,e.timestamp,e.agent??"",e.type,e.text,e.detail??""].join("|")}function oI(e){const n=new Map;return e.map(s=>{const a=mu(s),r=n.get(a)??0;return n.set(a,r+1),`${a}|${r}`})}function Vx(e){return e==="tool"||e==="tool_result"||e==="tool_error"}function ad({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(un,{size:14}):t.jsx(zn,{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 lI(e,n){return e.agent?Vx(e.type)?!0:!n||n.agent!==e.agent||n.type!==e.type:!1}function cI(e,n){const s=[];for(let a=0;a<e.length;a+=1){const{entry:r,hiddenToolBoundaryId:o}=e[a],l=n[a]??`${mu(r)}|fallback`,c=a>0?e[a-1]:void 0,d=c?.entry,u=lI(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]??`${mu(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 dI({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(()=>_p(Cp,!0)),[w,b]=i.useState(()=>_p(Ep,!0)),[v,N]=i.useState(!1),[k,E]=i.useState(!1),[y,j]=i.useState(!0);i.useEffect(()=>{Mp(Cp,g)},[g]),i.useEffect(()=>{Mp(Ep,w)},[w]);const P=i.useMemo(()=>{if(w)return e.map(I=>({entry:I,hiddenToolBoundaryId:0}));const q=[];let A=0;for(const I of e){if(Vx(I.type)){A+=1;continue}q.push({entry:I,hiddenToolBoundaryId:A})}return q},[e,w]),F=i.useMemo(()=>P.map(q=>q.entry),[P]),_=i.useMemo(()=>oI(F),[F]),R=i.useMemo(()=>cI(P,_),[P,_]);i.useLayoutEffect(()=>{const q=u.current;if(!q)return;const A=e.length,I=m.current,D=h.current||q.scrollHeight,S=_[0]??null,G=_[_.length-1]??null,he=f.current!==S,Se=p.current!==G;if(A>I)if(I===0)q.scrollTop=q.scrollHeight;else{const Ue=D-(q.scrollTop+q.clientHeight)<=qx,ce=Se&&!he,Ae=he&&!Se;if(ce&&Ue&&(q.scrollTop=q.scrollHeight),Ae){const X=q.scrollHeight-D;X>0&&(q.scrollTop+=X)}}m.current=A,h.current=q.scrollHeight,f.current=S,p.current=G,j(Rp(q))},[e,_]);const L=i.useCallback(()=>{const q=u.current;q&&j(Rp(q))},[]),U=i.useCallback(()=>{const q=u.current;q&&(q.scrollTop=q.scrollHeight,j(!0))},[]),C=i.useCallback(q=>{q.key==="Escape"&&v&&N(!1)},[v]);i.useEffect(()=>{if(v)return document.addEventListener("keydown",C),()=>{document.removeEventListener("keydown",C)}},[v,C]);const $=s?.provider&&s?.modelId,V=a?.provider&&a?.modelId,Y=r?.provider&&r?.modelId,ne=i.useMemo(()=>{const q=[];return $&&q.push({role:"Executor",provider:s.provider,modelId:s.modelId}),V&&q.push({role:"Reviewer",provider:a.provider,modelId:a.modelId}),Y&&q.push({role:"Planning",provider:r.provider,modelId:r.modelId}),q},[$,s,V,a,Y,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${v?" 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(q=>t.jsx(Tn,{provider:q.provider,size:"sm"},`${q.role}-${q.provider}-${q.modelId??"default"}`)),t.jsx("button",{className:"agent-log-model-expand-btn",onClick:()=>E(q=>!q),"aria-label":k?"Collapse model details":"Expand model details","aria-expanded":k,"aria-controls":"agent-log-model-details","data-testid":"agent-log-model-expand",children:k?t.jsx(un,{size:14}):t.jsx(zn,{size:14})})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>x(q=>!q),"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(q=>!q),"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:()=>N(q=>!q),"aria-label":v?"Exit full screen":"Expand agent log to full screen","data-testid":"agent-log-fullscreen-toggle",title:v?"Exit full screen":"Expand agent log to full screen",children:v?t.jsx(Ao,{size:14}):t.jsx(rc,{size:14})})]}),k&&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:"}),$?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Tn,{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:"}),V?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Tn,{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:"}),Y?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Tn,{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:L,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(Nt,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})}),R.map(q=>{const A=q.kind==="single"?q.entry:q.entries[0],I=q.showBadge?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:aI(A.timestamp)}):null,D=q.showBadge?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",rI[A.agent]??A.agent,"]"]}),I]}):null;if(q.kind==="single"){const{entry:G}=q;if(G.type==="tool")return t.jsxs("div",{className:"agent-log-tool",children:[D,t.jsxs("div",{className:"agent-log-tool-title",children:["⚡ ",G.text]}),G.detail?t.jsx(ad,{detail:G.detail,type:"tool"}):null]},q.key);if(G.type==="tool_result")return t.jsxs("div",{className:"agent-log-tool-result",children:[D,t.jsxs("div",{className:"agent-log-tool-title",children:["✓ ",G.text]}),G.detail?t.jsx(ad,{detail:G.detail,type:"tool_result"}):null]},q.key);if(G.type==="tool_error")return t.jsxs("div",{className:"agent-log-tool-error",children:[D,t.jsxs("div",{className:"agent-log-tool-title",children:["✗ ",G.text]}),G.detail?t.jsx(ad,{detail:G.detail,type:"tool_error"}):null]},q.key)}const S=q.kind==="single"?A.text:q.entries.map(G=>G.text).join("");return q.kind==="thinking"?t.jsxs("div",{className:"agent-log-thinking",children:[D,g?t.jsx("div",{className:"markdown-body",children:t.jsx(wi,{remarkPlugins:[ki],components:Ap,children:S})}):t.jsx("pre",{className:"agent-log-plain-block",children:S})]},q.key):t.jsxs("div",{className:"agent-log-text",children:[D,g?t.jsx("div",{className:"markdown-body",children:t.jsx(wi,{remarkPlugins:[ki],components:Ap,children:S})}):t.jsx("pre",{className:"agent-log-plain-block",children:S})]},q.key)}),!y&&t.jsxs("button",{type:"button",className:"agent-log-return-to-live",onClick:U,"data-testid":"agent-log-return-to-live",children:[t.jsx(un,{size:12}),t.jsx("span",{children:"Live"})]})]})]})}function wr(e){return e??void 0}function tl(e){return{provider:wr(e.modelProvider),modelId:wr(e.modelId)}}function nl(e){return{provider:wr(e.validatorModelProvider),modelId:wr(e.validatorModelId)}}function sl(e){return{provider:wr(e.planningModelProvider),modelId:wr(e.planningModelId)}}function uI(e,n){return pb(e,n)}function mI(e,n){return fb(e,n)}function hI(e,n){return gb(e,n)}function rd(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 od(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function ld(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function pI(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 fI({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(()=>tl(e)),[w,b]=i.useState(()=>tl(e)),[v,N]=i.useState(()=>nl(e)),[k,E]=i.useState(()=>nl(e)),[y,j]=i.useState(()=>sl(e)),[P,F]=i.useState(()=>sl(e)),[_,R]=i.useState(()=>e.thinkingLevel??null),[L,U]=i.useState(()=>e.thinkingLevel??null),[C,$]=i.useState(null),V=i.useRef(e.id);i.useEffect(()=>{h(!0),p(null),Fs().then(K=>{o(K.models),c(K.favoriteProviders),u(K.favoriteModels)}).catch(K=>{p(K.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const Y=i.useCallback(async K=>{const O=l,ve=O.includes(K)?O.filter(B=>B!==K):[K,...O];c(ve);try{await Pn({favoriteProviders:ve,favoriteModels:d})}catch{c(O),n("Failed to update favorites","error")}},[l,d,n]),ne=i.useCallback(async K=>{const O=d,ve=O.includes(K)?O.filter(B=>B!==K):[K,...O];u(ve);try{await Pn({favoriteProviders:l,favoriteModels:ve})}catch{u(O),n("Failed to update model favorites","error")}},[d,l,n]);i.useEffect(()=>{V.current=e.id;const K=tl(e),O=nl(e),pe=sl(e);x(K),b(K),N(O),E(O),j(pe),F(pe);const ve=e.thinkingLevel??null;R(ve),U(ve),$(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const q=i.useMemo(()=>od(g),[g]),A=i.useMemo(()=>od(v),[v]),I=i.useMemo(()=>od(y),[y]),D=i.useMemo(()=>uI(e,a),[e,a]),S=i.useMemo(()=>mI(e,a),[e,a]),G=i.useMemo(()=>hI(e,a),[e,a]),he=C!==null,Se=i.useCallback(async(K,O)=>{const pe=e.id,ve=w,B=k,we=P;$(K);try{const ze=s?K==="executor"?{modelProvider:O.provider??null,modelId:O.modelId??null}:K==="validator"?{validatorModelProvider:O.provider??null,validatorModelId:O.modelId??null}:{planningModelProvider:O.provider??null,planningModelId:O.modelId??null}:{modelProvider:(K==="executor"?O:w).provider??null,modelId:(K==="executor"?O:w).modelId??null,validatorModelProvider:(K==="validator"?O:k).provider??null,validatorModelId:(K==="validator"?O:k).modelId??null,planningModelProvider:(K==="planning"?O:P).provider??null,planningModelId:(K==="planning"?O:P).modelId??null},re=await qs(pe,ze);if(V.current!==pe)return;const He=tl(re),Pe=nl(re),tt=sl(re);b(He),x(He),E(Pe),N(Pe),F(tt),j(tt),s?.(re),n(pI(K,{executor:He,validator:Pe,planning:tt}[K]),"success")}catch(ze){if(V.current!==pe)return;K==="executor"?x(ve):K==="validator"?N(B):j(we),n(Ce(ze)||"Failed to save model settings","error")}finally{V.current===pe&&$(null)}},[e.id,w,k,P,n,s]),Ue=i.useCallback(K=>{const O=rd(K);x(O),!ld(O,w)&&Se("executor",O)},[w,Se]),ce=i.useCallback(K=>{const O=rd(K);N(O),!ld(O,k)&&Se("validator",O)},[k,Se]),Ae=i.useCallback(K=>{const O=rd(K);j(O),!ld(O,P)&&Se("planning",O)},[P,Se]),X=i.useCallback(async K=>{const O=e.id,pe=L,ve=K===""?null:K;R(ve),$("thinking");try{const B=await qs(O,{thinkingLevel:ve});if(V.current!==O)return;const we=B.thinkingLevel??null;U(we),R(we),s?.(B);const ze=a?.defaultThinkingLevel??"off";n(we===null?`Thinking level set to default (${ze})`:`Thinking level set to ${we}`,"success")}catch(B){if(V.current!==O)return;R(pe),n(Ce(B)||"Failed to save thinking level","error")}finally{V.current===O&&$(null)}},[e.id,L,a,n,s]),Z=!w.provider&&!w.modelId,ee=!k.provider&&!k.modelId,le=!P.provider&&!P.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),Fs().then(K=>{o(K.models),c(K.favoriteProviders),u(K.favoriteModels)}).catch(K=>p(K.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:Z?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",D.provider&&D.modelId?` (${D.provider}/${D.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[w.provider&&t.jsx(Tn,{provider:w.provider,size:"sm"}),w.provider,"/",w.modelId]})}),t.jsx(Ns,{id:"executorModel",label:"Executor Model",value:q,onChange:Ue,models:r,disabled:he,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:Y,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",S.provider&&S.modelId?` (${S.provider}/${S.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[k.provider&&t.jsx(Tn,{provider:k.provider,size:"sm"}),k.provider,"/",k.modelId]})}),t.jsx(Ns,{id:"validatorModel",label:"Reviewer Model",value:A,onChange:ce,models:r,disabled:he,placeholder:"Select reviewer model…",favoriteProviders:l,onToggleFavorite:Y,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:le?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",G.provider&&G.modelId?` (${G.provider}/${G.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[P.provider&&t.jsx(Tn,{provider:P.provider,size:"sm"}),P.provider,"/",P.modelId]})}),t.jsx(Ns,{id:"planningModel",label:"Planning Model",value:I,onChange:Ae,models:r,disabled:he,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:Y,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:L===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:L})}),t.jsxs("select",{id:"thinkingLevel",value:_??"",onChange:K=>X(K.target.value),disabled:he,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:Z&&ee&&le&&L===null?"Using project or global default models.":"Model settings are up to date."})]})]})}const gI={open:t.jsx(ec,{size:16}),closed:t.jsx(_o,{size:16}),merged:t.jsx(Og,{size:16})};function bI({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),[v,N]=i.useState(!1),[k,E]=i.useState(null),y=i.useCallback(async()=>{if(f.trim()){b(!0);try{const _=await bN(e,{title:f.trim(),body:g.trim()||void 0},n);c(_),h(!1),p(""),x(""),u(`Created PR #${_.number}`,"success")}catch(_){u(Ce(_)||"Failed to create PR","error")}finally{b(!1)}}},[e,f,g,n,c,u]),j=i.useCallback(async()=>{if(s){N(!0);try{const _=await xN(e,n);E(_),d(_.prInfo),u("PR status refreshed","success")}catch(_){u(Ce(_)||"Failed to refresh PR","error")}finally{N(!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(Js,{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(Js,{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(Js,{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:y,disabled:!f.trim()||w,children:w?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Js,{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(Cn,{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 P=gI[s.status]??t.jsx(ec,{size:16}),F=k?.blockingReasons??[];return t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Js,{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:P}),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:j,disabled:v,title:"Refresh PR status",children:t.jsx(fs,{size:14,style:{verticalAlign:"middle",opacity:v?.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(qi,{size:14}),s.commentCount]}),t.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[t.jsx($g,{size:14}),"View on GitHub"]})]})]})]})}const Pp=2e3;function xI(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function vI(e){return e==="agent"||e==="system"}function yI({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((j,P)=>new Date(P.createdAt).getTime()-new Date(j.createdAt).getTime()),[e.comments]),w=o.length>Pp;async function b(){const j=o.trim();if(j){f(!0);try{const P=await Lj(e.id,j,r);l(""),n?.(P),s("Comment added","success")}catch(P){s(Ce(P)||"Failed to add comment","error")}finally{f(!1)}}}async function v(j){const P=u.trim();if(P){f(!0);try{const F=await Pj(e.id,j,P,r);d(null),m(""),n?.(F),s("Comment updated","success")}catch(F){s(Ce(F)||"Failed to update comment","error")}finally{f(!1)}}}async function N(j){g(j);try{const P=await Ij(e.id,j,r);n?.(P),s("Comment deleted","success")}catch(P){s(Ce(P)||"Failed to delete comment","error")}finally{g(null)}}function k(j){j.key==="Enter"&&(j.ctrlKey||j.metaKey)&&(j.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(j=>{const P=j.author===a,F=c===j.id,_=vI(j.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:j.author}),t.jsx("span",{className:"detail-log-timestamp",children:xI(j)})]}),P&&!F?t.jsxs("div",{className:"comments-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{d(j.id),m(j.text)},children:"Edit"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void N(j.id),disabled:p===j.id,children:p===j.id?"Deleting…":"Delete"})]}):null]}),F?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:u,onChange:R=>m(R.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 v(j.id),disabled:h||!u.trim(),children:"Save"})]})]}):t.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:j.text})]},j.id)})}),t.jsxs("div",{className:"comments-compose-form",children:[t.jsx("textarea",{value:o,onChange:j=>l(j.target.value),onKeyDown:k,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," / ",Pp]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void b(),disabled:h||!o.trim()||w,children:h?"Posting…":"Add Comment"})]})]})]})}const Ip="Failed to load review data.",wI="No reviewer feedback yet — this task has not produced reviewer-agent feedback in direct mode.";function Vr(e){return e?new Date(e).toLocaleString():"Never"}function kI(e){return e==="manual"?"Manual":e==="auto"?"Background":"Initial load"}function jI(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 NI({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),v=r.length>0&&!d,N=w?.source==="pull-request",k=i.useMemo(()=>w?jI(w):[],[w]);i.useEffect(()=>{let L=!1;return h(!0),p(null),OS(e.id,n).then(U=>{L||(b(U.reviewState),x(U.emptyMessage??null))}).catch(()=>{L||p(Ip)}).finally(()=>{L||h(!1)}),()=>{L=!0}},[e.id,n]);const E=i.useMemo(()=>w?w.source==="pull-request"?`${w.summary?.reviewDecision??"REVIEW_REQUIRED"} · ${k.length} review item(s)`:`${w.summary?.summary??"reviewer-agent"} · ${k.length} review item(s)`:"No review feedback captured yet.",[w,k.length]),y=w?w.source==="pull-request"?w.summary?.reviewDecision:w.summary?.verdict:void 0,j=l?"refreshing":w?.refreshStatus??"ready",P=j==="error"?"status-dot status-dot--error":j==="refreshing"?"status-dot status-dot--pending":"status-dot status-dot--online",F=L=>o(U=>U.includes(L)?U.filter(C=>C!==L):[...U,L]),_=async()=>{try{p(null),c(!0);const L=await zS(e.id,n);if(b(L.reviewState),s?.({...e,reviewState:L.reviewState,prInfo:L.prInfo??e.prInfo}),L.reviewState.refreshStatus==="error"){const U=L.reviewState.refreshError??"Failed to refresh review data.";p(U),a(U,"error");return}a("Review refreshed","success")}catch(L){const U=L instanceof Error?L.message:Ip;p(U),a(U,"error")}finally{c(!1)}},R=async()=>{try{if(!w)return;p(null),u(!0);const L=k.filter(C=>r.includes(C.id)).map(C=>{if(!C.item)return{id:C.id,source:w.source==="pull-request"?"pr-review":"reviewer-agent",threadId:C.addressing?.snapshot?.threadId,filePath:C.addressing?.snapshot?.filePath,lineNumber:C.addressing?.snapshot?.lineNumber,author:C.addressing?.snapshot?.authorLogin,summary:C.summary,body:C.body,url:C.addressing?.snapshot?.url};const $=C.item;return{id:C.item.id,source:w.source==="pull-request"?"pr-review":"reviewer-agent",threadId:typeof $.threadId=="string"?$.threadId:void 0,filePath:C.item.path,lineNumber:typeof $.line=="number"?$.line:void 0,author:C.item.author?.login,summary:C.item.summary??C.item.body.slice(0,120),body:C.item.body,url:typeof $.url=="string"?$.url:void 0}}),U=await FS(e.id,L,n);b(U.reviewState),s?.({...U.task,reviewState:U.reviewState}),o([]),a("Same-task AI revision started from selected review feedback","success")}catch(L){const U=L instanceof Error?L.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:E}),y?t.jsx("span",{className:`task-review-tab__decision task-review-tab__decision--${y}`,children:y}):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:!v,onClick:R,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:P,"aria-hidden":"true"}),t.jsxs("span",{children:[j==="error"?"Refresh failed":j==="refreshing"?"Refreshing":"Up to date"," · Last refreshed: ",Vr(w?.lastRefreshedAt)," · ",kI(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&&!N&&k.length===0?t.jsx("div",{className:"task-review-tab__empty",children:g??wI}):null,!m&&!f&&k.length>0?t.jsx("ul",{className:"task-review-tab__list",children:k.map(L=>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(L.id),onChange:()=>F(L.id)}),t.jsxs("span",{className:"task-review-tab__item-summary",children:[L.path?`${L.path}: `:"",L.summary]}),t.jsx("span",{className:`task-review-tab__status task-review-tab__status--${L.status}`,children:L.status})]}),t.jsx("div",{className:"task-review-tab__meta",children:Vr(L.createdAt)}),L.addressing?t.jsxs("div",{className:"task-review-tab__meta",children:["Selected: ",Vr(L.addressing.selectedAt),L.addressing.startedAt?` · Started: ${Vr(L.addressing.startedAt)}`:"",L.addressing.completedAt?` · Completed: ${Vr(L.addressing.completedAt)}`:"",L.addressing.error?` · Error: ${L.addressing.error}`:""]}):null,t.jsx("pre",{className:"task-review-tab__body",children:L.body})]})},L.id))}):null,N&&!m&&!f&&k.length===0?t.jsx("div",{className:"task-review-tab__empty",children:"No review items yet."}):null]})}function SI(e){return e?e.slice(0,7):"Unknown"}function CI({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:SI(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 Wx(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(Ml.Fragment,{children:`${s}
683
- `},a)})}function EI(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function _I({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);Ti(f,e,"fusion:changes-diff-modal-size");const p=Gi(l);i.useEffect(()=>{s.length>0&&d===null&&u(0)},[s,d]);const g=i.useCallback(()=>{u(v=>v!==null&&v>0?v-1:v)},[]),x=i.useCallback(()=>{u(v=>v!==null&&v<s.length-1?v+1:v)},[]);if(i.useEffect(()=>{if(!e)return;const v=N=>{if(N.key==="Escape"){l();return}N.key==="ArrowUp"&&(N.metaKey||N.ctrlKey)&&(N.preventDefault(),g()),N.key==="ArrowDown"&&(N.metaKey||N.ctrlKey)&&(N.preventDefault(),x())};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[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(bi,{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(Zl,{})}),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(zn,{})})]}),t.jsx("button",{className:`btn btn-sm ${m?"btn-primary":""}`,onClick:()=>h(v=>!v),title:m?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(Rl,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx(fs,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(an,{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(Mo,{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((v,N)=>t.jsxs("button",{className:`changes-diff-file-item ${d===N?"selected":""}`,onClick:()=>u(N),title:v.path,children:[t.jsx("span",{className:`changes-file-status changes-file-status--${v.status}`,children:EI(v.status)}),t.jsx("span",{className:"changes-diff-file-path",title:v.path,children:t.jsx("bdo",{dir:"ltr",children:v.path})}),t.jsxs("span",{className:"changes-diff-file-stat",children:["+",v.additions," -",v.deletions]})]},v.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:Wx(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(bi,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function Kx(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function cd(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(Mo,{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(bi,{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:Kx("unknown")}),t.jsx("span",{className:"changes-file-path",title:a,children:t.jsx("bdo",{dir:"ltr",children:a})})]})},a))})]})}function MI({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(new Set),[w,b]=i.useState(null),[v,N]=i.useState(!0),[k,E]=i.useState(!1),y=a==="done",j=y&&!!r?.commitSha,P=a==="in-progress"||a==="in-review"||j,F=i.useCallback(async()=>{if(!P){h(!1);return}try{h(!0),p(null);const C=await nb(e,void 0,s),$=C.files.map(V=>({path:V.path,status:V.status,additions:V.additions,deletions:V.deletions,patch:V.patch}));c($),u(C.stats),$.length>0&&(x(new Set([$[0].path])),b(0))}catch(C){p(Ce(C)||"Failed to load diff")}finally{h(!1)}},[e,s,P]);i.useEffect(()=>{F()},[F]);const _=C=>{x($=>{const V=new Set($);if(V.has(C))V.delete(C);else{V.add(C);const Y=l.findIndex(ne=>ne.path===C);Y!==-1&&b(Y)}return V})},R=C=>{if(C<0||C>=l.length)return;const $=l[C].path;x(new Set([$])),b(C)},L=w!==null&&w>0,U=w!==null&&w<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(Ts,{size:16}),t.jsxs("span",{children:["Error loading changes: ",f]})]})});if(!y&&!n)return o&&o.length>0?cd(o,!1):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(bi,{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(y&&!j){if(o&&o.length>0)return cd(o,!0,r);const C=r?.filesChanged,$=r?.insertions,V=r?.deletions,Y=C!=null||$!=null||V!=null;return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(bi,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:Y?`Merge summary: ${C??0} file${(C??0)===1?"":"s"} changed, +${$??0} additions, -${V??0} deletions.`:"No merge commit was recorded for this task."})]})})}return l.length===0?o&&o.length>0?cd(o,y,r):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(bi,{size:24}),t.jsx("p",{children:"No files modified."}),t.jsx("span",{className:"task-changes-state-hint",children:y?"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:[y&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Mo,{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(bi,{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:()=>L&&R(w-1),disabled:!L,title:"Previous file","aria-label":"Previous file",children:t.jsx(Zl,{})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:w!==null?`${w+1}/${l.length}`:`—/${l.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>U&&R(w+1),disabled:!U,title:"Next file","aria-label":"Next file",children:t.jsx(zn,{})})]}),t.jsx("button",{className:`btn btn-sm ${v?"btn-primary":""}`,onClick:()=>N(C=>!C),title:v?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(Rl,{size:14})})]}),t.jsxs("div",{className:"changes-header-actions-secondary",children:[t.jsx("button",{className:"btn btn-sm",onClick:F,disabled:m,children:"Refresh"}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>E(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:t.jsx(rc,{})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map(C=>{const $=g.has(C.path);return t.jsxs("div",{className:`changes-file-item ${$?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>_(C.path),children:[t.jsx("span",{className:"changes-file-toggle",children:$?t.jsx(un,{size:14}):t.jsx(zn,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${C.status}`,title:C.status,children:Kx(C.status)}),t.jsx("span",{className:"changes-file-path",title:C.path,children:t.jsx("bdo",{dir:"ltr",children:C.path})}),t.jsxs("span",{className:"changes-file-stat",title:`+${C.additions} -${C.deletions}`,children:["+",C.additions," -",C.deletions]})]}),$&&C.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:Wx(C.patch)})})})]},C.path)})}),t.jsx(_I,{isOpen:k,taskId:e,files:l,stats:d,mergeDetails:r,column:a,onClose:()=>E(!1),onRefresh:F})]})}function Tp(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function AI(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function M5(e,n){const s=AI(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 $p(e){const n=e?.trim()??"";return dc.test(n)?n:""}function Gx(e,n){const s=$p(e?.githubTrackingDefaultRepo);return s||$p(n?.githubTrackingDefaultRepo)}function RI(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}const Dp=["image/png","image/jpeg","image/gif","image/webp"];function PI(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 Jx({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:v,onExecutorModelChange:N,validatorModel:k,onValidatorModelChange:E,planningModel:y,onPlanningModelChange:j,thinkingLevel:P,onThinkingLevelChange:F,presetMode:_,onPresetModeChange:R,selectedPresetId:L,onSelectedPresetIdChange:U,selectedWorkflowSteps:C,onWorkflowStepsChange:$,onDefaultOnApplied:V,pendingImages:Y,onImagesChange:ne,tasks:q,projectId:A,disabled:I=!1,addToast:D,isActive:S=!0,onAutoSaveDescription:G,onPlanningMode:he,onSubtaskBreakdown:Se,onClose:Ue,renderBelowPrimary:ce,renderBelowModelConfiguration:Ae,hideDependencies:X,autoExpandMoreOptionsOnSelection:Z=!0,reviewLevel:ee,onReviewLevelChange:le,executionMode:K,onExecutionModeChange:O,githubTrackingEnabled:pe,onGithubTrackingEnabledChange:ve,githubRepoOverride:B,onGithubRepoOverrideChange:we}){const ze=(X?!1:o.length>0)||Y.length>0||C.length>0||_!=="default"||(w??Ms)!==Ms||v!==""||k!==""||(y||"")!==""||(P||"")!==""||ee!==void 0||K==="fast"||(c||"")!==""||(u||"")!==""||(h||"")!==""||pe===!0||(B||"")!=="",[re,He]=i.useState(!1),[Pe,tt]=i.useState(Z?ze:!1),[qe,de]=i.useState(""),[De,Te]=i.useState([]),[ct,Ve]=i.useState([]),[me,oe]=i.useState([]),[Me,Xe]=i.useState(!1),[rt,ht]=i.useState(null),[yt,Re]=i.useState(null),[Ge,at]=i.useState([]),[ie,Ke]=i.useState("idle"),[je,Fe]=i.useState(!1),[Be,St]=i.useState(!1),[ye,kt]=i.useState(!1),It=i.useRef(null),Ie=i.useRef(null),be=i.useRef(null),ot=i.useRef(null),gt=i.useRef(null),xt=i.useRef(null),jt=i.useRef(null),Bt=i.useRef(!1),Jt=i.useRef(ze),Vt=i.useRef(n.trim()),pn=i.useRef(n.trim());i.useEffect(()=>{S&&(Xe(!0),Fs().then(se=>{Te(se.models),Ve(se.favoriteProviders),oe(se.favoriteModels)}).catch(()=>{}).finally(()=>Xe(!1)),oc(A).then(se=>ht(se)).catch(()=>ht(null)),$o(A).then(se=>at(se.filter(te=>te.enabled))).catch(()=>at([])),Ki().then(se=>Re(se)).catch(()=>Re(null)))},[S,A]);const Xt=rt?.modelPresets||[],mn=Xt.find(se=>se.id===L),Ht=Gx(rt,yt),Zt=(B||"").trim(),tn=Zt.length>0&&!dc.test(Zt),dn=(X?!1:o.length>0)||Y.length>0||C.length>0||_!=="default"||(w??Ms)!==Ms||v!==""||k!==""||(y||"")!==""||(P||"")!==""||ee!==void 0||K==="fast"||(c||"")!==""||(u||"")!==""||(h||"")!==""||pe===!0||(B||"")!=="";i.useEffect(()=>{if(e!=="create"||!S||!rt?.autoSelectModelPreset)return;const se=(rt.defaultPresetBySize,void 0);if(se){const te=Tp(se);U(se.id),R("preset"),N(te.executorValue),E(te.validatorValue)}},[S,rt,Xt,e]);const qt=i.useRef(!1),ke=i.useRef(!1);i.useEffect(()=>{if(e!=="create"||!S||qt.current||Ge.length===0)return;const se=Ge.filter(Oe=>Oe.defaultOn);if(se.length===0)return;qt.current=!0;const te=se.map(Oe=>Oe.id);$(te),V?.(te)},[e,S,Ge]),i.useEffect(()=>{S||(qt.current=!1)},[S]),i.useEffect(()=>{e!=="create"||!S||ve&&(ke.current||rt&&(ve(rt.githubTrackingEnabledByDefault??!1),ke.current=!0))},[e,S,rt,ve]),i.useEffect(()=>{S||(ke.current=!1)},[S]),i.useEffect(()=>{if(!Z){Jt.current=dn;return}dn&&!Jt.current&&tt(!0),Jt.current=dn},[dn,Z]),i.useEffect(()=>{Pe||(He(!1),de(""))},[Pe]),i.useEffect(()=>{e!=="edit"||!S||ot.current&&(ot.current.focus(),ot.current.select())},[e,S]),i.useEffect(()=>{if(!re)return;const se=te=>{Ie.current&&!Ie.current.contains(te.target)&&He(!1)};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[re]),i.useEffect(()=>{(e!=="edit"||I)&&kt(!1)},[e,I]),i.useEffect(()=>{if(e!=="edit"){Ke("idle");return}const se=n.trim();Vt.current=se,pn.current=se,Ke("idle")},[e]),i.useEffect(()=>{if(e!=="edit"||!G||!S)return;const se=n.trim(),te=Vt.current;if(se===te||se===pn.current){xt.current&&(clearTimeout(xt.current),xt.current=null),Bt.current||Ke("idle");return}return xt.current&&clearTimeout(xt.current),xt.current=setTimeout(async()=>{if(!Bt.current){Bt.current=!0,Ke("saving");try{await G(se),pn.current=se,Ke("saved"),jt.current&&clearTimeout(jt.current),jt.current=setTimeout(()=>{Ke("idle"),jt.current=null},2e3)}catch{Ke("idle")}finally{Bt.current=!1,xt.current=null}}},1500),()=>{xt.current&&(clearTimeout(xt.current),xt.current=null)}},[e,n,G,S]),i.useEffect(()=>()=>{xt.current&&clearTimeout(xt.current),jt.current&&clearTimeout(jt.current)},[]),i.useEffect(()=>{if(!je)return;const se=te=>{It.current&&!It.current.contains(te.target)&&Fe(!1)};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[je]);const $e=i.useCallback(se=>{const te=se.clipboardData?.items;if(te)for(let Oe=0;Oe<te.length;Oe++){const mt=te[Oe];if(mt.type.startsWith("image/")){const Pt=mt.getAsFile();if(Pt&&Dp.includes(Pt.type)){se.preventDefault(),ne([...Y,{file:Pt,previewUrl:URL.createObjectURL(Pt)}]);return}}}},[Y,ne]),Ye=i.useCallback(se=>{se.preventDefault();const te=se.dataTransfer.files;for(let Oe=0;Oe<te.length;Oe++){const mt=te[Oe];if(Dp.includes(mt.type)){ne([...Y,{file:mt,previewUrl:URL.createObjectURL(mt)}]);return}}},[Y,ne]),ut=i.useCallback(se=>{const te=Y[se];te&&URL.revokeObjectURL(te.previewUrl),ne(Y.filter((Oe,mt)=>mt!==se))},[Y,ne]),We=i.useCallback(se=>{l(o.includes(se)?o.filter(te=>te!==se):[...o,se])},[o,l]),$t=(se,te)=>se.length>te?se.slice(0,te)+"…":se,At=i.useCallback(se=>{s(se.target.value);const te=se.target;te.style.height="auto",te.style.height=te.scrollHeight+"px"},[s]),wt=i.useCallback(()=>{kt(se=>!se)},[]),zt=i.useCallback(se=>{!ye||se.key!=="Escape"||(se.preventDefault(),se.stopPropagation(),kt(!1))},[ye]),Lt=i.useCallback(async se=>{const te=n.trim();if(!(!te||Be)){St(!0);try{const Oe=await Qg(te,se,A);s(Oe),Fe(!1),D("Description refined with AI","success"),be.current&&(be.current.style.height="auto",be.current.style.height=be.current.scrollHeight+"px")}catch(Oe){const mt=Xg(Oe);D(mt,"error")}finally{St(!1)}}},[n,Be,D,s,A]),Ot=i.useCallback(async se=>{const te=ct,mt=te.includes(se)?te.filter(Pt=>Pt!==se):[se,...te];Ve(mt);try{await Pn({favoriteProviders:mt,favoriteModels:me})}catch{Ve(te)}},[ct,me]),nn=i.useCallback(async se=>{const te=me,mt=te.includes(se)?te.filter(Pt=>Pt!==se):[se,...te];oe(mt);try{await Pn({favoriteProviders:ct,favoriteModels:mt})}catch{oe(te)}},[me,ct]),Yt=i.useCallback(se=>{if(se<=0)return;const te=[...C];[te[se-1],te[se]]=[te[se],te[se-1]],$(te)},[C,$]),rn=i.useCallback(se=>{if(se>=C.length-1)return;const te=[...C];[te[se],te[se+1]]=[te[se+1],te[se]],$(te)},[C,$]),_e=i.useCallback(se=>{$(C.filter(te=>te!==se))},[C,$]),it=new Map;for(const se of Ge)it.set(se.id,{name:se.name,description:se.description});const bt=q.filter(se=>!o.includes(se.id)).sort((se,te)=>{const Oe=te.createdAt.localeCompare(se.createdAt);if(Oe!==0)return Oe;const mt=parseInt(se.id.slice(se.id.lastIndexOf("-")+1),10)||0;return(parseInt(te.id.slice(te.id.lastIndexOf("-")+1),10)||0)-mt}),Rt=qe?bt.filter(se=>se.id.toLowerCase().includes(qe.toLowerCase())||se.title&&se.title.toLowerCase().includes(qe.toLowerCase())||se.description&&se.description.toLowerCase().includes(qe.toLowerCase())):bt;return t.jsxs("div",{className:"task-form",onDrop:Ye,onDragOver:se=>se.preventDefault(),onPaste:$e,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:ot,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:a||"",onChange:se=>r(se.target.value),disabled:I})]}),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${ie==="idle"?"":" is-visible"}`,"aria-live":"polite",children:ie==="saving"?"Saving...":ie==="saved"?"Saved":""})]}),t.jsxs("div",{className:`description-with-refine${ye?" description--fullscreen":""}`,ref:It,onKeyDown:zt,children:[ye&&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:wt,"aria-label":"Collapse description",title:"Collapse description",children:t.jsx(Ao,{size:14})})]}),t.jsx("textarea",{ref:be,autoFocus:e==="create",id:"task-form-description",value:n,onChange:At,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:I||Be}),(()=>{const se=!!n.trim()&&!I;return t.jsxs(t.Fragment,{children:[!ye&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${se?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:wt,"aria-label":"Expand description",title:"Expand description",children:t.jsx(rc,{size:14})}),se&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${Be?"refine-button--loading":""}`,onClick:()=>Fe(te=>!te),disabled:Be,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(xs,{size:12,style:{verticalAlign:"middle"}}),Be?"Refining...":"Refine"]})]})})(),je&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:se=>se.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>Lt("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:()=>Lt("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:()=>Lt("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:()=>Lt("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"&&(he||Se)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[he&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const se=n.trim();if(!se){D("Enter a description first","error");return}Ue?.(),he(se)},disabled:I||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),Se&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const se=n.trim();if(!se){D("Enter a description first","error");return}Ue?.(),Se(se)},disabled:I||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),ce,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>tt(se=>!se),"aria-expanded":Pe,"aria-controls":"task-form-more-options",disabled:I,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),Pe?t.jsx(Ri,{size:14}):t.jsx(un,{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"}),Y.length>0&&t.jsx("div",{className:"inline-create-previews",children:Y.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:()=>ut(te),disabled:I,title:"Remove image",children:"×"})]},se.previewUrl))}),t.jsx("input",{ref:gt,type:"file",accept:"image/*",onChange:se=>{const te=se.target.files?.[0];te&&(ne([...Y,{file:te,previewUrl:URL.createObjectURL(te)}]),se.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>gt.current?.click(),disabled:I,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:I||g,children:[t.jsx("option",{value:"",children:"Use project default / local"}),(p??[]).map(se=>t.jsxs("option",{value:se.id,children:[se.name," (",RI(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(Da,{status:se.status,showLabel:!0})}):null})(),t.jsx("small",{children:x??"Task override takes priority over project default node routing."})]}),!X&&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:Ie,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>He(se=>!se),disabled:I,children:o.length>0?`${o.length} selected`:"Add dependencies"}),re&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:qe,onChange:se=>de(se.target.value),onClick:se=>se.stopPropagation()}),Rt.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Rt.map(se=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(se.id)?" selected":""}`,onClick:()=>We(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:$t(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:()=>We(se),disabled:I,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:I})]}),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:I})]})]}),(ve||we)&&t.jsxs("div",{className:"form-group","data-testid":"task-form-github-tracking",children:[t.jsx("label",{children:"GitHub Tracking"}),ve&&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=>{ke.current=!0,ve(se.target.checked)},disabled:I}),"Enable GitHub issue tracking for this task"]}),we&&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=>we(se.target.value),placeholder:Ht||"owner/repo",disabled:I}),tn?t.jsx("div",{className:"form-error",children:"Repository must be in owner/repo format."}):null]})]}),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??Ms,onChange:se=>b(se.target.value),disabled:I,children:da.map(se=>t.jsx("option",{value:se,children:se[0].toUpperCase()+se.slice(1)},se))})]}),O&&K!==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:K,onChange:se=>O(se.target.value),disabled:I,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),Me?t.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):De.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"?L:_,onChange:se=>{const te=se.target.value;if(te==="default"){R("default"),U(""),N(""),E("");return}if(te==="custom"){R("custom"),U("");return}const Oe=Xt.find(Pt=>Pt.id===te),mt=Tp(Oe);R("preset"),U(te),N(mt.executorValue),E(mt.validatorValue)},disabled:I,children:[t.jsx("option",{value:"default",children:"Use default"}),Xt.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,Xt.map(se=>t.jsx("option",{value:se.id,children:se.name},se.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),_==="preset"&&mn?t.jsxs("small",{children:["Using preset: ",mn.name]}):null,_==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>R("custom"),disabled:I,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(Ns,{id:"executor-model",label:"Executor Model",value:v,onChange:se=>{R("custom"),U(""),N(se)},models:De,disabled:I||_==="preset",favoriteProviders:ct,onToggleFavorite:Ot,favoriteModels:me,onToggleModelFavorite:nn})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Reviewer"}),t.jsx(Ns,{id:"validator-model",label:"Reviewer Model",value:k,onChange:se=>{R("custom"),U(""),E(se)},models:De,disabled:I||_==="preset",favoriteProviders:ct,onToggleFavorite:Ot,favoriteModels:me,onToggleModelFavorite:nn})]}),j&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),t.jsx(Ns,{id:"planning-model",label:"Planning Model",value:y||"",onChange:se=>{R("custom"),U(""),j(se)},models:De,disabled:I||_==="preset",favoriteProviders:ct,onToggleFavorite:Ot,favoriteModels:me,onToggleModelFavorite:nn})]}),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:P||"",onChange:se=>F(se.target.value),disabled:I||_==="preset",children:[t.jsxs("option",{value:"",children:["Default (",rt?.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"})]})]}),le&&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=>le(se.target.value===""?void 0:parseInt(se.target.value,10)),disabled:I,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"})]})]})]})]}),Ae,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:Ge.length>0&&Ge.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:C.includes(se.id),onChange:te=>{$(te.target.checked?[...C,se.id]:C.filter(Oe=>Oe!==se.id))},disabled:I}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[se.name,PI(se.phase||"pre-merge",se.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:se.description})]})]},se.id))})]}),C.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:"}),C.map((se,te)=>{const Oe=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:Oe?.name||se}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Yt(te),disabled:I||te===0,"data-testid":`workflow-step-move-up-${se}`,title:"Move up",children:t.jsx(Ri,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>rn(te),disabled:I||te===C.length-1,"data-testid":`workflow-step-move-down-${se}`,title:"Move down",children:t.jsx(un,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>_e(se),disabled:I,"data-testid":`workflow-step-remove-${se}`,title:"Remove",children:t.jsx(an,{})})]})]},se)})]})]})]})]})}const Lp={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 II(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function TI(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 $I(e){return e?new Date(e).toLocaleString():null}function DI(e){const n=e.split(`
684
- `);return n.length<=1?e:`${n.length} lines`}function il(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 LI({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 OI({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),v=n.some(S=>S.status==="pending"),{entries:N}=Hx(e,!!l&&v,o);i.useEffect(()=>{let S=!1;return $o(o).then(G=>{S||x(G.filter(he=>he.enabled))}).catch(()=>{S||x([])}),()=>{S=!0}},[o]);const k=a??[],E=i.useMemo(()=>g.map(S=>({id:S.id,name:S.name,description:S.description,phase:S.phase||"pre-merge"})),[g]),y=i.useMemo(()=>new Map(E.map(S=>[S.id,S])),[E]),j=S=>{u(G=>({...G,[S]:!G[S]}))},P=S=>{h(G=>{const he=G[S]??"markdown";return{...G,[S]:he==="markdown"?"plain":"markdown"}})},F=S=>{p(S)},_=()=>{p(null)};i.useEffect(()=>{if(!f)return;const S=G=>{G.key==="Escape"&&_()};return document.addEventListener("keydown",S),()=>{document.removeEventListener("keydown",S)}},[f]);const R=i.useCallback((S,G)=>{if(c){if(G){if(k.includes(S)){c(k);return}c([...k,S]);return}c(k.filter(he=>he!==S))}},[c,k]),L=i.useCallback(S=>{if(!c||S<=0)return;const G=[...k];[G[S-1],G[S]]=[G[S],G[S-1]],c(G)},[c,k]),U=i.useCallback(S=>{if(!c||S>=k.length-1)return;const G=[...k];[G[S],G[S+1]]=[G[S+1],G[S]],c(G)},[c,k]),C=i.useCallback(S=>{c&&c(k.filter(G=>G!==S))},[c,k]),$=n.length>0,V=k.length>0;i.useEffect(()=>{r||b(!1)},[r]);const Y=i.useMemo(()=>k.map(S=>{const G=y.get(S);return{id:S,name:G?.name||S,description:G?.description||"Step definition not found.",phase:G?.phase||"pre-merge"}}),[k,y]),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:E.map(S=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${S.id}`,children:[t.jsx("input",{type:"checkbox",checked:k.includes(S.id),onChange:G=>R(S.id,G.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[S.name,il(S.phase,S.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:S.description})]})]},S.id))})]}),k.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:"}),k.map((S,G)=>{const he=y.get(S);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${S}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:G+1}),t.jsx("span",{className:"workflow-step-order-name",children:he?.name||S}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>L(G),disabled:G===0,"data-testid":`workflow-step-move-up-${S}`,title:"Move up",children:t.jsx(Ri,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>U(G),disabled:G===k.length-1,"data-testid":`workflow-step-move-down-${S}`,title:"Move down",children:t.jsx(un,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>C(S),"data-testid":`workflow-step-remove-${S}`,title:"Remove",children:t.jsx(an,{})})]})]},S)})]})]}),q=()=>{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(!$)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 S=n.filter(ce=>ce.status==="passed").length,G=n.filter(ce=>ce.status==="failed").length,he=n.filter(ce=>ce.status==="skipped").length,Se=n.filter(ce=>ce.status==="pending").length,Ue=[`${n.length} step${n.length!==1?"s":""}`];return S>0&&Ue.push(`${S} passed`),G>0&&Ue.push(`${G} failed`),he>0&&Ue.push(`${he} skipped`),Se>0&&Ue.push(`${Se} 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:Ue.join(" · ")}),n.map((ce,Ae)=>{const X=ce.phase||"pre-merge",Z=d[ce.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${ce.status}`,"data-testid":`workflow-result-item-${ce.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[ce.workflowStepName,il(X,ce.workflowStepId,"workflow-result-phase")]}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${ce.status}`,"data-testid":`workflow-result-badge-${ce.workflowStepId}`,children:II(ce.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[ce.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",$I(ce.startedAt)]}),ce.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:TI(ce.startedAt,ce.completedAt)})]}),ce.status==="pending"&&ce.startedAt?t.jsx(LI,{entries:N,startedAt:ce.startedAt,stepId:ce.workflowStepId}):ce.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:()=>j(ce.workflowStepId),"data-testid":`workflow-result-toggle-${ce.workflowStepId}`,children:Z?"Hide output":"Show output"}),!Z&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${ce.workflowStepId}`,children:DI(ce.output)}),Z&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-mode-toggle",onClick:()=>P(ce.workflowStepId),"data-testid":`workflow-result-mode-toggle-${ce.workflowStepId}`,title:(m[ce.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(m[ce.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm workflow-result-expand-toggle",onClick:()=>F(ce.workflowStepId),"data-testid":`workflow-result-expand-${ce.workflowStepId}`,title:"Expand output",children:t.jsx(rc,{size:12})})]})]}),Z&&t.jsx("div",{className:`workflow-result-output${(m[ce.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${ce.workflowStepId}`,children:(m[ce.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(wi,{remarkPlugins:[ki],components:Lp,children:ce.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:ce.output})})]}):null]},`${ce.workflowStepId}-${Ae}`)})]})},A=r?t.jsx("button",{type:"button",className:"modal-edit-btn workflow-results-edit-toggle",onClick:()=>b(S=>!S),"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(bs,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(Os,{size:14}),"Edit"]})}):null,I=!s&&!$&&V,D=r&&$;return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[I?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:[Y.length," step",Y.length===1?"":"s"]})]}),A]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:Y.map(S=>t.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${S.id}`,children:[t.jsxs("div",{className:"workflow-configured-name",children:[S.name,il(S.phase,S.id,"workflow-configured-phase")]}),t.jsx("p",{className:"workflow-configured-description",children:S.description})]},S.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:[D&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:"Workflow Steps"}),A]}),q(),ne()]}),f&&(()=>{const S=n.find(Se=>Se.workflowStepId===f);if(!S)return null;const G=m[S.workflowStepId]??"markdown",he=S.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:Se=>{Se.target===Se.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:S.workflowStepName}),il(he,S.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:()=>P(S.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:G==="markdown"?"Switch to plain text":"Switch to markdown",children:G==="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(an,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${G==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:G==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(wi,{remarkPlugins:[ki],components:Lp,children:S.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:S.output})})})]})})})()]})}function zI(e){return e==="block"?"Block execution":e==="fallback-local"?"Fall back to local":"Not configured"}const FI=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function BI(e){return e!==void 0&&e!=="online"}function UI({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),$l().then(_=>{o(_)}).catch(_=>{u(Ce(_)||"Failed to load nodes")}).finally(()=>{c(!1)})},[]);const x=i.useMemo(()=>new Map(r.map(_=>[_.id,_])),[r]),w=i.useMemo(()=>[...r].sort((_,R)=>_.name.localeCompare(R.name)),[r]),b=n,v=e.nodeId??b?.defaultNodeId??null,N=e.nodeId?"Per-task override":b?.defaultNodeId?"Project default":"No routing",k=v?x.get(v):void 0,E=k?`${k.name} (${k.type})`:v?`${v} (node unavailable or unknown)`:"Local (no routing configured)",y=e.column==="in-progress"||FI.has(e.status),j=y||f||l,P=i.useCallback(async _=>{if(_===m)return;const R=e.id,L=m;h(_),p(!0);try{const U=await qs(R,{nodeId:_||null});if(g.current!==R)return;h(U.nodeId??""),a?.(U),s(_?"Node override updated":"Node override cleared","success")}catch(U){if(g.current!==R)return;h(L),s(Ce(U)||"Failed to update node override","error")}finally{g.current===R&&p(!1)}},[s,a,m,e.id]),F=i.useCallback(()=>{P("")},[P]);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:[k?t.jsx(Da,{status:k.status,compact:!0}):null,E,BI(k?.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:N})]}),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:zI(b?.unavailableNodePolicy)})]})]}),y&&v?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"}),y?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:j,onChange:_=>{P(_.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:y||f,onClick:F,children:"Clear override"})]}):null]})]})}const HI=/^[a-zA-Z0-9_-]{1,64}$/,qI=200;function Op(e){return e?new Date(e).toLocaleString():""}function VI(e,n=qI){return e.length<=n?e:e.substring(0,n)+"…"}function WI({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,v]=i.useState(null),[N,k]=i.useState([]),[E,y]=i.useState(!1),[j,P]=i.useState(!1),[F,_]=i.useState(""),[R,L]=i.useState(""),[U,C]=i.useState(!1),[$,V]=i.useState(null),[Y,ne]=i.useState(null),[q,A]=i.useState(!1),I=i.useCallback(async()=>{try{const X=await Tj(e,a);l(X)}catch(X){n(Ce(X)||"Failed to load documents","error")}finally{d(!1)}},[e,a,n]);i.useEffect(()=>{I()},[I]);async function D(X){u===X.key?(m(null),f(""),g(null),w(""),v(null),k([]),A(!1)):(m(X.key),f(X.content),g(null),w(""),v(null),k([]),A(!1))}async function S(X){if(b===X)v(null),k([]);else{v(X),y(!0);try{const Z=await $j(e,X,a);k(Z)}catch(Z){n(Ce(Z)||"Failed to load revisions","error")}finally{y(!1)}}}function G(){u&&(g(u),w(h))}function he(){g(null),w("")}async function Se(){if(!(!p||!x.trim())){C(!0);try{await Em(e,p,x,{},a),g(null),w(""),await I();const X=o.find(Z=>Z.key===p);X&&f(X.content),n("Document saved","success")}catch(X){n(Ce(X)||"Failed to save document","error")}finally{C(!1)}}}async function Ue(){const X=F.trim(),Z=R.trim();if(!X){n("Document key is required","error");return}if(!HI.test(X)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!Z){n("Content is required","error");return}C(!0);try{await Em(e,X,Z,{},a),P(!1),_(""),L(""),await I(),n("Document created","success")}catch(ee){n(Ce(ee)||"Failed to create document","error")}finally{C(!1)}}async function ce(X){V(X);try{await Dj(e,X,a),ne(null),V(null),u===X&&(m(null),f("")),b===X&&(v(null),k([])),await I(),n("Document deleted","success")}catch(Z){n(Ce(Z)||"Failed to delete document","error")}finally{V(null)}}function Ae(X){f(X.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"}),j&&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:X=>_(X.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:R,onChange:X=>L(X.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:()=>{P(!1),_(""),L("")},disabled:U,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Ue(),disabled:U||!F.trim()||!R.trim(),children:U?"Creating…":"Create"})]})]}),o.length===0&&!j?t.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):t.jsx("div",{className:"task-documents-list",children:o.map(X=>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(oa,{size:14}),t.jsx("span",{className:"task-document-key",children:X.key}),t.jsxs("span",{className:"task-document-revision-badge",children:["v",X.revision]})]}),t.jsxs("div",{className:"task-document-meta",children:[t.jsx("span",{className:"task-document-author",children:X.author}),t.jsx("span",{className:"task-document-timestamp",children:Op(X.updatedAt||X.createdAt)})]})]}),u===X.key&&p!==X.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(Z=>!Z),"aria-label":q?"Switch to plain text":"Switch to markdown","aria-pressed":q,title:q?"Switch to plain text":"Switch to markdown",children:q?"Markdown":"Plain"})}),t.jsx("div",{className:"task-document-content",children:q?t.jsx("div",{className:"task-document-content-markdown",children:t.jsx("div",{className:"markdown-body",children:t.jsx(wi,{remarkPlugins:[ki],children:h})})}):t.jsx("pre",{className:"task-document-content-text",children:h})}),b===X.key&&t.jsxs("div",{className:"task-document-revisions",children:[t.jsx("h5",{children:"Revision History"}),E?t.jsx("div",{className:"detail-log-empty",children:"Loading…"}):N.length<=1?t.jsx("div",{className:"detail-log-empty",children:"No previous revisions."}):t.jsx("div",{className:"task-document-revision-list",children:N.filter(Z=>Z.revision<X.revision).sort((Z,ee)=>ee.revision-Z.revision).map(Z=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>Ae(Z),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",Z.revision]}),t.jsx("span",{className:"revision-author",children:Z.author}),t.jsx("span",{className:"revision-timestamp",children:Op(Z.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:VI(Z.content,100)})]},Z.id))})]})]}),p===X.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:x,onChange:Z=>w(Z.target.value),rows:10,disabled:U}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:he,disabled:U,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Se(),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 D(X),children:u===X.key?t.jsxs(t.Fragment,{children:[t.jsx(Ri,{size:14})," Collapse"]}):t.jsxs(t.Fragment,{children:[t.jsx(un,{size:14})," Expand"]})}),u===X.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void S(X.key),children:[t.jsx(Pa,{size:14})," History"]}),r&&p!==X.key&&t.jsx("button",{className:"btn btn-sm",onClick:G,children:"Edit"}),r&&(Y===X.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 ce(X.key),disabled:$===X.key,children:$===X.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>ne(null),disabled:$===X.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>ne(X.key),children:t.jsx(Sn,{size:14})}))]})]})]},X.key))}),r&&!j&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>P(!0),children:[t.jsx(Cn,{size:14})," New Document"]})]})}function al(e){return e.toLocaleString()}function dd(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function Wr(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 KI(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=Cb(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 GI({tokenUsage:e,loading:n,task:s}){const a=Date.now(),r=Nb(s?.log??[]),o=r.filter(g=>typeof g.durationMs=="number"),l=o.reduce((g,x)=>g+(x.durationMs??0),0),c=Sb(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=KI(s?.workflowStepResults??[]),f=Eb(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:Wr(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:Wr(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:Wr(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} (${Wr(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} (${Wr(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 ${dd(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:al(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:al(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:al(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:al(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:dd(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:dd(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}const am=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function JI(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 YI(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 Yx(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 QI(e,n,s,a){const r=JI(n);if(r)return r;if(am.has(e.status??"")||e.column==="in-progress"){const o=Yx(s);if(o.provider&&o.modelId)return o}return pb(e,a)}function XI(e,n,s,a){const r=YI(n);if(r)return r;if(am.has(e.status??"")||e.column==="in-progress"){const o=Yx(s);if(o.provider&&o.modelId)return o}return fb(e,a)}function ZI(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 eT(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const a=ZI(n);return a||gb(e,s)}function tT(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 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()}function sT(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function ud(e,n){return e.length>n?e.slice(0,n)+"…":e}function zp(e=[],n=[]){return e.length===n.length&&e.every((s,a)=>s===n[a])}function md(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function hd(e){return e.trim()}function iT(e){const n=e.trim();return n.length>0?n:void 0}function Fi(e){return typeof e=="string"&&da.includes(e)?e:Ms}function Bi(e){return e==="fast"?"fast":"standard"}function aT(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function rT(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 oT=i.lazy(()=>kn(()=>import("./AgentDetailView-Cv-vgOj3.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(e=>({default:e.AgentDetailView})));function lT(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:aT(e.sourceMetadata)};case"research":return{label:"Research",contextInfo:rT(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 pd=200,cT=new Set(["triage","todo"]);function Qx({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,v]=i.useState(p),[N,k]=i.useState(()=>"prompt"in e?e:null),[E,y]=i.useState(()=>!("prompt"in e));i.useEffect(()=>{if("prompt"in e){k(e),y(!1);return}let J=!1;return y(!0),k(null),$a(e.id,n).then(Le=>{J||(k(Le),y(!1))}).catch(()=>{J||y(!1)}),()=>{J=!0}},[e.id,n]);const j=N?{...N,...e,prompt:N.prompt,log:N.log}:{...e,prompt:""},P=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),[R,L]=i.useState(null),U=lT(j,{sourceAgentName:F?.name});i.useEffect(()=>{v(p)},[p]),i.useEffect(()=>{Y(!1)},[e.id]);const[C,$]=i.useState("activity"),[V,Y]=i.useState(!1),[ne,q]=i.useState(e.attachments||[]),[A,I]=i.useState(!1),[D,S]=i.useState(e.dependencies||[]),[G,he]=i.useState(!1),[Se,Ue]=i.useState(""),[ce,Ae]=i.useState(null),[X,Z]=i.useState([]),[ee,le]=i.useState(!1),[K,O]=i.useState(!1),[pe,ve]=i.useState(!1),[B,we]=i.useState(!1),[ze,re]=i.useState(!1),[He,Pe]=i.useState(j.prompt||""),[tt,qe]=i.useState(""),[de,De]=i.useState(!1),[Te,ct]=i.useState(""),[Ve,me]=i.useState(!1),[oe,Me]=i.useState(!1),[Xe,rt]=i.useState(e.title||""),[ht,yt]=i.useState(e.description||""),[Re,Ge]=i.useState(e.dependencies||[]),[at,ie]=i.useState(e.branch??""),[Ke,je]=i.useState(e.baseBranch??""),[Fe,Be]=i.useState(""),[St,ye]=i.useState(""),[kt,It]=i.useState(""),[Ie,be]=i.useState(""),[ot,gt]=i.useState("default"),[xt,jt]=i.useState(void 0),[Bt,Jt]=i.useState(Ms),[Vt,pn]=i.useState(e.nodeId),[Xt,mn]=i.useState(Bi(e.executionMode)),[Ht,Zt]=i.useState(""),[tn,dn]=i.useState(e.enabledWorkflowSteps||[]),[qt,ke]=i.useState(e.sourceIssue?.provider??""),[$e,Ye]=i.useState(e.sourceIssue?.repository??""),[ut,We]=i.useState(e.sourceIssue?.externalIssueId??""),[$t,At]=i.useState(e.sourceIssue?.url??""),[wt,zt]=i.useState([]),[Lt,Ot]=i.useState(!1),[nn,Yt]=i.useState(Fi(e.priority)),[rn,_e]=i.useState(!1),[it,bt]=i.useState(Bi(e.executionMode)),[Rt,se]=i.useState(!1),te=i.useRef(!1),[Oe,mt]=i.useState(!1),[Pt,sn]=i.useState(!1),[In,fe]=i.useState(!1),[ft,lt]=i.useState(e.githubTracking?.repoOverride??""),[vt,et]=i.useState(null),[_t,Gt]=i.useState(!1),ae=i.useRef(null),pt=i.useRef(null),gn=i.useRef(null),{getSlotsForId:us}=lb(n),_n=us("task-detail-tab").map((J,Le)=>({entry:J,tabId:`plugin-${J.pluginId}-${Le}`})),$n=typeof b=="string"&&b.startsWith("plugin-")?_n.find(J=>J.tabId===b)??null:null;i.useEffect(()=>(te.current=!0,()=>{te.current=!1}),[]);const[hn,Ut]=i.useState(void 0),[Dn,as]=i.useState(null),[Rn,ms]=i.useState([]),[Xn,vs]=i.useState(!1),[Gn,hs]=i.useState(e.enabledWorkflowSteps||[]),Ln=e.column==="in-progress"||am.has(e.status);i.useEffect(()=>{rt(e.title||""),yt(e.description||""),ie(e.branch??""),je(e.baseBranch??""),ke(e.sourceIssue?.provider??""),Ye(e.sourceIssue?.repository??""),We(e.sourceIssue?.externalIssueId??""),At(e.sourceIssue?.url??""),mn(Bi(e.executionMode)),fe(!1),lt(e.githubTracking?.repoOverride??""),et(null),Me(!1)},[e.id,e.title,e.description,e.branch,e.baseBranch,e.sourceIssue,e.executionMode,e.githubTracking]),i.useEffect(()=>{hs(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),i.useEffect(()=>{Yt(Fi(e.priority))},[e.id,e.priority]),i.useEffect(()=>{bt(Bi(e.executionMode))},[e.id,e.executionMode]),i.useEffect(()=>{let J=!1;return oc(n).then(Le=>{J||Ut(Le)}).catch(()=>{}),Ki().then(Le=>{J||as(Le)}).catch(()=>{J||as(null)}),()=>{J=!0}},[n]),i.useEffect(()=>{if(b!=="workflow")return;let J=!1;return vs(!0),wS(e.id,n).then(Le=>{J||ms(Le)}).catch(Le=>{J||h(`Failed to load workflow results: ${Ce(Le)}`,"error")}).finally(()=>{J||vs(!1)}),()=>{J=!0}},[b,e.id,n,h]),i.useEffect(()=>{if(b!=="workflow")return;const J=n?`?projectId=${encodeURIComponent(n)}`:"",Le=Ct=>{try{const Kt=JSON.parse(Ct.data);Kt.id===e.id&&Array.isArray(Kt.workflowStepResults)&&ms(Kt.workflowStepResults)}catch{}};return li(`/api/events${J}`,{events:{"task:updated":Le}})},[b,e.id,n]),i.useEffect(()=>{G||Ue("")},[G]),i.useEffect(()=>{if(!e.assignedAgentId){Ae(null);return}const J=X.find(Ct=>Ct.id===e.assignedAgentId);if(J){Ae(J);return}let Le=!1;return Yd(e.assignedAgentId,n).then(Ct=>{Le||Ae(Ct)}).catch(()=>{Le||Ae(null)}),()=>{Le=!0}},[e.assignedAgentId,n,X]),i.useEffect(()=>{if(!e.sourceAgentId){_(null);return}const J=X.find(Ct=>Ct.id===e.sourceAgentId);if(J){_(J);return}let Le=!1;return Promise.resolve(Yd(e.sourceAgentId,n)).then(Ct=>{Le||_(Ct??null)}).catch(()=>{Le||_(null)}),()=>{Le=!0}},[e.sourceAgentId,n,X]),i.useEffect(()=>{le(!1)},[e.id]),i.useEffect(()=>{if(!(Oe||Pt))return;const Le=Ct=>{const Kt=Ct.target,Qn=ae.current?.contains(Kt),zi=gn.current?.contains(Kt);!Qn&&Oe&&mt(!1),!zi&&Pt&&sn(!1)};return document.addEventListener("mousedown",Le),()=>document.removeEventListener("mousedown",Le)},[Oe,Pt]),i.useEffect(()=>{if(!(Oe||Pt))return;const Le=Ct=>{Ct.key==="Escape"&&(Ct.stopPropagation(),Oe&&mt(!1),Pt&&sn(!1))};return document.addEventListener("keydown",Le),()=>document.removeEventListener("keydown",Le)},[Oe,Pt]),i.useEffect(()=>{re(!1),Pe(j.prompt||""),qe("")},[e.id,j.prompt]);const En=cT.has(e.column)&&!Lt,ps=e.githubTracking?.enabled===!0,Nn=e.githubTracking?.issue,As=ps||!!Nn,Cs=Gx(hn??null,Dn),Es=ft.trim(),Q=i.useCallback(async()=>{if(!(!En||_t)){Gt(!0);try{const J=await qs(e.id,{githubTracking:{enabled:!ps}},n);m?.(J)}catch(J){h(`Failed to update ${e.id}: ${Ce(J)}`,"error")}finally{te.current&&Gt(!1)}}},[h,En,ps,_t,m,n,e.id]),M=i.useCallback(async()=>{if(!(!En||_t)){if(Es.length>0&&!dc.test(Es)){et("Repository override must be in owner/repo format");return}et(null),Gt(!0);try{const J=await qs(e.id,{githubTracking:{repoOverride:Es.length>0?Es:null}},n);m?.(J)}catch(J){h(`Failed to update ${e.id}: ${Ce(J)}`,"error")}finally{te.current&&Gt(!1)}}},[h,En,Es,_t,m,n,e.id]),ue=i.useCallback(()=>{if(!En)return;Me(!0),rt(e.title||""),yt(e.description||""),Ge(e.dependencies||[]),ie(e.branch??""),je(e.baseBranch??"");const J=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",Le=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",Ct=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";Be(J),ye(Le),It(Ct),be(e.thinkingLevel??""),pn(e.nodeId),gt(J||Le||Ct?"custom":"default"),Zt(""),dn(e.enabledWorkflowSteps||[]),mn(Bi(e.executionMode)),ke(e.sourceIssue?.provider??""),Ye(e.sourceIssue?.repository??""),We(e.sourceIssue?.externalIssueId??""),At(e.sourceIssue?.url??""),zt([]),jt(e.reviewLevel),Jt(Fi(e.priority))},[En,e]),Ee=i.useCallback(()=>{Me(!1),rt(e.title||""),yt(e.description||""),Ge(e.dependencies||[]),ie(e.branch??""),je(e.baseBranch??""),pn(e.nodeId),ke(e.sourceIssue?.provider??""),Ye(e.sourceIssue?.repository??""),We(e.sourceIssue?.externalIssueId??""),At(e.sourceIssue?.url??""),Jt(Fi(e.priority)),mn(Bi(e.executionMode)),wt.forEach(J=>URL.revokeObjectURL(J.previewUrl)),zt([])},[e.title,e.description,e.dependencies,e.nodeId,e.priority,e.executionMode,wt]),[z,ge]=i.useState("idle"),xe=i.useRef(null),dt=i.useRef(0),Tt=i.useCallback(J=>{const Le={},Ct=Xe.trim(),Kt=ht.trim();Ct&&Ct!==(e.title??"")&&(Le.title=Ct),J&&Kt&&Kt!==(e.description??"")&&(Le.description=Kt),zp(Re,e.dependencies??[])||(Le.dependencies=Re),zp(tn,e.enabledWorkflowSteps??[])||(Le.enabledWorkflowSteps=tn);const Qn=at.trim()||null,zi=e.branch??null;Qn!==zi&&(Le.branch=Qn);const dm=Ke.trim()||null,Vv=e.baseBranch??null;dm!==Vv&&(Le.baseBranch=dm);const um=md(Fe),Wv=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";Fe!==Wv&&(Le.modelProvider=um?.provider??null,Le.modelId=um?.modelId??null);const mm=md(St),Kv=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";St!==Kv&&(Le.validatorModelProvider=mm?.provider??null,Le.validatorModelId=mm?.modelId??null);const hm=md(kt),Gv=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";kt!==Gv&&(Le.planningModelProvider=hm?.provider??null,Le.planningModelId=hm?.modelId??null);const Jv=e.thinkingLevel??"";Ie!==Jv&&(Le.thinkingLevel=Ie!==""?Ie:null),(e.nodeId??void 0)!==Vt&&(Le.nodeId=Vt??null),xt!==e.reviewLevel&&(Le.reviewLevel=xt),Bt!==Fi(e.priority)&&(Le.priority=Bt),Xt!==Bi(e.executionMode)&&(Le.executionMode=Xt==="fast"?"fast":null);const vc=hd(qt),yc=hd($e),Ho=hd(ut),wc=iT($t);if(vc.length===0&&yc.length===0&&Ho.length===0&&!wc)e.sourceIssue&&(Le.sourceIssue=null);else{if(!vc||!yc||!Ho)return{updates:null,error:"Source issue provider, repository, and issue identifier are required"};const Yv=Number.parseInt(Ho,10),kc=e.sourceIssue?.issueNumber??Yv;if(!Number.isFinite(kc)||kc<=0)return{updates:null,error:"Source issue identifier must be numeric for new metadata"};const Ya={provider:vc,repository:yc,externalIssueId:Ho,issueNumber:kc,...wc?{url:wc}:{}},Qa=e.sourceIssue;(!Qa||Qa.provider!==Ya.provider||Qa.repository!==Ya.repository||Qa.externalIssueId!==Ya.externalIssueId||Qa.issueNumber!==Ya.issueNumber||(Qa.url??void 0)!==Ya.url)&&(Le.sourceIssue=Ya)}return{updates:Le,error:null}},[Ke,at,Re,ht,Xt,Fe,Vt,kt,Bt,xt,tn,ut,qt,$e,$t,Ie,Xe,St,e]),Wt=i.useCallback(async J=>{const{updates:Le,error:Ct}=Tt(J);if(!Le)return ge("error"),Ct&&h(`Failed to update ${e.id}: ${Ct}`,"error"),!1;if(Object.keys(Le).length===0)return!0;const Kt=++dt.current;Ot(!0),ge("saving");try{const Qn=await qs(e.id,Le,n);return Kt!==dt.current?void 0:(m?.(Qn),ge("saved"),!0)}catch(Qn){return Kt===dt.current&&(ge("error"),h(`Failed to update ${e.id}: ${Ce(Qn)}`,"error")),!1}finally{te.current&&Kt===dt.current&&Ot(!1)}},[h,Tt,m,n,e.id]),bn=i.useCallback(async J=>{await Wt(!0)},[Wt]),Mn=i.useCallback(async()=>{await Wt(!0)&&(h(`Updated ${e.id}`,"success"),te.current&&Me(!1))},[h,Wt,e.id]);i.useEffect(()=>{if(oe)return xe.current&&clearTimeout(xe.current),xe.current=setTimeout(()=>{Wt(!1)},700),()=>{xe.current&&(clearTimeout(xe.current),xe.current=null)}},[oe,Xe,Re,at,Ke,Fe,St,kt,Ie,Vt,xt,Bt,Xt,tn,qt,$e,ut,$t,Wt]);const Zn=i.useCallback(async J=>{const Le=Fi(J),Ct=Fi(e.priority);if(Le===Ct){Yt(Ct);return}const Kt=nn;Yt(Le),_e(!0);try{const Qn=await qs(e.id,{priority:Le},n);Yt(Fi(Qn.priority)),m?.(Qn),h(`Priority updated to ${Fi(Qn.priority)}`,"success")}catch(Qn){Yt(Kt),h(`Failed to update ${e.id}: ${Ce(Qn)}`,"error")}finally{te.current&&_e(!1)}},[e.id,e.priority,n,nn,m,h]),On=i.useCallback(async()=>{const Le=Bi(e.executionMode)==="fast"?"standard":"fast",Ct=it;bt(Le),se(!0);try{const Kt=await qs(e.id,{executionMode:Le==="fast"?"fast":null},n),Qn=Bi(Kt.executionMode);bt(Qn),m?.(Kt),h(`Execution mode updated to ${Qn}`,"success")}catch(Kt){bt(Ct),h(`Failed to update ${e.id}: ${Ce(Kt)}`,"error")}finally{te.current&&se(!1)}},[e.id,e.executionMode,n,it,m,h]),Un=i.useCallback(J=>{oe&&(J.key==="Escape"?(J.preventDefault(),Ee()):J.key==="Enter"&&(J.ctrlKey||J.metaKey)&&(J.preventDefault(),Mn()))},[oe,Ee,Mn]);i.useEffect(()=>{if(oe)return document.addEventListener("keydown",Un),()=>document.removeEventListener("keydown",Un)},[oe,Un]);const rs=i.useRef(null),{nodes:ts}=uc(),{confirm:xn}=ci(),Jn=i.useCallback(async()=>{if(!(!En||!Nn||_t||!await xn({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}))){Gt(!0);try{const Le=await qs(e.id,{githubTracking:{issue:null}},n);m?.(Le),h("GitHub issue unlinked","success")}catch(Le){h(`Failed to update ${e.id}: ${Ce(Le)}`,"error")}finally{te.current&&Gt(!1)}}},[h,En,xn,Nn,_t,m,n,e.id]),{entries:Hn,loading:ws,loadMore:ns,hasMore:es,total:Bs,loadingMore:Ds}=Hx(e.id,b==="logs"&&C==="agent-log",n),wn=i.useCallback(()=>{w?.()},[w]);i.useEffect(()=>{if(x)return;const J=Le=>{Le.key==="Escape"&&!oe&&wn()};return document.addEventListener("keydown",J),()=>document.removeEventListener("keydown",J)},[x,wn,oe]);const ma=i.useCallback(async J=>{try{const Le=e.steps.some(Qn=>Qn.status!=="pending"),Ct=(J==="todo"||J==="triage")&&Le;let Kt;if(Ct){if(await xn({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Kt={preserveProgress:!0};else if(!await xn({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,J,Kt),wn(),h(`Moved to ${cs[J]}`,"success")}catch(Le){h(Ce(Le),"error")}},[e.id,e.steps,r,wn,h,xn]),ha=i.useCallback(async()=>{if(await xn({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0}))try{await o(e.id),wn(),h(`Deleted ${e.id}`,"info")}catch(Le){const Ct=Lu(Le);if(!Ct||Ct.dependentIds.length===0){h(Ce(Le),"error");return}const Kt=Ct.dependentIds.join(", ");if(!await xn({title:"Force Delete Task",message:`${e.id} is a dependency of ${Kt}.
685
-
686
- Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await o(e.id,{removeDependencyReferences:!0}),wn(),h(`Deleted ${e.id} after removing dependency references`,"info")}catch(zi){h(Ce(zi),"error")}}},[e.id,o,wn,h,xn]),pa=i.useCallback(async()=>{await xn({title:"Merge Task",message:`Merge ${e.id} into the current branch?`})&&(wn(),h(`Merging ${e.id}...`,"info"),l(e.id).then(Le=>{const Ct=Le.merged?`Merged ${e.id} (branch: ${Le.branch})`:`Closed ${e.id} (${Le.error||"no branch to merge"})`;h(Ct,"success")}).catch(Le=>{h(Ce(Le),"error")}))},[e.id,l,wn,h,xn]),Ha=i.useCallback(()=>{c&&(wn(),c(e.id).then(()=>{h(`Retried ${e.id}`,"success")}).catch(J=>{h(Ce(J),"error")}))},[e.id,c,wn,h]),ei=i.useCallback(()=>{d&&window.confirm(`This will erase all progress for ${e.id} and start the task from scratch. Continue?`)&&(wn(),d(e.id).then(()=>{h(`Reset ${e.id} — fresh run will be allocated`,"success")}).catch(J=>{h(Ce(J),"error")}))},[e.id,d,wn,h]),di=i.useCallback(async()=>{if(!(!u||!await xn({title:"Duplicate Task",message:`Duplicate ${e.id}? This will create a new task in Triage with the same description and prompt.`})))try{const Le=await u(e.id);wn(),h(`Duplicated ${e.id} → ${Le.id}`,"success")}catch(Le){h(Ce(Le),"error")}},[e.id,u,wn,h,xn]),Di=i.useCallback(async()=>{try{e.paused?(await jj(e.id,n),h(`Unpaused ${e.id}`,"success")):(await Kg(e.id,n),h(`Paused ${e.id}`,"success")),wn()}catch(J){h(Ce(J),"error")}},[e.id,e.paused,wn,h]),fa=i.useCallback(async()=>{try{await Ej(e.id,n),h(`Plan approved — ${e.id} moved to Todo`,"success"),wn()}catch(J){h(Ce(J),"error")}},[e.id,wn,h]),qa=i.useCallback(async()=>{if(await xn({title:"Reject Plan",message:"Reject this plan? The specification will be discarded and regenerated.",danger:!0}))try{await _j(e.id,n),h(`Plan rejected — ${e.id} returned to Planning for replanning`,"info"),wn()}catch(Le){h(Ce(Le),"error")}},[e.id,wn,h,xn]),Va=i.useCallback(async()=>{if(await xn({title:"Rebuild Plan",message:"Rebuild the plan for this task? The task will move to planning for replanning."}))try{await zj(e.id,n),wn(),h(`Replanning ${e.id}...`,"info")}catch(Le){h(Ce(Le),"error")}},[e.id,n,wn,h,xn]),ga=i.useCallback(()=>{De(!0),ct("")},[]),ti=i.useCallback(()=>{mt(!1),sn(!1)},[]),ui=i.useCallback(J=>{ti(),ma(J)},[ti]),ni=i.useCallback(J=>{ti(),J()},[ti]),ba=i.useCallback(()=>{ti(),pa()},[ti,pa]),xa=i.useCallback(()=>{De(!1),ct(""),me(!1)},[]),va=i.useCallback(async()=>{if(!Te.trim()){h("Please enter feedback describing what needs refinement","error");return}if(Te.length>2e3){h("Feedback must be 2000 characters or less","error");return}me(!0);try{const J=await Fj(e.id,Te.trim(),n);h(`Refinement task created: ${J.id}`,"success"),wn()}catch(J){h(Ce(J),"error")}finally{me(!1)}},[e.id,Te,h,wn]),Ls=i.useCallback(async J=>{I(!0);try{const Le=await lc(e.id,J,n);q(Ct=>[...Ct,Le]),h("Screenshot attached","success")}catch(Le){h(Ce(Le),"error")}finally{I(!1)}},[e.id,h]),Wa=i.useCallback(async J=>{const Le=J.target.files?.[0];Le&&(await Ls(Le),rs.current&&(rs.current.value=""))},[Ls]);i.useEffect(()=>{const J=Le=>{const Ct=Le.clipboardData?.items;if(Ct)for(let Kt=0;Kt<Ct.length;Kt++){const Qn=Ct[Kt];if(Qn.type.startsWith("image/")){const zi=Qn.getAsFile();if(zi){Le.preventDefault(),Ls(zi);return}}}};return document.addEventListener("paste",J),()=>document.removeEventListener("paste",J)},[Ls]);const ya=i.useCallback(J=>{J.preventDefault()},[]),Qi=i.useCallback(J=>{J.preventDefault();const Le=J.dataTransfer.files;for(let Ct=0;Ct<Le.length;Ct++){const Kt=Le[Ct];if(Kt.type.startsWith("image/")){Ls(Kt);return}}},[Ls]),Tr=i.useCallback(async J=>{try{await Rj(e.id,J,n),q(Le=>Le.filter(Ct=>Ct.filename!==J)),h("Attachment deleted","info")}catch(Le){h(Ce(Le),"error")}},[e.id,h]),$r=i.useCallback(async J=>{const Le=Gn;hs(J);try{const Ct=await qs(e.id,{enabledWorkflowSteps:J},n);h("Workflow steps updated","success"),m?.(Ct)}catch(Ct){hs(Le),h(`Failed to update workflow steps: ${Ce(Ct)}`,"error")}},[e.id,n,Gn,m,h]),Dr=i.useCallback(async()=>{O(!0);try{const J=await Mr(void 0,n);Z(J),le(!0)}catch(J){h(`Failed to load agents: ${Ce(J)}`,"error"),le(!1)}finally{O(!1)}},[n,h]),wa=i.useCallback(async J=>{try{const Le=await zm(e.id,J,n),Ct=X.find(Kt=>Kt.id===J)??null;Ae(Ct||(Kt=>Kt?.id===J?Kt:null)),le(!1),m?.(Le),h("Assigned agent updated","success")}catch(Le){h(`Failed to assign agent: ${Ce(Le)}`,"error")}},[e.id,n,X,m,h]),ka=i.useCallback(async()=>{try{const J=await zm(e.id,null,n);Ae(null),le(!1),m?.(J),h("Agent unassigned","success")}catch(J){h(`Failed to unassign agent: ${Ce(J)}`,"error")}},[e.id,n,m,h]),Li=i.useCallback(async J=>{const Le=[...D,J];S(Le);try{await qs(e.id,{dependencies:Le},n)}catch(Ct){S(D),h(Ce(Ct),"error")}},[e.id,D,h]),Ka=i.useCallback(async(J,Le)=>{J.stopPropagation();const Ct=D.filter(Kt=>Kt!==Le);S(Ct);try{await qs(e.id,{dependencies:Ct},n)}catch(Kt){S(D),h(Ce(Kt),"error")}},[e.id,D,h]),Oi=i.useCallback(async J=>{try{const Le=await $a(J,n);a(Le)}catch{h(`Failed to load dependency ${J}`,"error")}},[a,h]),ja=i.useCallback(async J=>{ve(!0);try{await qs(j.id,{prompt:J},n),h("Spec updated","success"),N&&(N.prompt=J)}catch(Le){throw h(Ce(Le),"error"),Le}finally{ve(!1)}},[j,N,h]),Ga=i.useCallback(async J=>{we(!0);try{await Oj(e.id,J,n),h("AI revision requested. Task moved to planning.","success"),wn()}catch(Le){const Ct=Ce(Le);Ct.includes("done")||Ct.includes("archived")?h("Cannot request revision: Task must be in 'triage', 'todo', 'in-progress', or 'in-review' column.","error"):h(Ct,"error")}finally{we(!1)}},[e.id,h,wn]),Na=i.useCallback(()=>{re(!0),Pe(j.prompt||""),qe("")},[j.prompt]),Ni=i.useCallback(()=>{re(!1),Pe(j.prompt||""),qe("")},[j.prompt]),Qe=i.useCallback(async()=>{if(He===(j.prompt||"")){Ni();return}re(!1);try{await ja(He)}catch(J){throw re(!0),J}},[He,j.prompt,ja,Ni]),Dt=i.useCallback(async()=>{tt.trim()&&await Ga(tt.trim())},[tt,Ga]),on=i.useCallback(J=>{J.key==="Escape"?(J.preventDefault(),Ni()):J.key==="Enter"&&(J.ctrlKey||J.metaKey)&&(J.preventDefault(),Qe())},[Ni,Qe]),os=s.filter(J=>J.id!==e.id&&!D.includes(J.id)).sort((J,Le)=>{const Ct=Le.createdAt.localeCompare(J.createdAt);if(Ct!==0)return Ct;const Kt=parseInt(J.id.slice(J.id.lastIndexOf("-")+1),10)||0;return(parseInt(Le.id.slice(Le.id.lastIndexOf("-")+1),10)||0)-Kt}),Ne=i.useMemo(()=>Ib(s),[s]).get(e.id),Je=i.useMemo(()=>{if(!Ne)return[];const J=new Set(Ne.staleBlockedByDependentIds);return Ne.dependentIds.map(Le=>{const Ct=s.find(Kt=>Kt.id===Le);return{id:Le,label:Ct?.title||Ct?.description||Le,stale:J.has(Le)}})},[Ne,s]),Mt=ce?.name??e.assignedAgentId??null,fn=i.useMemo(()=>{const J=[];return j.modelProvider&&J.push(j.modelProvider),j.validatorModelProvider&&!J.includes(j.validatorModelProvider)&&J.push(j.validatorModelProvider),j.planningModelProvider&&!J.includes(j.planningModelProvider)&&J.push(j.planningModelProvider),J},[j.modelProvider,j.validatorModelProvider,j.planningModelProvider]),en=Qd[e.column]||[],An=["todo","in-progress"],st=e.column==="in-review"?An:en,Ze=st[0],Ft=st.slice(1),ln=Ft.length>0,Ks=i.useCallback(()=>{mt(!1),pt.current?.focus()},[]),mi=i.useCallback(J=>{if(!ln){Ze&&ui(Ze);return}const Le=J.currentTarget.querySelector(".detail-move-btn__arrow");if(!!(J.target instanceof Element&&J.target.closest(".detail-move-btn__arrow")||Le&&J.clientX>0&&J.clientX>=Le.getBoundingClientRect().left)){mt(Kt=>!Kt),sn(!1);return}Ze&&ui(Ze)},[ln,Ze,ui]),ls=i.useCallback(J=>{!ln||!(J.key==="ArrowDown"||J.altKey&&J.key==="ArrowDown")||(J.preventDefault(),mt(!0),sn(!1))},[ln]),Yn=i.useCallback(J=>{J.key==="Escape"&&(J.preventDefault(),J.stopPropagation(),Ks())},[Ks]);i.useEffect(()=>{if(!Oe)return;ae.current?.querySelector(".detail-move-menu-item")?.focus()},[Oe]);const vn={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…","merging-fix":"Merging fixes…"},hi=e.status?vn[e.status]:void 0,Us=hn?.mergeStrategy??"direct",pi=hn?.autoMerge??!1,Ja=Us==="pull-request"&&!pi;let Xi="Merge & Close";return Ja&&!hi&&(e.prInfo?e.prInfo.status==="open"?Xi="Check PR Status":e.prInfo.status==="merged"&&(Xi="Finish & Close"):Xi="Start PR Review"),t.jsxs("div",{className:x?"task-detail-content task-detail-content--embedded":"task-detail-content",onDragOver:ya,onDrop:Qi,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:cs[e.column]})]}),t.jsxs("div",{className:"modal-header-actions",children:[!oe&&En&&t.jsx("button",{className:"modal-edit-btn",onClick:ue,title:"Edit task","aria-label":"Edit task",children:t.jsx(Os,{size:14})}),!x&&g==="back"&&t.jsxs("button",{className:"modal-close task-detail-mobile-back",onClick:wn,"aria-label":"Back to task list",type:"button",children:[t.jsx(Fa,{"aria-hidden":"true"}),t.jsx("span",{children:"Back"})]}),!x&&g!=="back"&&t.jsx("button",{className:"modal-close",onClick:wn,"aria-label":"Close",type:"button",children:"×"})]})]}),t.jsxs("div",{className:`detail-body${b==="logs"&&C==="agent-log"&&!oe?" detail-body--agent-log":""}`,children:[oe?t.jsx("div",{className:"modal-edit-form",children:t.jsx(Jx,{mode:"edit",title:Xe,onTitleChange:rt,description:ht,onDescriptionChange:yt,dependencies:Re,onDependenciesChange:Ge,branch:at,onBranchChange:ie,baseBranch:Ke,onBaseBranchChange:je,executorModel:Fe,onExecutorModelChange:Be,validatorModel:St,onValidatorModelChange:ye,planningModel:kt,onPlanningModelChange:It,thinkingLevel:Ie,onThinkingLevelChange:be,presetMode:ot,onPresetModeChange:gt,selectedPresetId:Ht,onSelectedPresetIdChange:Zt,selectedWorkflowSteps:tn,onWorkflowStepsChange:dn,pendingImages:wt,onImagesChange:zt,tasks:s.filter(J=>J.id!==e.id),projectId:n,disabled:Lt,addToast:h,isActive:oe,onAutoSaveDescription:bn,reviewLevel:xt,onReviewLevelChange:jt,priority:Bt,onPriorityChange:Jt,nodeId:Vt,onNodeIdChange:pn,nodeOptions:ts,nodeOverrideDisabled:Ln,nodeOverrideDisabledReason:Ln?"Execution node override is locked while a task is active/in progress.":void 0,executionMode:Xt,onExecutionModeChange:mn,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:qt,onChange:J=>ke(J.target.value),disabled:Lt,"data-testid":"task-source-provider-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Repository (e.g. owner/repo)",value:$e,onChange:J=>Ye(J.target.value),disabled:Lt,"data-testid":"task-source-repository-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:ut,onChange:J=>We(J.target.value),disabled:Lt,"data-testid":"task-source-external-id-input"}),t.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:$t,onChange:J=>At(J.target.value),disabled:Lt,"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 J=e.title||e.description||e.id,Le=!V&&J.length>pd;return t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"detail-title",children:Le?J.slice(0,pd)+"…":J}),J.length>pd&&t.jsx("button",{className:"detail-description-toggle",onClick:()=>Y(!V),children:V?"Show less":"Show more"})]})})(),t.jsxs("div",{className:"detail-meta",children:[t.jsxs("label",{className:`card-priority-badge card-priority-badge--${nn} detail-priority-chip ${rn?"detail-priority-chip--saving":""}`,children:[t.jsx("span",{children:"Priority:"}),t.jsx("select",{className:"detail-priority-select",value:nn,onChange:J=>{Zn(J.target.value)},disabled:rn,"aria-label":"Task priority",children:da.map(J=>t.jsx("option",{value:J,children:J},J))})]}),t.jsxs("button",{type:"button",className:`btn btn-sm detail-execution-mode-toggle ${it==="fast"?"detail-execution-mode-toggle--fast":""} ${Rt?"detail-execution-mode-toggle--saving":""}`,onClick:()=>{On()},disabled:Rt,"aria-label":`Execution mode: ${it}`,"aria-pressed":it==="fast",children:[t.jsx(is,{"aria-hidden":"true"}),t.jsx("span",{children:it==="fast"?"Fast":"Standard"})]}),U&&t.jsxs("div",{className:"detail-provenance",children:[t.jsx(Ps,{"aria-hidden":"true"}),t.jsxs("span",{children:[j.sourceType==="agent_heartbeat"?t.jsxs(t.Fragment,{children:["Created by"," ",U.sourceAgentId?t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>L(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:()=>Oi(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(Ps,{"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",children:["Created ",new Date(e.createdAt).toLocaleDateString()," · Updated"," ",new Date(e.updatedAt).toLocaleDateString()]})]})]}),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})]})]}),!oe&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"detail-tabs",children:[t.jsx("button",{className:`detail-tab${b==="definition"?" detail-tab-active":""}`,onClick:()=>v("definition"),children:"Definition"}),t.jsx("button",{className:`detail-tab${b==="logs"?" detail-tab-active":""}`,onClick:()=>v("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:()=>v("changes"),children:"Changes"}),t.jsx("button",{className:`detail-tab${b==="review"?" detail-tab-active":""}`,onClick:()=>v("review"),children:"Review"}),t.jsx("button",{className:`detail-tab${b==="comments"?" detail-tab-active":""}`,onClick:()=>v("comments"),children:"Comments"}),t.jsx("button",{className:`detail-tab${b==="documents"?" detail-tab-active":""}`,onClick:()=>v("documents"),children:"Documents"}),t.jsx("button",{className:`detail-tab${b==="model"?" detail-tab-active":""}`,onClick:()=>v("model"),children:"Model"}),t.jsx("button",{className:`detail-tab${b==="workflow"?" detail-tab-active":""}`,onClick:()=>v("workflow"),children:"Workflow"}),t.jsx("button",{className:`detail-tab${b==="stats"?" detail-tab-active":""}`,onClick:()=>v("stats"),children:"Stats"}),t.jsx("button",{className:`detail-tab${b==="routing"?" detail-tab-active":""}`,onClick:()=>v("routing"),children:"Routing"}),_n.map(({entry:J,tabId:Le})=>t.jsx("button",{className:`detail-tab${b===Le?" detail-tab-active":""}`,onClick:()=>v(Le),children:J.slot.label},`plugin-tab-${J.pluginId}-${Le}`))]}),b==="workflow"?t.jsx("div",{className:"detail-section",children:t.jsx(OI,{taskId:e.id,results:Rn,loading:Xn,enabledWorkflowSteps:Gn,canEdit:En,projectId:n,isTaskInProgress:e.column==="in-progress"&&e.status!=="paused",onWorkflowStepsChange:$r})}):b==="model"?t.jsx("div",{className:"detail-section",children:t.jsx(fI,{task:e,addToast:h,onTaskUpdated:m,settings:hn})}):b==="logs"?t.jsxs("div",{className:`detail-section${C==="agent-log"?" detail-section--agent-log":""}`,children:[t.jsxs("div",{className:"log-subview-toggle",children:[t.jsx("button",{className:`log-subview-btn${C==="activity"?" log-subview-btn-active":""}`,onClick:()=>$("activity"),children:"Activity"}),t.jsx("button",{className:`log-subview-btn${C==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>$("agent-log"),children:"Agent Log"})]}),C==="agent-log"?t.jsx(dI,{entries:Hn,loading:ws,executorModel:QI(e,Hn,ce,hn),validatorModel:XI(e,Hn,ce,hn),planningModel:eT(e,Hn,hn),hasMore:es,onLoadMore:ns,loadingMore:Ds,totalCount:Bs}):t.jsxs("div",{className:"detail-activity",children:[t.jsx("h4",{children:"Activity"}),j.activityLogTruncatedCount?t.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",j.log.length," activity entries."]}):null,j.log&&j.log.length>0?t.jsx("div",{className:"detail-activity-list",children:[...j.log].reverse().map((J,Le)=>t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-timestamp",children:nT(J.timestamp)}),t.jsx("span",{className:"detail-log-action",children:J.action})]}),J.outcome&&t.jsx("div",{className:"detail-log-outcome",children:J.outcome})]},Le))}):t.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):b==="changes"?t.jsx(MI,{taskId:e.id,worktree:e.worktree,projectId:n,column:e.column,mergeDetails:e.mergeDetails,modifiedFiles:e.modifiedFiles}):b==="review"?t.jsx(NI,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):b==="comments"?t.jsx(yI,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):b==="documents"?t.jsx(WI,{taskId:e.id,addToast:h,projectId:n,onTaskUpdated:m,canEdit:En}):$n?t.jsx("div",{className:"detail-section",children:t.jsx(ia,{slotId:"task-detail-tab",projectId:n,pluginIds:[$n.entry.pluginId]})}):b==="stats"?t.jsx("div",{className:"detail-section",children:t.jsx(GI,{tokenUsage:j.tokenUsage,loading:E,task:j})}):b==="routing"?t.jsx("div",{className:"detail-section",children:t.jsx(UI,{task:e,settings:hn,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(wi,{remarkPlugins:[ki],children:e.summary})})]}),t.jsx(CI,{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(Ps,{"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":In,"aria-label":In?"Collapse source issue details":"Expand source issue details",onClick:()=>fe(J=>!J),children:t.jsx(zn,{size:16,className:In?"detail-source-chevron--expanded":void 0})})]}),In&&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)"})})]})]})]}),As&&t.jsxs("div",{className:"detail-section detail-github-tracking-section",children:[t.jsx("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(Ps,{"aria-hidden":"true"}),t.jsx("span",{children:Nn?"Linked":"Pending"})]}),!Nn&&t.jsx("span",{className:"detail-source-empty",children:"Not yet created"})]})}),Nn&&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:Nn.url?t.jsx("a",{className:"detail-source-link",href:Nn.url,target:"_blank",rel:"noopener noreferrer",children:`${Nn.owner}/${Nn.repo}#${Nn.number}`}):t.jsx("span",{children:`${Nn.owner}/${Nn.repo}#${Nn.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"})})]})]}),En&&t.jsxs("div",{className:"detail-github-tracking-controls",children:[t.jsxs("label",{className:"checkbox-label",htmlFor:"detail-github-tracking-toggle",children:[t.jsx("input",{id:"detail-github-tracking-toggle",type:"checkbox",checked:ps,disabled:_t,onChange:()=>void Q()}),"Enable GitHub tracking"]}),t.jsxs("div",{className:"detail-github-tracking-repo-row",children:[t.jsx("input",{className:"input",value:ft,onChange:J=>{lt(J.target.value),et(null)},placeholder:Cs||"owner/repo"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void M(),disabled:_t,children:"Save"})]}),vt&&t.jsx("small",{className:"detail-github-tracking-error",children:vt}),Nn&&t.jsx("button",{className:"btn btn-sm touch-target",onClick:()=>void Jn(),disabled:_t,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:[fn.length>0&&t.jsx("span",{className:"detail-provider-icons","data-testid":"detail-provider-icons",children:fn.map(J=>t.jsx(Tn,{provider:J,size:"sm"},J))}),t.jsxs("span",{className:"detail-meta-label",children:[t.jsx(Vn,{size:14,className:"detail-meta-label-icon"}),"Agent"]})]}),t.jsxs("div",{className:"detail-agent-actions",children:[Mt?t.jsxs("span",{className:"detail-agent-chip",children:[t.jsx(Vn,{size:14}),Mt,t.jsx("button",{className:"detail-agent-clear",onClick:()=>void ka(),title:"Unassign agent",children:t.jsx(an,{size:12})})]}):t.jsx("button",{className:"btn btn-sm",onClick:()=>{ee?le(!1):Dr()},children:"Assign Agent"}),ee&&t.jsxs("div",{className:"agent-picker-dropdown",children:[K&&t.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!K&&X.map(J=>t.jsxs("button",{className:`agent-picker-item${e.assignedAgentId===J.id?" selected":""}`,onClick:()=>void wa(J.id),children:[t.jsx(Vn,{size:14}),t.jsx("span",{className:"agent-picker-name",children:J.name}),t.jsx("span",{className:"agent-picker-role",children:J.role})]},J.id)),!K&&X.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"}),j.steps&&j.steps.length>0?t.jsxs("div",{className:"step-progress-wrapper",children:[t.jsx("div",{className:"step-progress-bar",children:j.steps.map((J,Le)=>t.jsx("div",{className:`step-progress-segment step-progress-segment--${J.status}`,"data-tooltip":`${J.name} (${J.status})`,style:{backgroundColor:tT(J.status)}},Le))}),t.jsxs("span",{className:"step-progress-label",children:[j.steps.filter(J=>J.status==="done").length,"/",j.steps.length," step",j.steps.length===1?"":"s"]})]}):t.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),t.jsxs("div",{className:"detail-section",children:[!ze&&t.jsx("div",{className:"detail-spec-edit-trigger",children:t.jsx("button",{className:"btn btn-sm",onClick:Na,children:"Edit"})}),ze?t.jsxs("div",{className:"spec-editor-edit-mode",children:[t.jsx("textarea",{className:"spec-editor-textarea",value:He,onChange:J=>Pe(J.target.value),onKeyDown:on,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:Ni,disabled:pe,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Qe(),disabled:He===(j.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:tt,onChange:J=>qe(J.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:[tt.length,"/2000"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Dt(),disabled:!tt.trim()||B,children:B?"Requesting…":"Request AI Revision"})]})]})]}):E?t.jsx("div",{className:"spec-loading",children:"Loading specification…"}):j.prompt?t.jsx("div",{className:"markdown-body",children:t.jsx(wi,{remarkPlugins:[ki],children:j.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(J=>{const Le=Ii(`/api/tasks/${e.id}/attachments/${J.filename}`);return t.jsxs("div",{className:"detail-attachment-card",children:[t.jsx("a",{className:"detail-attachment-link",href:Le,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{src:Le,alt:J.originalName,className:"detail-attachment-image"})}),t.jsxs("div",{className:"detail-attachment-meta",children:[J.originalName," (",sT(J.size),")"]}),t.jsx("button",{className:"detail-attachment-delete",onClick:()=>Tr(J.filename),title:"Delete attachment",children:"×"})]},J.filename)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no attachments)"}),t.jsx("input",{className:"detail-hidden-file-input",ref:rs,type:"file",accept:"image/*",onChange:Wa}),t.jsx("button",{className:"btn btn-sm",onClick:()=>rs.current?.click(),disabled:A,children:A?"Uploading…":"Attach Screenshot"})]}),t.jsxs("div",{className:"detail-deps",children:[t.jsx("h4",{children:"Dependencies"}),D.length>0?t.jsx("ul",{className:"detail-dep-list",children:D.map(J=>{const Le=s.find(Kt=>Kt.id===J),Ct=Le?.title||Le?.description||J;return t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>Oi(J),onKeyDown:Kt=>{(Kt.key==="Enter"||Kt.key===" ")&&(Kt.preventDefault(),Oi(J))},role:"link",tabIndex:0,title:`Click to view ${J}`,children:[t.jsx("span",{className:"detail-dep-id",children:J}),t.jsx("span",{className:"detail-dep-label",children:ud(Ct,40)})]}),t.jsx("button",{className:"dep-remove-btn",onClick:Kt=>Ka(Kt,J),title:`Remove dependency ${J}`,children:"×"})]},J)})}):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:()=>{G&&Ue(""),he(J=>!J)},children:"Add Dependency"}),G&&(()=>{const J=Se.toLowerCase(),Le=J?os.filter(Ct=>Ct.id.toLowerCase().includes(J)||Ct.title&&Ct.title.toLowerCase().includes(J)||Ct.description&&Ct.description.toLowerCase().includes(J)):os;return t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Se,onChange:Ct=>Ue(Ct.target.value),onClick:Ct=>Ct.stopPropagation()}),Le.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Le.map(Ct=>t.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{Li(Ct.id),he(!1)},children:[t.jsx("span",{className:"dep-dropdown-id",children:Ct.id}),t.jsx("span",{className:"dep-dropdown-title",children:ud(Ct.title||Ct.description||Ct.id,30)})]},Ct.id))]})})()]})]}),t.jsxs("div",{className:"detail-deps detail-blocking",children:[t.jsx("h4",{children:"Blocking"}),Je.length>0?t.jsx("ul",{className:"detail-dep-list",children:Je.map(J=>t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>Oi(J.id),onKeyDown:Le=>{(Le.key==="Enter"||Le.key===" ")&&(Le.preventDefault(),Oi(J.id))},role:"link",tabIndex:0,title:`Click to view ${J.id}`,children:[t.jsx("span",{className:"detail-dep-id",children:J.id}),t.jsx("span",{className:"detail-dep-label",children:ud(J.label,40)})]}),J.stale&&t.jsx("span",{className:"detail-blocking-item--stale",title:"Stale blockedBy edge: self-healing clearStaleBlockedBy should clear this automatically",children:"(stale)"})]},J.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(bI,{taskId:e.id,projectId:n,prInfo:e.prInfo,automationStatus:e.status??null,autoMerge:hn?.autoMerge??!1,isManualPrFlow:Ja,prAuthAvailable:f??!1,onPrCreated:J=>{e.prInfo=J},onPrUpdated:J=>{e.prInfo=J},addToast:h})})]})]})]}),t.jsx("div",{className:"modal-actions",children:oe?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"modal-edit-hint",children:z==="saving"?"Autosaving…":z==="saved"?"Saved":z==="error"?"Save failed":"Changes autosave as you edit"}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("button",{className:"btn btn-sm",onClick:Ee,disabled:Lt,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Mn(),disabled:Lt,children:Lt?"Saving…":"Save"})]}):t.jsxs(t.Fragment,{children:[e.column==="triage"&&e.status==="awaiting-approval"&&j.prompt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:fa,children:"Approve Plan"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:qa,children:"Reject Plan"})]}),e.column==="triage"&&e.status!=="awaiting-approval"&&!P&&t.jsx("button",{className:"btn btn-sm btn-danger",onClick:ha,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(e.column!=="triage"||e.status==="awaiting-approval"||P||e.paused)&&t.jsxs("div",{className:"detail-actions-dropdown",ref:gn,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{sn(J=>!J),mt(!1)},"aria-haspopup":"menu","aria-expanded":Pt,children:["Actions",t.jsx(un,{size:12})]}),Pt&&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:()=>ni(ha),children:"Delete"}),u&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ni(di),children:"Duplicate"}),(e.column==="done"||e.column==="in-review")&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ni(ga),children:"Refine"}),t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ni(Va),children:"Respecify"}),P&&c&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ni(Ha),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:()=>ni(ei),children:"Reset"}),e.column!=="done"&&!e.assignedAgentId&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ni(Di),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:ae,children:e.column==="in-review"?t.jsxs("div",{className:"detail-move-actions-in-review",children:[t.jsxs("div",{children:[t.jsxs("button",{ref:pt,className:"btn btn-primary btn-sm detail-move-btn",onClick:mi,onKeyDown:ls,disabled:!Ze,"aria-label":Ze?`Move to ${cs[Ze]}`:void 0,"aria-haspopup":ln?"menu":void 0,"aria-expanded":ln?Oe:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",Ze?cs[Ze]:""]}),ln&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(un,{size:12})})]}),Oe&&ln&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:Yn,children:Ft.map(J=>t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>ui(J),onKeyDown:Yn,children:J==="in-progress"?"Back to In Progress":`Move to ${cs[J]}`},J))})]}),hi?t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:hi}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:ba,children:Xi})]}):t.jsxs("div",{children:[t.jsxs("button",{ref:pt,className:"btn btn-primary btn-sm detail-move-btn",onClick:mi,onKeyDown:ls,disabled:!Ze,"aria-label":Ze?`Move to ${cs[Ze]}`:void 0,"aria-haspopup":ln?"menu":void 0,"aria-expanded":ln?Oe:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",Ze?cs[Ze]:""]}),ln&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(un,{size:12})})]}),Oe&&ln&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:Yn,children:Ft.map(J=>t.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>ui(J),onKeyDown:Yn,children:["Move to ",cs[J]]},J))})]})})]})}),de&&t.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:xa,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal detail-refine-modal",onClick:J=>J.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:xa,"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:Te,onChange:J=>ct(J.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:[Te.length,"/2000 characters"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:va,disabled:!Te.trim()||Ve,children:Ve?"Creating...":"Create Refinement Task"})]})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:xa,disabled:Ve,children:"Cancel"})})]})}),R&&t.jsx(i.Suspense,{fallback:null,children:t.jsx(oT,{agentId:R,projectId:n,onClose:()=>L(null),addToast:h})})]})}function dT({onClose:e,...n}){const s=i.useRef(null);Ti(s,!0,"task-detail-modal-size"),ji(!0);const a=Gi(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(Qx,{...n,onRequestClose:e})})})}const rl={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},Fp=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function Bp(e){return e==="merging-fix"?"Merging fixes…":e}const Xx=["title","status","column","dependencies","progress"],uT=["title","status","column"];function mT(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function hT(e){return e==="online"?"●":e==="connecting"?"◐":e==="error"?"✕":"○"}function Up(e){try{const n=Fn("kb-dashboard-list-columns",e);if(n){const a=JSON.parse(n).filter(r=>Xx.includes(r));if(a.length>0)return new Set(a)}}catch{}return new Set(uT)}function Hp(e){try{const n=Fn("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function qp(e){try{const n=Fn("kb-dashboard-list-collapsed",e);if(n){const a=JSON.parse(n).filter(r=>sa.includes(r));if(a.length>0)return new Set(a)}}catch{}return new Set}function Vp(e){try{const n=Fn("kb-dashboard-selected-tasks",e);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function Wp(e){try{const n=Fn("kb-dashboard-list-selected-task",e);if(typeof n=="string"&&n.trim().length>0)return n}catch{}return null}function Kp(e){try{const s=Fn("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 ql=280,hu=.65,ol=16;function pu(e){return Math.max(ql,e*hu)}function ll(e,n){const s=pu(n);return Math.min(Math.max(e,ql),s)}function pT(e){return e.status==="executing"||e.column==="in-progress"}function Gp(e){const n=jb(e);return n.total===0||!pT(e)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function fT({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:v,onTasksUpdated:N,projectId:k,projectName:E,taskStuckTimeoutMs:y,searchQuery:j="",lastFetchTimeMs:P,prAuthAvailable:F}){const[_,R]=i.useState(null),[L,U]=i.useState("asc"),[C,$]=i.useState(null),[V,Y]=i.useState(null),[ne,q]=i.useState(null),I=Zs()==="mobile",{confirm:D}=ci(),[S,G]=i.useState(()=>Up(k)),[he,Se]=i.useState(()=>Hp(k)),[Ue,ce]=i.useState(()=>qp(k));i.useEffect(()=>{typeof window<"u"&&ds("kb-dashboard-list-columns",JSON.stringify([...S]),k)},[k,S]),i.useEffect(()=>{typeof window<"u"&&ds("kb-dashboard-hide-done",he.toString(),k)},[he,k]),i.useEffect(()=>{typeof window<"u"&&ds("kb-dashboard-list-collapsed",JSON.stringify([...Ue]),k)},[Ue,k]);const[Ae,X]=i.useState(!1),[Z,ee]=i.useState(!1),[le,K]=i.useState(()=>Vp(k)),[O,pe]=i.useState(()=>Wp(k)),[ve,B]=i.useState(null),[we,ze]=i.useState(()=>Kp(k)),re=i.useRef(null),He=i.useRef(null);i.useEffect(()=>{G(Up(k)),Se(Hp(k)),ce(qp(k)),K(Vp(k));const ke=Wp(k);pe(ke),B(ke?e.find($e=>$e.id===ke)??null:null),ze(Kp(k))},[k,e]),i.useEffect(()=>{typeof window<"u"&&ds("kb-dashboard-selected-tasks",JSON.stringify([...le]),k)},[k,le]),i.useEffect(()=>{if(!(typeof window>"u")){if(O){ds("kb-dashboard-list-selected-task",O,k);return}vr("kb-dashboard-list-selected-task",k)}},[k,O]),i.useEffect(()=>{if(!O){B(null);return}const ke=e.find($e=>$e.id===O);ke&&B($e=>!$e||$e.id!==O?ke:{...$e,...ke})},[O,e]),i.useEffect(()=>{if(I||typeof ResizeObserver>"u")return;const ke=re.current;if(!ke)return;const $e=()=>{const ut=ll(we,ke.clientWidth);ut!==we&&ze(ut)};$e();const Ye=new ResizeObserver($e);return Ye.observe(ke),()=>Ye.disconnect()},[I,we]),i.useEffect(()=>{if(I||typeof ResizeObserver>"u")return;const ke=He.current,$e=re.current;if(!ke||!$e)return;let Ye=null,ut=ke.offsetWidth;const We=new ResizeObserver(()=>{const $t=ll(ke.offsetWidth,$e.clientWidth);$t!==ut&&(ut=$t,Ye&&clearTimeout(Ye),Ye=setTimeout(()=>{try{ds("kb-dashboard-list-sidebar-width",String($t),k)}catch{}},200))});return We.observe(ke),()=>{We.disconnect(),Ye&&clearTimeout(Ye)}},[I,k]);const Pe=i.useCallback(()=>{ee(ke=>(ke&&K(new Set),!ke))},[]),tt=i.useCallback(ke=>{K($e=>{const Ye=new Set($e);return Ye.has(ke)?Ye.delete(ke):Ye.add(ke),Ye})},[]),qe=i.useCallback(()=>{K(new Set)},[]),de=i.useCallback(ke=>{G($e=>{const Ye=new Set($e);return Ye.has(ke)?Ye.size>1&&Ye.delete(ke):Ye.add(ke),Ye})},[]),De={title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},Te=i.useCallback(ke=>{if(_===ke){U($e=>$e==="asc"?"desc":"asc");return}R(ke),U("asc")},[_]),ct=i.useCallback(ke=>{q($e=>$e===ke?null:ke)},[]),Ve=i.useCallback(ke=>{ce($e=>{const Ye=new Set($e);return Ye.has(ke)?Ye.delete(ke):Ye.add(ke),Ye})},[]),me=i.useCallback(()=>{q(null)},[]),oe=i.useMemo(()=>{let ke=j?e.filter(ut=>ut.id.toLowerCase().includes(j.toLowerCase())||ut.title&&ut.title.toLowerCase().includes(j.toLowerCase())||ut.description.toLowerCase().includes(j.toLowerCase())):[...e];he&&!ne&&(ke=ke.filter(ut=>ut.column!=="done"&&ut.column!=="archived"));const $e=ne?ke.filter(ut=>ut.column===ne):ke,Ye={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};$e.forEach(ut=>{const We=Du(ut.column)?ut.column:Ll;Ye[We].push(ut)});for(const ut of sa){if(!_){Ye[ut]=xb(Ye[ut],ut);continue}Ye[ut]=[...Ye[ut]].sort((We,$t)=>{let At=0;switch(_){case"title":At=(We.title||We.description).localeCompare($t.title||$t.description);break;case"status":At=(We.status||"").localeCompare($t.status||"");break;case"column":At=We.column.localeCompare($t.column);break}return L==="asc"?At:-At})}return Ye},[e,j,_,L,he,ne]),Me=i.useMemo(()=>Object.values(oe).reduce((ke,$e)=>ke+$e.length,0),[oe]),Xe=i.useMemo(()=>e.filter(ke=>ke.column==="done"||ke.column==="archived").length,[e]),rt=i.useMemo(()=>he?Xe:0,[he,Xe]),ht=i.useCallback(()=>{const ke=Object.values(oe).flat().filter($e=>$e.column!=="archived").map($e=>$e.id);K($e=>{if(ke.every(ut=>$e.has(ut))){const ut=new Set($e);return ke.forEach(We=>ut.delete(We)),ut}else return new Set([...$e,...ke])})},[oe]),yt=i.useMemo(()=>{const ke=Object.values(oe).flat().filter($e=>$e.column!=="archived");return ke.length===0?!1:ke.every($e=>le.has($e.id))},[oe,le]),Re=i.useMemo(()=>{const ke=Object.values(oe).flat().filter(Ye=>Ye.column!=="archived");if(ke.length===0)return!1;const $e=ke.filter(Ye=>le.has(Ye.id)).length;return $e>0&&$e<ke.length},[oe,le]),[Ge,at]=i.useState("__no_change__"),[ie,Ke]=i.useState("__no_change__"),[je,Fe]=i.useState("__no_change__"),[Be,St]=i.useState([]),[ye,kt]=i.useState(!1),It=i.useMemo(()=>je&&je!=="__no_change__"?Be.find(ke=>ke.id===je):void 0,[Be,je]),[Ie,be]=i.useState(!1);i.useEffect(()=>{if(le.size===0)return;let ke=!1;return(async()=>{kt(!0);try{const Ye=await $l();ke||St(Ye)}catch(Ye){console.error("Failed to fetch nodes for bulk edit",Ye),ke||St([])}finally{ke||kt(!1)}})(),()=>{ke=!0}},[le.size]);const ot=i.useCallback(async()=>{if(le.size===0)return;const ke=Array.from(le).map(wt=>e.find(zt=>zt.id===wt)).filter(wt=>!!wt),$e=ke.filter(wt=>wt.column==="archived"),Ye=ke.filter(wt=>wt.column!=="archived");if(Ye.length===0){d("No selected tasks can be deleted (archived tasks are excluded)","error");return}if(!await D({title:"Delete Selected Tasks",message:`Delete ${Ye.length} selected task${Ye.length===1?"":"s"}?`,confirmLabel:"Delete",cancelLabel:"Cancel",danger:!0}))return;be(!0);const We=[],$t=[],At=$e.map(wt=>wt.id);try{for(const wt of Ye)try{await a(wt.id),We.push(wt.id)}catch(zt){const Lt=Lu(zt);if(!Lt){$t.push(wt.id);continue}if(!await D({title:"Force Delete Task",message:`Task ${wt.id} has dependents: ${Lt.dependentIds.join(", ")}. Remove dependency references and force delete?`,confirmLabel:"Force Delete",cancelLabel:"Skip",danger:!0})){$t.push(wt.id);continue}try{await a(wt.id,{removeDependencyReferences:!0}),We.push(wt.id)}catch{$t.push(wt.id)}}}finally{be(!1)}We.length>0&&K(wt=>{const zt=new Set(wt);for(const Lt of We)zt.delete(Lt);return zt}),d(`Deleted ${We.length} task${We.length===1?"":"s"} · ${At.length} archived skipped · ${$t.length} failed`,$t.length>0?"error":"success")},[d,D,a,le,e]),gt=i.useCallback(async()=>{if(le.size===0)return;const ke=Array.from(le).filter(Ye=>{const ut=e.find(We=>We.id===Ye);return ut&&ut.column!=="archived"});if(ke.length===0){d("No valid tasks to update (archived tasks cannot be modified)","error");return}const $e={taskIds:ke};if(Ge!=="__no_change__")if(Ge==="")$e.modelProvider=null,$e.modelId=null;else{const Ye=Ge.indexOf("/");Ye!==-1&&($e.modelProvider=Ge.slice(0,Ye),$e.modelId=Ge.slice(Ye+1))}if(ie!=="__no_change__")if(ie==="")$e.validatorModelProvider=null,$e.validatorModelId=null;else{const Ye=ie.indexOf("/");Ye!==-1&&($e.validatorModelProvider=ie.slice(0,Ye),$e.validatorModelId=ie.slice(Ye+1))}if(je!=="__no_change__"&&(je===""?$e.nodeId=null:$e.nodeId=je),Object.keys($e).length===1){d("No changes to apply","info");return}be(!0);try{const Ye=await gj($e.taskIds,$e.modelProvider,$e.modelId,$e.validatorModelProvider,$e.validatorModelId,void 0,void 0,$e.nodeId,k);N&&N(Ye.updated),d(`Updated ${ke.length} task${ke.length===1?"":"s"}`,"success"),qe(),at("__no_change__"),Ke("__no_change__"),Fe("__no_change__")}catch(Ye){d(Ce(Ye)||"Failed to update models","error")}finally{be(!1)}},[le,e,Ge,ie,je,k,d,qe,N]),xt=i.useCallback(ke=>{if(I){c(ke,{origin:"list-mobile"});return}pe(ke.id),B(ke)},[I,c]),jt=i.useRef(null),Bt=i.useRef(null);i.useEffect(()=>()=>{jt.current&&clearTimeout(jt.current)},[]);const Jt=i.useCallback(ke=>{if(pe(ke.id),B(ke),"prompt"in ke){Bt.current=null,jt.current&&(clearTimeout(jt.current),jt.current=null);return}Bt.current=ke.id,jt.current&&clearTimeout(jt.current),jt.current=setTimeout(()=>{jt.current=null,Bt.current===ke.id&&$a(ke.id,k).then(Ye=>{Bt.current===Ye.id&&B(ut=>!ut||ut.id!==Ye.id?ut:{...ut,...Ye})}).catch(()=>{})},200)},[k]),Vt=i.useCallback((ke,$e)=>{if($e.paused){ke.preventDefault();return}ke.dataTransfer.setData("text/plain",$e.id),ke.dataTransfer.effectAllowed="move",$($e.id)},[]),pn=i.useCallback(()=>{$(null),Y(null)},[]),Xt=i.useCallback(ke=>{if(I)return;ke.preventDefault();const $e=re.current;if(!$e)return;const Ye=$e.getBoundingClientRect(),ut=$t=>{const At=$t.clientX-Ye.left;ze(ll(At,Ye.width))},We=()=>{window.removeEventListener("mousemove",ut),window.removeEventListener("mouseup",We)};window.addEventListener("mousemove",ut),window.addEventListener("mouseup",We)},[I]),mn=i.useCallback(ke=>{if(I)return;const $e=re.current?.clientWidth??0,Ye=we/hu+ol,ut=Math.max($e,Ye),We=pu(ut);if(ke.key==="ArrowLeft"||ke.key==="ArrowRight"){ke.preventDefault();const $t=ke.key==="ArrowLeft"?-ol:ol;ze(At=>ll(At+$t,ut));return}if(ke.key==="Home"){ke.preventDefault(),ze(ql);return}ke.key==="End"&&(ke.preventDefault(),ze(We))},[I,we]),Ht=i.useCallback((ke,$e)=>{ke.preventDefault(),ke.dataTransfer.dropEffect="move",Y($e)},[]),Zt=i.useCallback(()=>{Y(null)},[]),tn=i.useCallback(async(ke,$e)=>{ke.preventDefault(),Y(null);const Ye=ke.dataTransfer.getData("text/plain");if(Ye){if($e==="archived"){d("Tasks can only be archived via the archive button","error");return}try{const We=e.find(wt=>wt.id===Ye)?.steps.some(wt=>wt.status!=="pending")??!1,$t=($e==="todo"||$e==="triage")&&We;let At;if($t){if(await D({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))At={preserveProgress:!0};else if(!await D({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await n(Ye,$e,At)}catch(ut){d(Ce(ut),"error")}}},[n,d,e,D]),dn=ke=>!_||_!==ke?t.jsx(Rg,{size:14,className:"sort-icon"}):L==="asc"?t.jsx(Ra,{size:14,className:"sort-icon active"}):t.jsx(Co,{size:14,className:"sort-icon active"}),qt=ke=>t.jsxs("div",{id:ke,className:"list-view-options-panel",children:[t.jsx("div",{className:"list-view-options-columns",children:Xx.map($e=>{const Ye=S.has($e),ut=Ye&&S.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${ut?" disabled":""}`,title:ut?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:Ye,onChange:()=>de($e),disabled:ut}),t.jsx("span",{children:De[$e]})]},$e)})}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>Se($e=>!$e),"aria-pressed":he,title:he?"Show done tasks":"Hide done tasks",children:[he?t.jsx(Er,{size:14}):t.jsx(Su,{size:14}),he?"Show Done":"Hide Done"]}),t.jsx("div",{className:"list-drop-zones list-drop-zones--sidebar",children:sa.map($e=>{const Ye=e.filter(At=>At.column===$e).length,ut=$e==="done"||$e==="archived",We=he&&ut?0:Ye,$t=he&&ut&&Ye>0;return t.jsxs("div",{className:`list-drop-zone${V===$e?" drag-over":""}${ne===$e?" active":""}`,onClick:()=>ct($e),onDragOver:At=>Ht(At,$e),onDragLeave:Zt,onDrop:At=>tn(At,$e),"data-column":$e,children:[t.jsx("span",{className:`list-section-dot dot-${$e}`}),t.jsx("span",{className:"drop-zone-label",children:cs[$e]}),t.jsx("span",{className:"drop-zone-count",children:$t?`${We} of ${Ye}`:Ye})]},$e)})})]});return t.jsxs("div",{className:"list-view",children:[I&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"list-toolbar",children:[t.jsx("button",{className:"btn btn-sm",onClick:Pe,"aria-pressed":Z,children:Z?"Done Editing":"Bulk Edit"}),t.jsxs("button",{className:"btn btn-sm list-view-options-toggle",onClick:()=>X(ke=>!ke),"aria-expanded":Ae,"aria-controls":"list-view-options-panel-mobile",children:[t.jsx(gm,{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?`${Me} of ${e.length} tasks in ${cs[ne]}`:`${Me} of ${e.length} tasks`})]}),Ae?t.jsx("div",{className:"list-toolbar-mobile-options",children:qt("list-view-options-panel-mobile")}):null]}),t.jsx("div",{className:"list-table-container",children:t.jsxs("div",{className:I?"":"list-split-layout","data-testid":I?void 0:"list-split-layout",ref:re,children:[t.jsxs("div",{className:I?"":"list-split-sidebar","data-testid":I?void 0:"list-split-sidebar",ref:He,style:I?void 0:{width:`${we}px`},children:[!I&&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?`${Me} of ${e.length} tasks in ${cs[ne]}`:`${Me} of ${e.length} tasks`,rt>0&&!ne&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",rt," hidden)"]})]}),t.jsxs("div",{className:"list-sidebar-controls__actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Pe,"aria-pressed":Z,children:Z?"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: ${cs[ne]}`}):null,he?t.jsx("span",{className:"list-sidebar-chip",children:"Done hidden"}):null,Z?t.jsx("span",{className:"list-sidebar-chip",children:"Bulk edit"}):null,Z&&le.size>0?t.jsx("button",{className:"btn btn-sm",onClick:qe,children:`${le.size} selected`}):null]})]}),t.jsxs("button",{className:"btn btn-sm list-view-options-toggle",onClick:()=>X(ke=>!ke),"aria-expanded":Ae,"aria-controls":"list-view-options-panel",children:[t.jsx(gm,{size:14}),"View options"]}),Ae&&qt("list-view-options-panel"),Z&&le.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:ot,disabled:Ie,children:[t.jsx(Sn,{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(Ns,{models:f,value:Ge,onChange:at,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(Ns,{models:f,value:ie,onChange:Ke,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:je,onChange:ke=>Fe(ke.target.value),"aria-label":"Node Override",disabled:ye,children:[t.jsx("option",{value:"__no_change__",children:"No change"}),t.jsx("option",{value:"",children:"Use project default"}),Be.map(ke=>t.jsx("option",{value:ke.id,children:`${hT(ke.status)} ${ke.name||ke.id} (${mT(ke.status)})`},ke.id))]}),It?t.jsx(Da,{status:It.status,showLabel:!0}):null]}),t.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:gt,disabled:Ie||Ge==="__no_change__"&&ie==="__no_change__"&&je==="__no_change__",children:Ie?"Applying...":"Apply"})]}):null]}):null]}),t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx(Rb,{onCreate:h??(async()=>d("Task creation not available","error")),addToast:d,tasks:e,availableModels:f,onPlanningMode:b,onSubtaskBreakdown:v,projectId:k,autoExpand:!1,favoriteProviders:p,favoriteModels:g,onToggleFavorite:x,onToggleModelFavorite:w})}),Me===0?t.jsx("div",{className:"list-empty",children:j?"No tasks match your filter":"No tasks yet"}):I?t.jsx("div",{className:"list-cards",children:sa.map(ke=>{if(ne&&ke!==ne||he&&(ke==="done"||ke==="archived")&&!ne)return null;const $e=oe[ke],Ye=$e.length===0;if(j&&Ye)return null;const ut=Ue.has(ke);return t.jsxs(i.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${ut?" list-section-header--collapsed":""}`,onClick:()=>Ve(ke),"aria-expanded":!ut,role:"button",tabIndex:0,onKeyDown:We=>{(We.key==="Enter"||We.key===" ")&&(We.preventDefault(),Ve(ke))},children:[t.jsx(zn,{size:14,className:`list-section-chevron${ut?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${ke}`}),t.jsx("span",{className:"list-section-title",children:cs[ke]}),t.jsx("span",{className:"list-section-count",children:$e.length})]}),!ut&&t.jsx(t.Fragment,{children:Ye?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):$e.map(We=>{const $t=We.status==="failed",At=We.paused===!0,wt=zl(We,y,P),zt=!u&&!$t&&!At&&!wt&&(We.column==="in-progress"||Fp.has(We.status)),Lt=typeof We.status=="string"&&We.status.trim().length>0,Ot=!!(We.dependencies&&We.dependencies.length>0),nn=Gp(We),Yt=nn.hasProgress,rn=Z;return t.jsxs("div",{className:`list-card${zt?" agent-active":""}${rn?" list-card--selectable":""}`,onClick:()=>xt(We),"data-id":We.id,children:[rn&&t.jsx("label",{className:"list-card-checkbox",onClick:_e=>_e.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:le.has(We.id),onChange:_e=>{_e.stopPropagation(),tt(We.id)},onClick:_e=>_e.stopPropagation(),disabled:We.column==="archived","aria-label":`Select ${We.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:We.id}),We.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(is,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),t.jsx("span",{className:"list-card-spacer"}),At&&We.pausedByAgentId?t.jsx("span",{className:"list-status-badge paused",children:"paused by agent"}):wt?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):Lt?t.jsx("span",{className:`list-status-badge list-status-badge--${We.column}${$t?" failed":""}${zt?" pulsing":""}`,children:Bp(We.status??"")}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:We.title||We.description})}),(Ot||Yt)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[Ot&&t.jsxs("span",{className:"list-dep-badge",title:We.dependencies.join(", "),children:[t.jsx(pr,{size:12})," ",We.dependencies.length]}),Yt&&t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${nn.percent}%`,backgroundColor:rl[We.column]}})}),t.jsx("span",{className:"list-progress-label",children:nn.label})]})]})]},We.id)})})]},ke)})}):t.jsxs("table",{className:"list-table",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[Z&&t.jsx("th",{className:"list-header-cell list-header-checkbox",children:t.jsx("input",{type:"checkbox",checked:yt,ref:ke=>{ke&&(ke.indeterminate=Re)},onChange:ht,"aria-label":"Select all visible tasks"})}),S.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Te("title"),children:["Title ",dn("title")]}),S.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Te("status"),children:["Status ",dn("status")]}),S.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Te("column"),children:["Column ",dn("column")]}),S.has("dependencies")&&t.jsx("th",{className:"list-header-cell",children:"Dependencies"}),S.has("progress")&&t.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),t.jsx("tbody",{children:sa.map(ke=>{if(ne&&ke!==ne||he&&(ke==="done"||ke==="archived")&&!ne)return null;const $e=oe[ke],Ye=$e.length===0;if(j&&Ye)return null;const ut=Ue.has(ke);return t.jsxs(i.Fragment,{children:[t.jsx("tr",{className:`list-section-header${ut?" list-section-header--collapsed":""}`,onClick:()=>Ve(ke),"aria-expanded":!ut,children:t.jsxs("th",{colSpan:S.size+(Z?1:0),className:"list-section-cell",children:[t.jsx(zn,{size:14,className:`list-section-chevron${ut?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${ke}`}),t.jsx("span",{className:"list-section-title",children:cs[ke]}),t.jsx("span",{className:"list-section-count",children:$e.length})]})}),!ut&&t.jsx(t.Fragment,{children:Ye?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:S.size+(Z?1:0),className:"list-empty-cell",children:"No tasks"})}):$e.map(We=>{const $t=We.status==="failed",At=We.paused===!0,wt=zl(We,y,P),zt=!u&&!$t&&!At&&!wt&&(We.column==="in-progress"||Fp.has(We.status)),Lt=C===We.id;return t.jsxs("tr",{className:`list-row${$t?" failed":""}${At?" paused":""}${wt?" stuck":""}${zt?" agent-active":""}${Lt?" dragging":""}${O===We.id?" list-row--selected":""}`,onClick:()=>xt(We),draggable:!At,onDragStart:Ot=>Vt(Ot,We),onDragEnd:pn,"data-id":We.id,children:[Z&&t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:le.has(We.id),onChange:Ot=>{Ot.stopPropagation(),tt(We.id)},onClick:Ot=>Ot.stopPropagation(),disabled:We.column==="archived","aria-label":`Select ${We.id}`})}),S.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:We.id}),t.jsxs("div",{className:"list-title-row",children:[We.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(is,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),t.jsx("span",{className:"list-title-text",children:We.title||We.description})]})]})}),S.has("status")&&t.jsx("td",{className:"list-cell",children:At&&We.pausedByAgentId?t.jsx("span",{className:"list-status-badge paused",children:"paused by agent"}):wt?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):We.status?t.jsx("span",{className:`list-status-badge list-status-badge--${We.column}${$t?" failed":""}${zt?" pulsing":""}`,children:Bp(We.status??"")}):t.jsx("span",{className:"list-status-badge",children:"-"})}),S.has("column")&&t.jsx("td",{className:"list-cell",children:t.jsx("span",{className:"list-column-badge",style:{background:`${rl[We.column]}20`,color:rl[We.column]},children:cs[We.column]})}),S.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:We.dependencies&&We.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:We.dependencies.join(", "),children:[t.jsx(pr,{size:12})," ",We.dependencies.length]}):"-"}),S.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const Ot=Gp(We);return Ot.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:`${Ot.percent}%`,backgroundColor:rl[We.column]}})}),t.jsx("span",{className:"list-progress-label",children:Ot.label})]}):"-"})()})]},We.id)})})]},ke)})})]})]}),!I&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"list-split-resize-handle","data-testid":"list-split-resize-handle",onMouseDown:Xt,onKeyDown:mn,role:"separator",tabIndex:0,"aria-orientation":"vertical","aria-label":"Resize task list sidebar","aria-valuemin":ql,"aria-valuemax":Math.round(pu(re.current?.clientWidth??we/hu+ol)),"aria-valuenow":Math.round(we)}),t.jsx("div",{className:"list-split-detail","data-testid":"list-split-detail",children:ve?t.jsx("div",{className:"list-split-detail-content","data-testid":"list-split-detail-content",children:t.jsx(Qx,{task:ve,projectId:k,tasks:e,embedded:!0,onOpenDetail:Jt,onMoveTask:n,onDeleteTask:a,onMergeTask:r,onRetryTask:s,onResetTask:o,onDuplicateTask:l,onTaskUpdated:ke=>{B($e=>!$e||$e.id!==ke.id?$e:{...$e,...ke})},addToast:d,prAuthAvailable:F})}):t.jsx("div",{className:"list-split-detail-empty",children:t.jsx("p",{children:"Select a task to view details"})})})]})]})})]})}const gT={active:{label:"Active",color:"var(--color-success)",icon:ss},paused:{label:"Paused",color:"var(--color-warning)",icon:xi},errored:{label:"Error",color:"var(--color-error)",icon:Ts},initializing:{label:"Initializing",color:"var(--color-warning)",icon:Nt}};function bT(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 Jp(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 xT(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 vT({project:e,health:n,onSelect:s,onPause:a,onResume:r,onRemove:o,availabilityMappings:l=[],isLoading:c=!1}){const[d,u]=i.useState(!1),m=gT[e.status],h=m.icon,f=i.useCallback(()=>{s(e)},[s,e]),p=i.useCallback(N=>{N.stopPropagation(),a(e)},[a,e]),g=i.useCallback(N=>{N.stopPropagation(),r(e)},[r,e]),x=i.useCallback(N=>{if(N.stopPropagation(),!d){u(!0);return}o(e),u(!1)},[d,o,e]),w=e.status==="paused",b=e.status==="errored",v=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:N=>{(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),f())},children:[t.jsxs("div",{className:"project-card-header",children:[t.jsx("div",{className:"project-card-icon",children:t.jsx(ys,{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(N=>t.jsxs("div",{className:"project-card-availability__row",title:`${N.displayName} → ${N.path}`,children:[t.jsx("span",{className:"project-card-availability__node",children:N.displayName}),t.jsx("span",{className:"project-card-availability__arrow",children:"→"}),t.jsx("code",{className:"project-card-availability__path",children:Jp(N.path,28)})]},`${N.nodeId}-${N.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:Jp(e.path)})]}),t.jsxs("div",{className:"project-card-status-badge",style:{color:m.color,borderColor:m.color},children:[t.jsx(h,{size:12,className:v?"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:bT(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(ss,{size:14}),t.jsx("span",{children:"Resume"})]}):t.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:p,disabled:c||v,title:v?"Cannot pause while initializing":"Pause project","aria-label":"Pause project",children:[t.jsx(xi,{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(Eo,{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(Sn,{size:14}),t.jsx("span",{children:d?"Confirm":""})]})]})]})]})}const yT=i.memo(vT,xT);function Yp(e){return typeof e=="string"&&e.trim().length>0}function ao(e){return(e.nodeMappings??[]).filter(s=>Yp(s.nodeId)&&Yp(s.path)).map(s=>({nodeId:s.nodeId,nodeName:s.nodeName,path:s.path,available:s.available!==!1}))}function wT(e,n){return ao(e).filter(s=>s.nodeId===n.id&&s.available)}function kT(e,n){return wT(e,n).length>0}function jT(e,n){return e.filter(s=>kT(s,n))}function A5(e,n){return jT(e,n).length}function Qp(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 NT(){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(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(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(Wn,{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(Ts,{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 ST=1e4,Xp=5;function CT(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+=Xp){const x=e.slice(g,g+Xp),w=await Promise.allSettled(x.map(async b=>{try{return await Um(b)}catch{return null}}));if(x.forEach((b,v)=>{const N=w[v];p[b]=N.status==="fulfilled"?N.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 Um(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()},ST),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[m,e.length]),{healthMap:n,loading:a,error:o,refresh:m,refreshProject:h}}function ET({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 C=JSON.parse(U);b(C)}catch{}},[]);const[w,b]=i.useState([]),v=i.useMemo(()=>e.map(U=>U.id),[e]),{healthMap:N,loading:k}=CT(v),E=i.useMemo(()=>e.map(U=>({project:U,health:N[U.id]||null})),[e,N]),y=i.useMemo(()=>{let U=[...E];return d!=="all"&&(U=U.filter(({project:C})=>C.status===d)),m!==null&&(U=U.filter(({project:C})=>ao(C).some($=>$.available&&$.nodeId===m))),U},[E,d,m]),j=i.useMemo(()=>{const U=[...y];return U.sort((C,$)=>{let V=0;switch(f){case"name":V=C.project.name.localeCompare($.project.name);break;case"activity":{const Y=C.project.lastActivityAt||C.health?.lastActivityAt||C.project.updatedAt,ne=$.project.lastActivityAt||$.health?.lastActivityAt||$.project.updatedAt;V=new Date(ne).getTime()-new Date(Y).getTime();break}case"status":{const Y={errored:0,initializing:1,paused:2,active:3};V=Y[C.project.status]-Y[$.project.status];break}}return g==="asc"?V:-V}),U},[y,f,g]),P=i.useMemo(()=>{const U=e.length,C=e.filter(I=>I.status==="active").length,$=e.filter(I=>I.status==="errored").length,V=new Set;e.forEach(I=>{ao(I).forEach(D=>{D.available&&V.add(D.nodeId)})});const Y=V.size;let ne=0,q=0,A=0;return Object.values(N).forEach(I=>{I&&(ne+=I.activeTaskCount,q+=I.totalTasksCompleted,A+=I.inFlightAgentCount)}),{totalProjects:U,activeProjects:C,erroredProjects:$,totalNodes:Y,totalActiveTasks:ne,totalCompletedTasks:q,totalInFlightAgents:A}},[e,N]),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(C=>{ao(C).filter($=>$.available).forEach($=>{const V=$.nodeId,Y=U.get(V),ne=Qp(V,$,c,C);Y?Y.count+=1:U.set(V,{name:ne,count:1})})}),Array.from(U.entries()).map(([C,{name:$,count:V}])=>({nodeId:C,name:$,count:V}))},[e,c]),R=i.useCallback(U=>{const C=[U.id,...w.filter($=>$!==U.id)].slice(0,3);b(C),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify(C)),s(U)},[s,w]);return n||k&&e.length>0&&Object.keys(N).length===0?t.jsx(NT,{}):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(Ma,{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(Cn,{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(la,{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(ys,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:P.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:P.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(Wn,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:P.totalCompletedTasks}),t.jsx("span",{className:"project-stat__label",children:"Completed"})]})]}),P.erroredProjects>0&&t.jsxs("div",{className:"project-stat project-stat--error",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Ts,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:P.erroredProjects}),t.jsx("span",{className:"project-stat__label",children:"Errored"})]})]}),P.totalNodes>1&&t.jsxs("div",{className:"project-stat project-stat--nodes",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(bo,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:P.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(Cn,{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(bo,{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:C,count:$})=>t.jsxs("option",{value:U??"",children:[C," (",$,")"]},U??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(Al,{size:14}),t.jsxs("select",{value:`${f}-${g}`,onChange:U=>{const[C,$]=U.target.value.split("-");p(C),x($)},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(Rg,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:j.map(({project:U,health:C})=>{const $=ao(U).filter(V=>V.available).map(V=>({...V,displayName:Qp(V.nodeId,V,c,U)}));return t.jsx(yT,{project:U,health:C,availabilityMappings:$,onSelect:R,onPause:r,onResume:o,onRemove:l},U.id)})}),j.length===0&&t.jsxs("div",{className:"project-overview__no-results",children:[t.jsx(Al,{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 rm="kb-planning-last-description",om="kb-subtask-last-description",lm="kb-mission-last-goal";function _T(e,n){ds(rm,e,n)}function MT(e){return Fn(rm,e)||""}function sr(e){vr(rm,e)}function AT(e,n){ds(om,e,n)}function RT(e){return Fn(om,e)||""}function fd(e){vr(om,e)}function PT(e,n){ds(lm,e,n)}function IT(e){return Fn(lm,e)||""}function ea(e){vr(lm,e)}function TT(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 $T(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 DT(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 oi({entries:e,defaultShowThinking:n=!1}){const[s,a]=i.useState({}),r=DT(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?TT(o):void 0,h=o.question&&m!==void 0?$T(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 Zp="fusion-tab-id";function LT(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Ua(){if(typeof window>"u")return"server-tab";const e=window.sessionStorage.getItem(Zp);if(e)return e;const n=LT();return window.sessionStorage.setItem(Zp,n),n}function xc(e){const n=i.useMemo(()=>Ua(),[]),[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(Z1(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=e0(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=Ii(`/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:li("/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(t0(e,n)),a(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:d,isLoading:l}}const OT="fusion:ai-session-sync",ef="fusion:ai-session-sync",zT=3e4,FT=6e4;function Ci(){return Date.now()}function BT(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function tf(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 UT{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=BT(),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:Ci()})}broadcastUpdate(n){const s=n.timestamp??Ci();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??Ci();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=Ci();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=Ci();this.releaseTabOwnership(n,s,a),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:a})}broadcastHeartbeat(n){const s=Ci();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(OT),this.channel.onmessage=s=>{const a=tf(s.data);a&&this.handleIncomingMessage(a)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==ef||!s.newValue))try{const a=JSON.parse(s.newValue),r=tf(a.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=Ci();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},zT)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,a]of this.ownedSessions.entries()){const r=Ci();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(ef,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:Ci()});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=Ci(),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>FT;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 Ei=new UT;function Ir(){const e=i.useSyncExternalStore(c=>Ei.subscribe(c),()=>Ei.getSnapshot(),()=>Ei.getSnapshot());i.useEffect(()=>{Ei.requestSync()},[]);const n=i.useCallback(c=>{Ei.broadcastUpdate(c)},[]),s=i.useCallback(c=>{Ei.broadcastCompleted(c)},[]),a=i.useCallback((c,d)=>{Ei.broadcastLock(c,d)},[]),r=i.useCallback((c,d)=>{Ei.broadcastUnlock(c,d)},[]),o=i.useCallback(c=>{Ei.broadcastHeartbeat(c)},[]),l=i.useCallback(()=>{Ei.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:a,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function HT(e,n){return e&&n?`${e}/${n}`:""}function qT(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 VT=["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 WT({isOpen:e,onClose:n,onMissionCreated:s,projectId:a,initialGoal:r,resumeSessionId:o}){ji(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),[v,N]=i.useState(!1),k=i.useRef(!1),[E,y]=i.useState(""),[j,P]=i.useState(!0),[F,_]=i.useState(!1),[R,L]=i.useState(!1),[U,C]=i.useState(!1),$=i.useRef(null),V=i.useRef(null),Y=i.useRef(null),ne=i.useRef(null),[q,A]=i.useState(o??null),I=i.useMemo(()=>Ua(),[]),{isLockedByOther:D,takeControl:S,isLoading:G}=xc(e?q:null),{activeTabMap:he,broadcastUpdate:Se,broadcastCompleted:Ue,broadcastLock:ce,broadcastUnlock:Ae,broadcastHeartbeat:X}=Ir(),{confirm:Z}=ci(),[ee,le]=i.useState(void 0),[K,O]=i.useState(void 0),[pe,ve]=i.useState([]),[B,we]=i.useState(!0),[ze,re]=i.useState(null),[He,Pe]=i.useState([]),[tt,qe]=i.useState([]),de=HT(ee,K);i.useEffect(()=>{(async()=>{try{we(!0);const Fe=await Fs();ve(Fe.models),Pe(Fe.favoriteProviders),qe(Fe.favoriteModels)}catch(Fe){re(Ce(Fe)||"Failed to load models")}finally{we(!1)}})()},[]);const De=i.useCallback(je=>{Pe(Fe=>{const Be=Fe,ye=Be.includes(je)?Be.filter(kt=>kt!==je):[je,...Be];return Pn({favoriteProviders:ye,favoriteModels:tt}).catch(()=>{Pe(Be)}),ye})},[tt]),Te=i.useCallback(je=>{qe(Fe=>{const Be=Fe,ye=Be.includes(je)?Be.filter(kt=>kt!==je):[je,...Be];return Pn({favoriteProviders:He,favoriteModels:ye}).catch(()=>{qe(Be)}),ye})},[He]),ct=i.useCallback((je,Fe)=>{if(!je||!Fe)return"Using default";const Be=pe.find(St=>St.provider===je&&St.id===Fe);return Be?`${Be.provider}/${Be.id}`:`${je}/${Fe}`},[pe]),Ve=i.useCallback(je=>{V.current?.close();const Fe=z1(je,a,{onThinking:Be=>{y(St=>St+Be),Se({sessionId:je,status:"generating",needsInput:!1,owningTabId:I,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onQuestion:Be=>{_(!1),L(!1),ea(a),u({type:"question",sessionId:je,question:Be}),y(""),N(!0),Se({sessionId:je,status:"awaiting_input",needsInput:!0,owningTabId:I,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onSummary:Be=>{_(!1),L(!1),ea(a),u({type:"summary",sessionId:je,summary:Be}),b(Be),y(""),N(!0),Se({sessionId:je,status:"complete",needsInput:!1,owningTabId:I,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onError:Be=>{const St=Be||"Session failed while contacting the AI.";_(!1),L(!1),h(null),u({type:"error",sessionId:je,errorMessage:St}),y(""),N(!0),Y.current=je,Se({sessionId:je,status:"error",needsInput:!1,owningTabId:I,type:"mission_interview",title:l.trim()||void 0,projectId:a??null}),Ue({sessionId:je,status:"error"})},onComplete:()=>{_(!1),L(!1),Y.current=null,Ue({sessionId:je,status:"complete"})},onConnectionStateChange:Be=>{_(Be==="reconnecting")}});V.current=Fe},[Ue,Se,l,a,I]),me=i.useCallback(async je=>{const Fe=je??l;if(Fe.trim()){h(null),y(""),p([]),x([]),_(!1),u({type:"loading"});try{const{sessionId:Be}=await $1(Fe.trim(),a,ee&&K?{modelProvider:ee,modelId:K}:void 0);Y.current=Be,A(Be),ea(a),Ve(Be),p([])}catch(Be){_(!1),h(Ce(Be)||"Failed to start interview session"),u({type:"initial"}),Y.current=null,A(null)}}},[Ve,l,ee,K,a]);i.useEffect(()=>{e&&d.type==="initial"&&$.current?.focus()},[e,d.type]),i.useEffect(()=>{if(e&&!r&&!o&&!k.current&&d.type==="initial"){const je=IT(a);je&&c(je)}},[e]),i.useEffect(()=>{if(e&&r&&!k.current&&d.type==="initial"){c(r);const je=setTimeout(()=>{k.current=!0,me(r)},0);return()=>clearTimeout(je)}},[e,r,d.type,me]),i.useEffect(()=>{e||(k.current=!1,_(!1),L(!1),A(null))},[e]),i.useEffect(()=>{if(!e||!o||d.type!=="initial")return;let je=!1;return Ai(o).then(Fe=>{if(je||!Fe)return;const Be=xr(Fe.conversationHistory);if(x(Be),A(Fe.id),p(Be.map(St=>St.response).filter(St=>!!(St&&typeof St=="object"&&!Array.isArray(St)))),Fe.status==="awaiting_input"&&Fe.currentQuestion)try{ea(a);const St=JSON.parse(Fe.currentQuestion);Y.current=Fe.id,N(!0),u({type:"question",sessionId:Fe.id,question:St})}catch{h("Failed to restore session question.")}else if(Fe.status==="complete"&&Fe.result)try{ea(a);const St=JSON.parse(Fe.result);Y.current=Fe.id,N(!0),b(St),u({type:"summary",sessionId:Fe.id,summary:St})}catch{h("Failed to restore session result.")}else Fe.status==="generating"?(Y.current=Fe.id,N(!0),Fe.thinkingOutput&&y(Fe.thinkingOutput),u({type:"loading"}),Ve(Fe.id)):Fe.status==="error"&&(Y.current=Fe.id,N(!0),h(null),u({type:"error",sessionId:Fe.id,errorMessage:Fe.error??"The session encountered an error."}))}).catch(()=>{je||h("Failed to resume session.")}),()=>{je=!0}},[Ve,e,o,d.type,a]),i.useEffect(()=>{if(!e){ne.current&&(Ae(ne.current,I),ne.current=null);return}if(q&&ne.current!==q){ne.current&&Ae(ne.current,I),ce(q,I),ne.current=q;return}!q&&ne.current&&(Ae(ne.current,I),ne.current=null)},[ce,Ae,e,q,I]),i.useEffect(()=>{if(!e||!q||ne.current!==q)return;X(I);const je=setInterval(()=>{X(I)},3e4);return()=>{clearInterval(je)}},[X,e,q,I]),i.useEffect(()=>()=>{V.current?.close(),V.current=null,ne.current&&(Ae(ne.current,I),ne.current=null)},[Ae,I]),i.useEffect(()=>{if(!e)return;const je=Fe=>{(d.type==="question"||d.type==="summary")&&(Fe.preventDefault(),Fe.returnValue=""),V.current?.close()};return window.addEventListener("beforeunload",je),()=>window.removeEventListener("beforeunload",je)},[e,d]);const oe=i.useCallback(()=>{V.current?.close(),V.current=null,n()},[n]),Me=i.useCallback(async()=>{if(l&&PT(l,a),!(v&&!await Z({title:"Close Interview",message:"Are you sure you want to close? Your interview progress will be lost.",danger:!0}))){if(V.current?.close(),V.current=null,d.type==="question"||d.type==="summary"||d.type==="error")try{await ib(d.sessionId,a,I)}catch{}c(""),u({type:"initial"}),h(null),p([]),x([]),b(null),y(""),_(!1),L(!1),N(!1),C(!1),le(void 0),O(void 0),Y.current=null,A(null),n()}},[l,v,d,n,a,I,Z]);i.useEffect(()=>{if(!e)return;const je=Fe=>{Fe.key==="Escape"&&Me()};return document.addEventListener("keydown",je),()=>document.removeEventListener("keydown",je)},[e,Me]);const Xe=i.useCallback(async je=>{if(d.type!=="question")return;const{sessionId:Fe}=d;h(null),p(Be=>[...Be,je]),x(Be=>[...Be,{question:d.question,response:je}]),u({type:"loading"}),y("");try{Ve(Fe),await D1(Fe,je,a,I),N(!0)}catch(Be){V.current?.close(),V.current=null,h(Ce(Be)||"Failed to submit response"),u({type:"question",sessionId:Fe,question:d.question})}},[d,a,I,Ve]),rt=i.useCallback(async()=>{if(d.type!=="error")return;const je=d.sessionId;h(null),L(!0),y(""),u({type:"loading"}),Ve(je);try{Y.current=je,A(je),await L1(je,a,I)}catch(Fe){let Be=Fe;if((Ce(Fe)||"").includes("not in an error state"))try{const ye=await Ai(je);if(!ye)throw new Error("Failed to refresh interview session.");const kt=xr(ye.conversationHistory);if(x(kt),p(kt.map(It=>It.response).filter(It=>!!(It&&typeof It=="object"&&!Array.isArray(It)))),Y.current=ye.id,A(ye.id),N(!0),ye.status==="generating")y(ye.thinkingOutput??""),u({type:"loading"}),V.current?.isConnected()||Ve(ye.id);else if(ye.status==="awaiting_input"){if(!ye.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");ea(a);const It=JSON.parse(ye.currentQuestion);u({type:"question",sessionId:ye.id,question:It}),V.current?.isConnected()||Ve(ye.id)}else if(ye.status==="complete"){if(!ye.result)throw new Error("Interview session is complete but has no result.");ea(a);const It=JSON.parse(ye.result);b(It),u({type:"summary",sessionId:ye.id,summary:It})}else ye.status==="error"&&u({type:"error",sessionId:ye.id,errorMessage:ye.error??"Retry failed. Please try again."});_(!1);return}catch(ye){Be=ye}V.current?.close(),V.current=null,u({type:"error",sessionId:je,errorMessage:Ce(Be)||"Retry failed. Please try again."}),_(!1)}finally{L(!1)}},[Ve,a,I,d]),ht=i.useCallback(async()=>{if(d.type==="summary"){h(null),C(!0);try{const je=await O1(d.sessionId,w||void 0,a);s(je),ea(a),V.current?.close(),V.current=null,c(""),u({type:"initial"}),h(null),p([]),x([]),b(null),y(""),_(!1),L(!1),N(!1),C(!1),Y.current=null,A(null),n()}catch(je){h(Ce(je)||"Failed to create mission"),C(!1)}}},[d,w,s,n,a]),yt=()=>d.type==="question"?Math.min(f.length+1,6):6,Re=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",Ge=q?he.get(q):null,at=Ge&&Ge.tabId!==I,ie=!!(at&&!Ge.stale),Ke=D&&(!at||Ge.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:je=>je.target===je.currentTarget&&Me(),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(js,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Plan Mission with AI"})]}),t.jsxs("div",{className:"modal-header-actions",children:[Re&&t.jsx("button",{className:"modal-send-to-background",onClick:oe,title:"Send to background","aria-label":"Send to background",children:t.jsx(Ao,{size:16})}),t.jsx("button",{className:"modal-close",onClick:Me,"aria-label":"Close",children:t.jsx(an,{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…"}),ie&&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(xs,{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:$,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:je=>c(je.target.value),onKeyDown:je=>{je.key==="Enter"&&!je.shiftKey&&l.trim()&&(je.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:VT.map((je,Fe)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c(je),children:je.length>45?je.slice(0,45)+"...":je},Fe))})]}),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(Ns,{id:"mission-interview-modal-model",label:"Planning Model",value:de,onChange:je=>{const{provider:Fe,modelId:Be}=qT(je);le(Fe),O(Be)},models:pe,disabled:B,favoriteProviders:He,onToggleFavorite:De,favoriteModels:tt,onToggleModelFavorite:Te}),ze&&t.jsxs("div",{className:"form-hint form-hint-error",children:[ze," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{we(!0);const je=await Fs();ve(je.models),Pe(je.favoriteProviders),qe(je.favoriteModels),re(null)}catch(je){re(Ce(je)||"Failed to load models")}finally{we(!1)}})()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${ee&&K?"model-badge-custom":"model-badge-default"}`,children:ct(ee,K)})})]})]}),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(js,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),d.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(Nt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:E?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>P(!j),type:"button",children:j?"Hide thinking":"Show thinking"}),j&&E&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:E})})]})]}),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(oi,{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 rt(),disabled:R,children:[R?t.jsx(Nt,{size:14,className:"spin"}):t.jsx(fs,{size:14}),t.jsx("span",{className:"icon-ml-6",children:R?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Me,disabled:R,children:"Cancel"})]})]})]})}),d.type==="question"&&t.jsx(KT,{question:d.question,progress:yt(),historyEntries:g,onSubmit:Xe}),d.type==="summary"&&w&&t.jsx(GT,{summary:w,historyEntries:g,onSummaryChange:b,onApprove:ht,onStartOver:()=>{u({type:"initial"}),N(!1),b(null),p([]),x([]),A(null),V.current?.close(),V.current=null},isCreating:U}),D&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(ac,{size:16}),t.jsx("span",{children:Ke?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Ke&&t.jsx("button",{type:"button",onClick:()=>{S()},disabled:G,className:"btn btn-primary session-lock-take-control",children:G?"Taking control...":"Take Control"})]})})]})]})}):null}function KT({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(oi,{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(Wn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(an,{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(Eo,{size:16,className:"icon-ml-4"})]})})]})}function GT({summary:e,historyEntries:n,onSummaryChange:s,onApprove:a,onStartOver:r,isCreating:o}){const[l,c]=i.useState(()=>new Set(e.milestones.map((k,E)=>E))),[d,u]=i.useState(()=>{const k=new Set;return e.milestones.forEach((E,y)=>{E.slices.forEach((j,P)=>k.add(`${y}-${P}`))}),k}),m=k=>{c(E=>{const y=new Set(E);return y.has(k)?y.delete(k):y.add(k),y})},h=k=>{u(E=>{const y=new Set(E);return y.has(k)?y.delete(k):y.add(k),y})},f=(k,E)=>{const y=[...e.milestones];y[k]={...y[k],...E},s({...e,milestones:y})},p=(k,E,y)=>{const j=[...e.milestones],P=[...j[k].slices];P[E]={...P[E],...y},j[k]={...j[k],slices:P},s({...e,milestones:j})},g=(k,E,y,j)=>{const P=[...e.milestones],F=[...P[k].slices],_=[...F[E].features];_[y]={..._[y],...j},F[E]={...F[E],features:_},P[k]={...P[k],slices:F},s({...e,milestones:P})},x=k=>{const E=e.milestones.filter((y,j)=>j!==k);s({...e,milestones:E})},w=(k,E)=>{const y=[...e.milestones];y[k]={...y[k],slices:y[k].slices.filter((j,P)=>P!==E)},s({...e,milestones:y})},b=(k,E,y)=>{const j=[...e.milestones],P=[...j[k].slices];P[E]={...P[E],features:P[E].features.filter((F,_)=>_!==y)},j[k]={...j[k],slices:P},s({...e,milestones:j})},v=(k,E)=>{const y=[...e.milestones],j=[...y[k].slices];j[E]={...j[E],features:[...j[E].features,{title:"New feature",description:""}]},y[k]={...y[k],slices:j},s({...e,milestones:y})},N=e.milestones.reduce((k,E)=>k+E.slices.reduce((y,j)=>y+j.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(oi,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Wn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Mission Plan Ready"}),t.jsxs("p",{className:"text-muted",children:[e.milestones.length," milestones, ",N," 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:k=>s({...e,missionTitle:k.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:k=>s({...e,missionDescription:k.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Roadmap"}),t.jsx("div",{className:"roadmap-list",children:e.milestones.map((k,E)=>t.jsxs("div",{className:"roadmap-card",children:[t.jsxs("div",{className:"roadmap-card-header",onClick:()=>m(E),children:[l.has(E)?t.jsx(un,{size:16,className:"icon-text-secondary"}):t.jsx(zn,{size:16,className:"icon-text-secondary"}),t.jsx(Ia,{size:16,className:"icon-milestone"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:k.title,onChange:y=>f(E,{title:y.target.value}),onClick:y=>y.stopPropagation()}),e.milestones.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:y=>{y.stopPropagation(),x(E)},title:"Remove milestone",children:t.jsx(Sn,{size:14,className:"icon-text-secondary"})})]}),l.has(E)&&t.jsxs("div",{className:"roadmap-card-body",children:[t.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:k.description||"",onChange:y=>f(E,{description:y.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:k.verification||"",onChange:y=>f(E,{verification:y.target.value})})]}),k.slices.map((y,j)=>{const P=`${E}-${j}`;return t.jsxs("div",{className:"roadmap-slice-card",children:[t.jsxs("div",{className:"roadmap-slice-header",onClick:()=>h(P),children:[d.has(P)?t.jsx(un,{size:14,className:"icon-text-secondary"}):t.jsx(zn,{size:14,className:"icon-text-secondary"}),t.jsx(Vd,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:y.title,onChange:F=>p(E,j,{title:F.target.value}),onClick:F=>F.stopPropagation()}),k.slices.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:F=>{F.stopPropagation(),w(E,j)},title:"Remove slice",children:t.jsx(Sn,{size:12,className:"icon-text-secondary"})})]}),d.has(P)&&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:y.verification||"",onChange:F=>p(E,j,{verification:F.target.value})})]}),y.features.map((F,_)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(zd,{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:R=>g(E,j,_,{title:R.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(E,j,_),title:"Remove feature",children:t.jsx(Sn,{size:12,className:"icon-text-secondary"})})]},_)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>v(E,j),children:[t.jsx(Cn,{size:12}),"Add Feature"]})]})]},j)})]})]},E))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:o,children:[t.jsx(Fa,{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(Nt,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Wn,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}const JT=30,YT=16,QT=16;function XT(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let El=null;function Zx(){return El===null&&(El=window.visualViewport?.height??window.innerHeight),El}function ZT(e){const n=Zx();e>n&&(El=e)}function e4(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 nf(){if(typeof window>"u"||!window.visualViewport)return{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0};const e=window.visualViewport,n=e4(document.activeElement),s=e.offsetTop;n||ZT(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=Zx(),o=Math.max(0,r-e.offsetTop-e.height);if(o>=JT&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};if(o>=YT&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};const l=Math.max(0,r-e.height);return n&&l>=QT?{overlap:0,open:!0,vvHeight:e.height,vvOffsetTop:s}:{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0}}function Yi({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||!XT()){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 y=nf();s(y.overlap),r(y.vvHeight),l(y.vvOffsetTop),d(y.open)},h=()=>{const y=nf();s(y.overlap),r(y.vvHeight),d(y.open)},f=[],p=y=>{if(typeof window>"u")return;const j=window.setTimeout(()=>{typeof window>"u"||m()},y);f.push(j)};let g=null,x=0,w=-1,b=0;const v=()=>{g!==null&&typeof window<"u"&&(window.cancelAnimationFrame(g),g=null)},N=()=>{if(typeof window>"u")return;m();const y=window.visualViewport?.offsetTop??0;if(y===w?b+=1:(b=0,w=y),b>=2||performance.now()>x){g=null;return}g=window.requestAnimationFrame(N)},k=()=>{typeof window>"u"||(v(),x=performance.now()+1500,w=-1,b=0,g=window.requestAnimationFrame(N))},E=()=>{m(),p(50),p(200),p(500),p(1e3),p(1500),k()};return E(),u.addEventListener("resize",m),u.addEventListener("scroll",h),document.addEventListener("focusin",E),document.addEventListener("focusout",m),document.addEventListener("visibilitychange",E),window.addEventListener("pageshow",E),()=>{u.removeEventListener("resize",m),u.removeEventListener("scroll",h),document.removeEventListener("focusin",E),document.removeEventListener("focusout",m),document.removeEventListener("visibilitychange",E),window.removeEventListener("pageshow",E);for(const y of f)clearTimeout(y);v(),s(0),r(null),l(0),d(!1)}},[e]),{keyboardOverlap:n,viewportHeight:a,viewportOffsetTop:o,keyboardOpen:c}}function t4({isOpen:e,onClose:n,onApplied:s,targetType:a,targetId:r,targetTitle:o,missionContext:l,projectId:c,resumeSessionId:d}){const u=Zs();ji(e);const{keyboardOverlap:m,viewportHeight:h,viewportOffsetTop:f,keyboardOpen:p}=Yi({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,v]=i.useState(null),[N,k]=i.useState([]),[E,y]=i.useState([]),[j,P]=i.useState(null),[F,_]=i.useState(""),[R,L]=i.useState(!0),[U,C]=i.useState(!1),[$,V]=i.useState(!1),Y=i.useRef(null),ne=i.useRef(null),q=i.useRef(null),A=i.useRef(null),[I,D]=i.useState(null),S=i.useMemo(()=>Ua(),[]);xc(e?I:null);const{activeTabMap:G,broadcastUpdate:he,broadcastCompleted:Se,broadcastLock:Ue,broadcastUnlock:ce,broadcastHeartbeat:Ae}=Ir(),X=a==="milestone"?F1:V1,Z=a==="milestone"?B1:W1,ee=a==="milestone"?U1:K1,le=a==="milestone"?H1:G1,K=a==="milestone"?q1:J1,O=a==="milestone"?"Milestone":"Slice",pe=a==="milestone"?"milestone_interview":"slice_interview",ve=i.useCallback(Ve=>{ne.current?.close();const me=ee(Ve,c,{onThinking:oe=>{_(Me=>Me+oe),he({sessionId:Ve,status:"generating",needsInput:!1,owningTabId:S,type:pe,title:o,projectId:c??null})},onQuestion:oe=>{C(!1),B(),w({type:"question",sessionId:Ve,question:oe}),_(""),he({sessionId:Ve,status:"awaiting_input",needsInput:!0,owningTabId:S,type:pe,title:o,projectId:c??null})},onSummary:oe=>{C(!1),B(),w({type:"summary",sessionId:Ve,summary:oe}),P(oe),_(""),he({sessionId:Ve,status:"complete",needsInput:!1,owningTabId:S,type:pe,title:o,projectId:c??null})},onError:oe=>{const Me=oe||"Session failed while contacting the AI.";C(!1),v(null),w({type:"error",sessionId:Ve,errorMessage:Me}),_(""),q.current=Ve,he({sessionId:Ve,status:"error",needsInput:!1,owningTabId:S,type:pe,title:o,projectId:c??null}),Se({sessionId:Ve,status:"error"})},onComplete:()=>{C(!1),q.current=null,Se({sessionId:Ve,status:"complete"})},onConnectionStateChange:oe=>{C(oe==="reconnecting")}});ne.current=me},[Se,he,ee,pe,c,S,o]),B=()=>{P(null),k([]),y([]),_("")},we=i.useCallback(async()=>{v(null),B(),C(!1),w({type:"loading"});try{const{sessionId:Ve}=await X(r,c);q.current=Ve,D(Ve),ve(Ve)}catch(Ve){C(!1),v(Ce(Ve)||`Failed to start ${O.toLowerCase()} interview`),w({type:"initial"}),q.current=null,D(null)}},[ve,c,X,r,O]),ze=i.useCallback(async()=>{v(null),V(!0);try{await K(r,c),s(),w({type:"applied"})}catch(Ve){v(Ce(Ve)||`Failed to skip ${O.toLowerCase()} interview`),V(!1)}},[s,c,K,r,O]);i.useEffect(()=>{e&&x.type==="initial"&&Y.current?.focus()},[e,x.type]),i.useEffect(()=>{if(!e||!d||x.type!=="initial")return;let Ve=!1;return Ai(d).then(me=>{if(Ve||!me)return;const oe=xr(me.conversationHistory);if(y(oe),D(me.id),k(oe.map(Me=>Me.response).filter(Me=>!!(Me&&typeof Me=="object"&&!Array.isArray(Me)))),me.status==="awaiting_input"&&me.currentQuestion)try{const Me=JSON.parse(me.currentQuestion);q.current=me.id,w({type:"question",sessionId:me.id,question:Me})}catch{v("Failed to restore session question.")}else if(me.status==="complete"&&me.result)try{const Me=JSON.parse(me.result);q.current=me.id,P(Me),w({type:"summary",sessionId:me.id,summary:Me})}catch{v("Failed to restore session result.")}else me.status==="generating"?(q.current=me.id,me.thinkingOutput&&_(me.thinkingOutput),w({type:"loading"}),ve(me.id)):me.status==="error"&&(q.current=me.id,v(null),w({type:"error",sessionId:me.id,errorMessage:me.error??"The session encountered an error."}))}).catch(()=>{Ve||v("Failed to resume session.")}),()=>{Ve=!0}},[ve,e,d,x.type]),i.useEffect(()=>{e||(C(!1),D(null))},[e]),i.useEffect(()=>{if(!(!e||!I)){if(A.current!==I){A.current&&ce(A.current,S),Ue(I,S),A.current=I;return}!I&&A.current&&(ce(A.current,S),A.current=null)}},[Ue,ce,e,I,S]),i.useEffect(()=>{if(!e||!I||A.current!==I)return;Ae(S);const Ve=setInterval(()=>{Ae(S)},3e4);return()=>{clearInterval(Ve)}},[Ae,e,I,S]),i.useEffect(()=>()=>{ne.current?.close(),ne.current=null,A.current&&(ce(A.current,S),A.current=null)},[ce,S]);const re=i.useCallback(()=>{ne.current?.close(),ne.current=null,n()},[n]),He=i.useCallback(async()=>{ne.current?.close(),ne.current=null,B(),w({type:"initial"}),v(null),q.current=null,D(null),n()},[n]),Pe=i.useCallback(async Ve=>{if(x.type!=="question")return;const{sessionId:me}=x;v(null),k(oe=>[...oe,Ve]),y(oe=>[...oe,{question:x.question,response:Ve}]),w({type:"loading"}),_("");try{ve(me),await Z(me,Ve,c,S)}catch(oe){ne.current?.close(),ne.current=null,v(Ce(oe)||"Failed to submit response"),w({type:"question",sessionId:me,question:x.question})}},[ve,c,Z,S,x]),tt=i.useCallback(async()=>{if(x.type==="summary"){v(null),V(!0);try{await le(x.sessionId,j||void 0,c),s(),w({type:"applied"})}catch(Ve){v(Ce(Ve)||"Failed to apply interview results"),V(!1)}}},[le,j,s,c,x]),qe=()=>x.type==="question"?Math.min(N.length+1,6):6,de=x.type==="loading"||x.type==="question"||x.type==="summary"||x.type==="error",De=I?G.get(I):null,ct=!!(De&&De.tabId!==S&&!De.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Ve=>Ve.target===Ve.currentTarget&&He(),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(xs,{size:20,className:"icon-triage"}),t.jsxs("h3",{children:["Plan ",O,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[de&&t.jsx("button",{className:"modal-send-to-background",onClick:re,title:"Send to background","aria-label":"Send to background",children:t.jsx(Ao,{size:16})}),t.jsx("button",{className:"modal-close",onClick:He,"aria-label":"Close",children:t.jsx(an,{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…"}),ct&&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(xs,{size:32,className:"icon-triage-lg"}),t.jsxs("h4",{children:["Refine ",O," 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 we(),children:[t.jsx(xs,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void ze(),disabled:$,children:[$?t.jsx(Nt,{size:16,className:"spin"}):null,"Use Mission Context"]}),t.jsx("button",{className:"btn",onClick:He,children:"Cancel"})]})]}),x.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(Nt,{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:()=>L(!R),type:"button",children:R?"Hide thinking":"Show thinking"}),R&&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:[E.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(oi,{entries:E}),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:He,children:"Cancel"})})]})]})}),x.type==="question"&&t.jsx(n4,{question:x.question,progress:qe(),historyEntries:E,onSubmit:Pe}),x.type==="summary"&&j&&t.jsx(s4,{summary:j,historyEntries:E,onSummaryChange:P,onApply:tt,onCancel:He,isApplying:$}),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(Wn,{size:48,className:"icon-success"}),t.jsxs("h4",{children:[O," 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 n4({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(oi,{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(Wn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(an,{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(Eo,{size:16,className:"icon-ml-4"})]})})]})}function s4({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(oi,{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(un,{size:16}):t.jsx(zn,{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(Nt,{size:16,className:"spin"}):null,"Apply"]}),t.jsx("button",{className:"btn",onClick:r,disabled:o,children:"Cancel"})]})]})}const sf=300,cl=220,dl=560,af="fusion:mission-sidebar-width",Kr={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)"}},rf={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)"}},of={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)"}},ul={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)"}},ml={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)"}},hl={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)"}},lf={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)"}},i4=3;function a4(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function cf({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 df(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const uf={title:"",description:"",status:"planning",autopilotEnabled:!1},gd={title:"",description:"",status:"planning",dependencies:[]},bd={title:"",description:"",status:"pending"},xd={title:"",description:"",acceptanceCriteria:"",status:"defined"},r4=3600*1e3;function Vl(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 o4(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=r4,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 l4(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 c4(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 vd(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 ev=["feature_triaged","feature_completed"],tv=["slice_activated","slice_completed","milestone_completed"],nv=["mission_started","mission_paused","mission_resumed","mission_completed"],sv=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function mf(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return nv.includes(e);case"tasks":return ev.includes(e);case"slices":return tv.includes(e);case"autopilot":return sv.includes(e);default:return!0}}function d4(e){return e==="error"||e==="warning"?"mission-event__type--error":nv.includes(e)?"mission-event__type--state":ev.includes(e)?"mission-event__type--task":tv.includes(e)?"mission-event__type--slice":sv.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function u4(e){return e.replace(/_/g," ")}function m4(e,n){return n?e==="watching"?`Watching since ${Vl(n)}`:`Last activation ${Vl(n)}`:null}function h4({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),[v,N]=i.useState(!1),k=Zs()==="mobile",[E,y]=i.useState(()=>{if(typeof window>"u")return sf;const H=window.localStorage.getItem(af),Ne=H?Number(H):NaN;return Number.isFinite(Ne)?Math.max(cl,Math.min(dl,Ne)):sf}),j=i.useCallback(H=>{try{window.localStorage.setItem(af,String(H))}catch{}},[]),P=i.useCallback(H=>{if(k)return;H.preventDefault(),H.stopPropagation();const Ne=H.currentTarget;typeof Ne.setPointerCapture=="function"&&Ne.setPointerCapture(H.pointerId);const Je=H.clientX,Mt=E;let fn=Mt;document.body.style.userSelect="none";const en=st=>{const Ze=st.clientX-Je,Ft=Math.max(cl,Math.min(dl,Mt+Ze));fn=Ft,y(Ft)},An=st=>{typeof Ne.releasePointerCapture=="function"&&Ne.releasePointerCapture(st.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",en),document.removeEventListener("pointerup",An),j(fn)};document.addEventListener("pointermove",en),document.addEventListener("pointerup",An)},[k,j,E]),F=i.useCallback(H=>{if(k||H.key!=="ArrowLeft"&&H.key!=="ArrowRight")return;H.preventDefault();const Ne=H.shiftKey?50:10,Je=H.key==="ArrowLeft"?-Ne:Ne,Mt=Math.max(cl,Math.min(dl,E+Je));y(Mt),j(Mt)},[k,j,E]),[_,R]=i.useState(!1),[L,U]=i.useState(null),[C,$]=i.useState(uf),[V,Y]=i.useState(!1),[ne,q]=i.useState(new Set),[A,I]=i.useState(new Set),[D,S]=i.useState(null),[G,he]=i.useState(gd),[Se,Ue]=i.useState(!1),[ce,Ae]=i.useState(null),[X,Z]=i.useState(bd),[ee,le]=i.useState(!1),[K,O]=i.useState(null),[pe,ve]=i.useState(null),[B,we]=i.useState(xd),[ze,re]=i.useState(!1),[He,Pe]=i.useState(null),[tt,qe]=i.useState(null),[de,De]=i.useState(""),[Te,ct]=i.useState(!1),[Ve,me]=i.useState([]),[oe,Me]=i.useState(void 0),Xe=oe??c,[rt,ht]=i.useState(null),[yt,Re]=i.useState(null),[Ge,at]=i.useState(null);i.useEffect(()=>{h&&Xe&&ct(!0)},[h,Xe]),i.useEffect(()=>{if(!h||Xe)return;let H=!1;return Ru(r).then(Ne=>{if(H)return;const Je=Ne.filter(Mt=>Mt.type==="mission_interview"&&(Mt.status==="awaiting_input"||Mt.status==="error"));me(Je)}).catch(Ne=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",Ne)}),()=>{H=!0}},[h,r,Xe]),i.useEffect(()=>{if(!h||!u)return;let H=!1;return Ai(u).then(Ne=>{if(!(H||!Ne))try{const Je=JSON.parse(Ne.inputPayload||"{}");Je.targetId&&Je.targetType&&ht({type:Je.targetType,id:Je.targetId,title:Je.targetTitle||Ne.title,resumeSessionId:u})}catch{ht({type:"milestone",id:"",title:Ne.title,resumeSessionId:u})}}).catch(Ne=>{H||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",Ne),m?.())}),()=>{H=!0}},[h,u,m]);const[ie,Ke]=i.useState(null),[je,Fe]=i.useState(new Map),[Be,St]=i.useState(null),[ye,kt]=i.useState({title:"",assertion:"",status:"pending"}),[It,Ie]=i.useState(!1),[be,ot]=i.useState(null),[gt,xt]=i.useState(new Map),[jt,Bt]=i.useState(new Set),[Jt,Vt]=i.useState(new Set),[pn,Xt]=i.useState(null),[mn,Ht]=i.useState(new Map),[Zt,tn]=i.useState(null),[dn,qt]=i.useState(null),[ke,$e]=i.useState(!0),[Ye,ut]=i.useState(new Set),[We,$t]=i.useState(new Map),[At,wt]=i.useState(null),[zt,Lt]=i.useState(new Map),[Ot,nn]=i.useState(null),[Yt,rn]=i.useState(new Map),[_e,it]=i.useState(new Map),[bt,Rt]=i.useState("structure"),[se,te]=i.useState([]),Oe=i.useRef([]),mt=i.useRef([]),Pt=i.useRef(null),sn=i.useRef(null),In=i.useRef("structure"),fe=i.useRef("all"),[ft,lt]=i.useState(!1),[vt,et]=i.useState(0),[_t,Gt]=i.useState("all"),[ae,pt]=i.useState(new Set),gn=i.useRef(null),us=i.useRef(null);mt.current=f,Pt.current=g,sn.current=Zt,In.current=bt,fe.current=_t;const Kn=i.useCallback((H="auto")=>{const Ne=us.current;if(Ne&&typeof Ne.scrollIntoView=="function"){Ne.scrollIntoView({block:"end",behavior:H});return}const Je=gn.current;Je&&(Je.scrollTop=Je.scrollHeight)},[]),_n=i.useCallback(()=>{const H=gn.current;return H?H.scrollHeight-H.scrollTop-H.clientHeight<=100:!0},[]),$n=i.useCallback(async H=>{if(H.length===0){it(new Map);return}const Ne=await l1(r);it(Je=>{const Mt=new Map(Je);for(const[fn,en]of Object.entries(Ne))l4(en)&&Mt.set(fn,en);return Mt})},[r]),hn=i.useCallback(async()=>{try{b(!0);const H=await s1(r);p(H),$n(H)}catch(H){a(Ce(H)||"Failed to load missions","error")}finally{b(!1)}},[a,r,$n]),Ut=i.useCallback(async H=>{try{N(!0);const Ne=await sb(H,r);if(!Ne||!Array.isArray(Ne.milestones)){N(!1);return}if(x(Ne),Ne.milestones.length>0){const Je=Ne.milestones[0].id;tn(Je),$e(!0),q(new Set([Je])),Ec(Je,r).then(Mt=>{Fe(fn=>{const en=new Map(fn);return en.set(Je,Mt),en})}).catch(()=>{}),_c(Je,r).then(Mt=>{Ht(fn=>{const en=new Map(fn);return en.set(Je,Mt),en})}).catch(()=>{}),Ne.milestones[0].slices.length>0&&I(new Set([Ne.milestones[0].slices[0].id]))}else tn(null),qt(null)}catch(Ne){a(Ce(Ne)||"Failed to load mission details","error")}finally{N(!1)}},[a,r]);i.useEffect(()=>{if(!h||!Zt){qt(null);return}let H=!1;return qt(null),qm(Zt,r).then(Ne=>{if(!H){if(!vd(Ne)){qt(null);return}qt(Ne),Ht(Je=>{const Mt=new Map(Je);return Mt.set(Zt,Ne.rollup),Mt})}}).catch(()=>{H||qt(null)}),()=>{H=!0}},[h,Zt,r]),i.useEffect(()=>{$e(!0)},[Zt]);const Dn=i.useCallback(H=>{!H||H!==sn.current||qm(H,r).then(Ne=>{sn.current!==H||!vd(Ne)||(qt(Ne),Ht(Je=>{const Mt=new Map(Je);return Mt.set(H,Ne.rollup),Mt}))}).catch(()=>{})},[r]),as=i.useCallback(async(H,Ne)=>{const Je=Ne?.append??!1,Mt=Je?Oe.current.length:0;Je||(lt(!0),pt(new Set));try{const fn=await o1(H,{limit:50,offset:Mt,eventType:void 0},r),en=fn.events.filter(An=>mf(An.eventType,_t));te(An=>{if(!Je)return Oe.current=en,en;const st=new Set(An.map(Ft=>Ft.id)),Ze=[...An];for(const Ft of en)st.has(Ft.id)||Ze.push(Ft);return Oe.current=Ze,Ze}),et(fn.total),Je||requestAnimationFrame(()=>{Kn("auto")})}catch(fn){a(Ce(fn)||"Failed to load mission activity","error")}finally{Je||lt(!1)}},[a,_t,r,Kn]);i.useEffect(()=>{Oe.current=se},[se]),i.useEffect(()=>{h&&(hn(),x(null),tn(null),qt(null),te([]),et(0),Rt("structure"),Gt("all"),pt(new Set))},[h,hn]);const Rn=i.useRef(null);i.useEffect(()=>{h&&d&&Rn.current!==d&&f.length>0&&(Rn.current=d,Ut(d))},[h,d,f,Ut]),i.useEffect(()=>{h||(Rn.current=null)},[h]);const ms=i.useRef(!1);i.useEffect(()=>{!h||!n||k||w||ms.current||g||d||f.length!==0&&(ms.current=!0,Ut(f[0].id))},[h,n,k,w,f,g,d,Ut]),i.useEffect(()=>{h||(ms.current=!1)},[h]),i.useEffect(()=>{!h||!g||bt!=="activity"||as(g.id)},[bt,h,as,g,_t]),i.useEffect(()=>{if(!h||typeof EventSource>"u")return;const H=new URLSearchParams;r&&H.set("projectId",r);const Ne=`/api/events${H.size>0?`?${H.toString()}`:""}`,Je=()=>{$n(mt.current)},Mt=ls=>{Je();const Yn=ls;if(Yn.data)try{const vn=JSON.parse(Yn.data);vn?.id&&p(hi=>hi.map(Us=>Us.id===vn.id?{...Us,...vn}:Us))}catch{}Pt.current&&Ut(Pt.current.id)},fn=ls=>{Je(),Pt.current&&Ut(Pt.current.id)},en=()=>{Je(),Pt.current&&Ut(Pt.current.id)},An=ls=>{Je(),Pt.current&&Ut(Pt.current.id)},st=ls=>{const Yn=ls;if(Yn.data)try{const vn=JSON.parse(Yn.data);vn&&vn.featureId&&(ei(vn.featureId),di(vn.featureId),vn.milestoneId&&Dn(vn.milestoneId))}catch{}},Ze=ls=>{const Yn=ls;if(Yn.data)try{const vn=JSON.parse(Yn.data);vn&&vn.featureId&&(ei(vn.featureId),di(vn.featureId),vn.milestoneId&&Dn(vn.milestoneId),Pt.current&&Ut(Pt.current.id))}catch{}},Ft=ls=>{const Yn=ls;if(Yn.data)try{const vn=JSON.parse(Yn.data);vn&&vn.milestoneId&&(Hn(vn.milestoneId),Dn(vn.milestoneId))}catch{}},ln=ls=>{const Yn=ls;if(Yn.data)try{const vn=JSON.parse(Yn.data);vn&&vn.milestoneId&&(Jn(vn.milestoneId),Hn(vn.milestoneId),Dn(vn.milestoneId))}catch{}};return li(Ne,{events:{"mission:updated":Mt,"slice:updated":fn,"feature:updated":en,"milestone:updated":An,"mission:event":ls=>{Je();const Yn=Pt.current;if(!Yn||In.current!=="activity")return;const vn=_n(),hi=ls;if(hi.data)try{const Us=JSON.parse(hi.data);if(!c4(Us)||Us.missionId!==Yn.id||!mf(Us.eventType,fe.current))return;te(pi=>{const Ja=pi.filter(Xi=>Xi.id!==Us.id);return[Us,...Ja].slice(0,100)}),et(pi=>pi+1),vn&&requestAnimationFrame(()=>{const pi=gn.current;pi&&(pi.scrollTop=0)})}catch{}},"validator-run:started":st,"validator-run:completed":Ze,"milestone:validation:updated":Ft,"assertion:created":ln,"assertion:updated":ln,"assertion:deleted":ln,"assertion:linked":ln,"assertion:unlinked":ln,"fix-feature:created":ls=>{const Yn=ls;if(Yn.data)try{const vn=JSON.parse(Yn.data);if(vn&&vn.sourceFeatureId){ei(vn.sourceFeatureId);const hi=vn?.feature?.sliceId,Us=Pt.current;if(hi&&Us){const pi=Us.milestones.find(Ja=>Ja.slices.some(Xi=>Xi.id===hi));pi&&Dn(pi.id)}Pt.current&&Ut(Pt.current.id)}}catch{}}}})},[h,_n,Ut,$n,r,Dn]);const Xn=i.useCallback(H=>{U(H.id),R(!1),$({title:H.title,description:H.description||"",status:H.status,autopilotEnabled:H.autopilotEnabled??!1})},[]),vs=i.useCallback(()=>{U(null),R(!1),$(uf)},[]),Gn=i.useCallback(async()=>{if(!C.title.trim()){a("Mission title is required","error");return}try{if(Y(!0),_)await i1({title:C.title.trim(),description:C.description.trim()||void 0,autopilotEnabled:C.autopilotEnabled},r),a("Mission created","success");else if(L){const H={title:C.title.trim(),description:C.description.trim()||void 0,status:C.status,autopilotEnabled:C.autopilotEnabled};C.autopilotEnabled&&(H.autoAdvance=!0),await a1(L,H,r),a("Mission updated","success"),g?.id===L&&await Ut(L)}await hn(),vs()}catch(H){a(Ce(H)||"Failed to save mission","error")}finally{Y(!1)}},[C,_,L,a,hn,Ut,g,vs,r]),hs=i.useCallback(async H=>{try{await r1(H,r),a("Mission deleted","success"),g?.id===H&&x(null),await hn(),Ke(null)}catch(Ne){a(Ce(Ne)||"Failed to delete mission","error")}},[a,hn,g,r]),Ln=i.useCallback(()=>{Ue(!0),S(null),he(gd)},[]),En=i.useCallback(H=>{S(H.id),Ue(!1),he({title:H.title,description:H.description||"",status:H.status,dependencies:H.dependencies})},[]),ps=i.useCallback(()=>{S(null),Ue(!1),he(gd)},[]),Nn=i.useCallback(async()=>{if(!G.title.trim()){a("Milestone title is required","error");return}try{Y(!0),Se&&g?(await c1(g.id,{title:G.title.trim(),description:G.description.trim()||void 0,dependencies:G.dependencies},r),a("Milestone created","success")):D&&(await d1(D,{title:G.title.trim(),description:G.description.trim()||void 0,status:G.status,dependencies:G.dependencies},r),a("Milestone updated","success")),await Ut(g.id),ps()}catch(H){a(Ce(H)||"Failed to save milestone","error")}finally{Y(!1)}},[G,Se,D,g,a,Ut,ps,C.title,r]),As=i.useCallback(async H=>{try{await u1(H,r),a("Milestone deleted","success"),await Ut(g.id),Ke(null)}catch(Ne){a(Ce(Ne)||"Failed to delete milestone","error")}},[a,Ut,g,r]),Cs=i.useCallback(H=>{tn(H),$e(!0),q(Ne=>{const Je=new Set(Ne);return!Je.has(H)?(Je.add(H),Ec(H,r).then(fn=>{Fe(en=>{const An=new Map(en);return An.set(H,fn),An})}).catch(()=>{}),_c(H,r).then(fn=>{Ht(en=>{const An=new Map(en);return An.set(H,fn),An})}).catch(()=>{})):Je.delete(H),Je})},[r]),Es=i.useCallback(H=>{O(H),le(!0),Ae(null),Z(bd)},[]),Q=i.useCallback(H=>{Ae(H.id),le(!1),Z({title:H.title,description:H.description||"",status:H.status})},[]),M=i.useCallback(()=>{Ae(null),le(!1),O(null),Z(bd)},[]),ue=i.useCallback(async()=>{if(!X.title.trim()){a("Slice title is required","error");return}try{Y(!0),ee&&K?(await m1(K,{title:X.title.trim(),description:X.description.trim()||void 0},r),a("Slice created","success")):ce&&(await h1(ce,{title:X.title.trim(),description:X.description.trim()||void 0,status:X.status},r),a("Slice updated","success")),await Ut(g.id),M()}catch(H){a(Ce(H)||"Failed to save slice","error")}finally{Y(!1)}},[X,ee,ce,K,g,a,Ut,M,r]),Ee=i.useCallback(async H=>{try{await p1(H,r),a("Slice deleted","success"),await Ut(g.id),Ke(null)}catch(Ne){a(Ce(Ne)||"Failed to delete slice","error")}},[a,Ut,g,r]),z=i.useCallback(async H=>{try{await f1(H,r),a("Slice activated","success"),await Ut(g.id)}catch(Ne){a(Ce(Ne)||"Failed to activate slice","error")}},[a,Ut,g,r]),ge=i.useCallback(H=>{I(Ne=>{const Je=new Set(Ne);return Je.has(H)?Je.delete(H):Je.add(H),Je})},[]),xe=i.useCallback(H=>{Pe(H),re(!0),ve(null),we(xd)},[]),dt=i.useCallback(H=>{ve(H.id),re(!1),we({title:H.title,description:H.description||"",acceptanceCriteria:H.acceptanceCriteria||"",status:H.status})},[]),Tt=i.useCallback(()=>{ve(null),re(!1),Pe(null),we(xd)},[]),Wt=i.useCallback(async()=>{if(!B.title.trim()){a("Feature title is required","error");return}try{Y(!0),ze&&He?(await g1(He,{title:B.title.trim(),description:B.description.trim()||void 0,acceptanceCriteria:B.acceptanceCriteria.trim()||void 0},r),a("Feature created","success")):pe&&(await b1(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),Tt()}catch(H){a(Ce(H)||"Failed to save feature","error")}finally{Y(!1)}},[B,ze,pe,He,g,a,Ut,Tt,r]),bn=i.useCallback(async H=>{try{await x1(H,r),a("Feature deleted","success"),await Ut(g.id),Ke(null)}catch(Ne){a(Ce(Ne)||"Failed to delete feature","error")}},[a,Ut,g,r]),Mn=i.useCallback(async()=>{if(!tt||!de.trim()){a("Task ID is required","error");return}try{await v1(tt,de.trim(),r),a("Feature linked to task","success"),await Ut(g.id),qe(null),De("")}catch(H){a(Ce(H)||"Failed to link feature to task","error")}},[tt,de,a,Ut,g,r]),Zn=i.useCallback(async H=>{try{await y1(H,r),a("Feature unlinked from task","success"),await Ut(g.id)}catch(Ne){a(Ce(Ne)||"Failed to unlink feature","error")}},[a,Ut,g,r]),On=i.useCallback(async H=>{try{Y(!0),await w1(H,void 0,void 0,r),a("Feature triaged — task created","success"),await Ut(g.id)}catch(Ne){a(Ce(Ne)||"Failed to triage feature","error")}finally{Y(!1)}},[a,Ut,g,r]),Un=i.useCallback(async H=>{at(H);try{const Ne=await Y1(H,r);Re({featureId:H,enrichedDescription:Ne.description})}catch{await On(H)}finally{at(null)}},[On,r]),rs=i.useCallback(async()=>{yt&&(Re(null),await On(yt.featureId))},[On,yt]),ts=i.useCallback(()=>{Re(null)},[]),xn=i.useCallback(async H=>{try{Y(!0);const Ne=await k1(H,r);a(`Triaged ${Ne.count} feature${Ne.count!==1?"s":""}`,"success"),await Ut(g.id)}catch(Ne){a(Ce(Ne)||"Failed to triage slice features","error")}finally{Y(!1)}},[a,Ut,g,r]),Jn=i.useCallback(async H=>{try{const Ne=await Ec(H,r);Fe(Je=>{const Mt=new Map(Je);return Mt.set(H,Ne),Mt})}catch{}},[r]),Hn=i.useCallback(async H=>{try{const Ne=await _c(H,r);Ht(Je=>{const Mt=new Map(Je);return Mt.set(H,Ne),Mt})}catch{}},[r]),ws=i.useCallback(async H=>{if(!ye.title.trim()||!ye.assertion.trim()){a("Title and assertion text are required","error");return}try{Y(!0),await j1(H,{title:ye.title.trim(),assertion:ye.assertion.trim(),status:ye.status},r),a("Assertion created","success"),await Jn(H),await Hn(H),Ie(!1),kt({title:"",assertion:"",status:"pending"})}catch(Ne){a(Ce(Ne)||"Failed to create assertion","error")}finally{Y(!1)}},[ye,a,Jn,Hn,r]),ns=i.useCallback(H=>{St(H.id),kt({title:H.title,assertion:H.assertion,status:H.status})},[]),es=i.useCallback(()=>{St(null),Ie(!1),kt({title:"",assertion:"",status:"pending"})},[]),Bs=i.useCallback(async(H,Ne)=>{if(!ye.title.trim()||!ye.assertion.trim()){a("Title and assertion text are required","error");return}try{Y(!0),await N1(H,{title:ye.title.trim(),assertion:ye.assertion.trim(),status:ye.status},r),a("Assertion updated","success"),await Jn(Ne),await Hn(Ne),es()}catch(Je){a(Ce(Je)||"Failed to update assertion","error")}finally{Y(!1)}},[ye,a,Jn,Hn,es,r]),Ds=i.useCallback(async H=>{try{const Ne=await E1(H,r);xt(Je=>{const Mt=new Map(Je);return Mt.set(H,Ne),Mt})}catch{}},[r]),wn=i.useCallback(async H=>{const Ne=be!==H;ot(Je=>Je===H?null:H),Ne&&await Ds(H)},[be,Ds]),ma=i.useCallback(H=>{ot(H),Ds(H),requestAnimationFrame(()=>{const Ne=document.querySelector(`[data-mission-assertion-id="${H}"]`);Ne instanceof HTMLElement&&typeof Ne.scrollIntoView=="function"&&Ne.scrollIntoView({behavior:"smooth",block:"center"})})},[Ds]),ha=i.useCallback(async(H,Ne)=>{try{Bt(Je=>new Set(Je).add(Ne)),await S1(H,Ne,r),a("Feature linked to assertion","success"),await Ds(Ne),Xt(null)}catch(Je){a(Ce(Je)||"Failed to link feature","error")}finally{Bt(Je=>{const Mt=new Set(Je);return Mt.delete(Ne),Mt})}},[a,Ds,r]),pa=i.useCallback(async(H,Ne)=>{const Je=`${H}-${Ne}`;try{Vt(Mt=>new Set(Mt).add(Je)),await C1(H,Ne,r),a("Feature unlinked from assertion","success"),await Ds(Ne)}catch(Mt){a(Ce(Mt)||"Failed to unlink feature","error")}finally{Vt(Mt=>{const fn=new Set(Mt);return fn.delete(Je),fn})}},[a,Ds,r]),Ha=i.useCallback(async H=>{try{ut(Je=>new Set(Je).add(H)),await _1(H,r),a("Validation triggered","success");const Ne=await Vm(H,r);$t(Je=>{const Mt=new Map(Je);return Mt.set(H,Ne),Mt})}catch(Ne){a(Ce(Ne)||"Failed to trigger validation","error")}finally{ut(Ne=>{const Je=new Set(Ne);return Je.delete(H),Je})}},[a,r]),ei=i.useCallback(async H=>{try{const Ne=await Vm(H,r);$t(Je=>{const Mt=new Map(Je);return Mt.set(H,Ne),Mt})}catch{}},[r]),di=i.useCallback(async H=>{try{const Ne=await M1(H,{limit:10},r);Lt(Je=>{const Mt=new Map(Je);return Mt.set(H,Ne),Mt})}catch{}},[r]),Di=i.useCallback(H=>{const Ne=Pt.current;if(Ne){for(const Je of Ne.milestones)for(const Mt of Je.slices)if(Mt.features.find(en=>en.id===H)){q(en=>{const An=new Set(en);return An.add(Je.id),An}),I(en=>{const An=new Set(en);return An.add(Mt.id),An}),wt(H),tn(Je.id),ei(H),di(H),requestAnimationFrame(()=>{const en=document.querySelector(`[data-mission-feature-id="${H}"]`);en instanceof HTMLElement&&typeof en.scrollIntoView=="function"&&en.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[ei,di]),fa=i.useCallback(async H=>{try{const Ne=await A1(H,r);rn(Je=>{const Mt=new Map(Je);return Mt.set(H,Ne),Mt})}catch{}},[r]),qa=i.useCallback(async H=>{At===H?wt(null):(wt(H),await ei(H),await di(H))},[At,ei,di]),Va=i.useCallback(async H=>{Ot===H?nn(null):(nn(H),await fa(H))},[Ot,fa]),ga=i.useCallback(async H=>{try{await R1(H,r),a("Mission resumed","success"),await Ut(H),hn()}catch(Ne){a(Ce(Ne)||"Failed to resume mission","error")}},[a,Ut,hn,r]),ti=i.useCallback(async H=>{try{const Je=(await P1(H,r)).pausedTaskIds?.length??0;a(`Mission stopped (${Je} task${Je!==1?"s":""} paused)`,"success"),await Ut(H),hn()}catch(Ne){a(Ce(Ne)||"Failed to stop mission","error")}},[a,Ut,hn,r]),ui=i.useCallback(async H=>{try{await I1(H,r),a("Mission started — first slice activated","success"),await Ut(H),hn()}catch(Ne){a(Ce(Ne)||"Failed to start mission","error")}},[a,Ut,hn,r]),ni=i.useCallback(async(H,Ne)=>{try{await T1(H,{enabled:Ne},r),a(Ne?"Autopilot enabled":"Autopilot disabled","success"),await Ut(H),hn()}catch(Je){a(Ce(Je)||"Failed to update autopilot","error")}},[a,Ut,hn,r]),ba=i.useCallback(H=>{Rt("structure"),tn(null),qt(null),te([]),et(0),Gt("all"),pt(new Set),Ut(H.id)},[Ut]),xa=i.useCallback(()=>{x(null),tn(null),qt(null),Rt("structure"),te([]),et(0),Gt("all"),pt(new Set),hn()},[hn]),va=se.length<vt,Ls=g?.autopilotState??"inactive",Wa=Ls==="watching"||Ls==="activating",ya=m4(Ls,g?.lastAutopilotActivityAt),Qi=i.useMemo(()=>!dn||!Zt||!vd(dn)?null:dn.rollup.milestoneId===Zt?dn:null,[Zt,dn]),Tr=i.useMemo(()=>{const H=new Map;for(const Ne of Qi?.validationTelemetry.validationRounds??[]){const Je=H.get(Ne.featureId);(!Je||Ne.startedAt>Je.startedAt)&&H.set(Ne.featureId,Ne)}return H},[Qi]),$r=i.useCallback(()=>{!g||ft||!va||as(g.id,{append:!0})},[ft,va,as,g]),Dr=i.useCallback(H=>{pt(Ne=>{const Je=new Set(Ne);return Je.has(H)?Je.delete(H):Je.add(H),Je})},[]),wa=i.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),Gn())},[Gn]),ka=i.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),Nn())},[Nn]),Li=i.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),ue())},[ue]),Ka=i.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),Wt())},[Wt]),Oi=i.useRef(null);if(i.useEffect(()=>{if(!h)return;const H=Ne=>{Ne.key==="Escape"&&s()};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[h,s]),!h)return null;const ja=()=>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:[Wa&&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:(Kr[g.status]||Kr.planning).bg,color:(Kr[g.status]||Kr.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=>ni(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(is,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),t.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(ml[Ls]||ml.inactive).bg,color:(ml[Ls]||ml.inactive).text},"data-testid":"autopilot-state-badge",children:[Wa&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),Ls]})]}),ya&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:ya})]}),t.jsxs("div",{className:"mission-detail__actions",children:[g.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ti(g.id),title:"Stop mission","aria-label":"Stop mission",children:t.jsx(Mi,{size:14})}),g.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>ga(g.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(ss,{size:14})}),g.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>ui(g.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(ss,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Xn(g),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(Os,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ke({type:"mission",id:g.id}),title:"Delete mission","aria-label":"Delete mission",children:t.jsx(Sn,{size:14})})]})]}),L===g.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:C.title,onChange:H=>$({...C,title:H.target.value}),onKeyDown:wa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:C.description,onChange:H=>$({...C,description:H.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:C.status,onChange:H=>$({...C,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:C.autopilotEnabled,onChange:H=>$({...C,autopilotEnabled:H.target.checked})}),t.jsx(is,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Gn,disabled:V,children:[V?t.jsx(Nt,{size:14,className:"spinner"}):t.jsx(bs,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:vs,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[t.jsx("button",{className:`mission-btn ${bt==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Rt("structure"),role:"tab","aria-selected":bt==="structure","data-testid":"mission-tab-structure",children:"Structure"}),t.jsxs("button",{className:`mission-btn ${bt==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Rt("activity"),role:"tab","aria-selected":bt==="activity","data-testid":"mission-tab-activity",children:["Activity (",vt,")"]})]}),bt==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[g.milestones.map(H=>{const Ne=Qi?.rollup.milestoneId===H.id?Qi:null,Je=Ne?.rollup??mn.get(H.id),Mt=Ne?.validationTelemetry.validationRounds??[],fn=Ne?.fixFeatures??[],en=lf[Je?.state??"not_started"]??lf.not_started,An=Je&&(Je.state==="blocked"||Je.state==="failed")?Ne?.validationTelemetry.validationRounds.find(st=>st.blockedReason)?.blockedReason:void 0;return t.jsxs("div",{className:"mission-milestone",children:[t.jsxs("div",{className:"mission-milestone__header",onClick:()=>Cs(H.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:ne.has(H.id)?t.jsx(un,{size:16}):t.jsx(zn,{size:16})}),t.jsx(Ia,{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:rf[H.status].bg,color:rf[H.status].text},children:H.status}),t.jsxs("span",{className:"mission-milestone__count",children:[H.slices.length," slices"]}),t.jsx(cf,{state:a4(H.interviewState)}),Je&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:en.bg,color:en.text},title:"Validation state",children:df(Je.state)}),Je.totalAssertions>0&&t.jsx("div",{className:"mission-milestone__coverage-bar",title:`${Je.passedAssertions??0} of ${Je.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${(Je.passedAssertions??0)/Je.totalAssertions*100}%`,backgroundColor:(Je.passedAssertions??0)===Je.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),H.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>ht({type:"milestone",id:H.id,title:H.title}),title:"Plan milestone","aria-label":"Plan milestone",children:t.jsx(oa,{size:14})}),t.jsxs("div",{className:"mission-milestone__actions",onClick:st=>st.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>Es(H.id),title:"Add slice",children:t.jsx(Cn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>En(H),title:"Edit milestone",children:t.jsx(Os,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ke({type:"milestone",id:H.id}),title:"Delete milestone",children:t.jsx(Sn,{size:14})})]})]}),ne.has(H.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(Se||D===H.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:G.title,onChange:st=>he({...G,title:st.target.value}),onKeyDown:ka,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:G.description,onChange:st=>he({...G,description:st.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Nn,disabled:V,children:[V?t.jsx(Nt,{size:14,className:"spinner"}):t.jsx(bs,{size:14}),D?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ps,children:"Cancel"})]})]}),Ne&&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:[Ne.validationTelemetry.totalRuns," rounds",Ne.validationTelemetry.lastValidatorStatus?` · Last ${Ne.validationTelemetry.lastValidatorStatus}`:""]})]}),An&&t.jsxs("div",{className:"mission-blocked-reason",children:[t.jsx("strong",{children:"Blocked reason:"})," ",An]}),Mt.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:()=>$e(st=>!st),title:ke?"Hide validation rounds":"Show validation rounds",children:[ke?t.jsx(un,{size:12}):t.jsx(zn,{size:12}),"Validation rounds (",Mt.length,")"]}),ke&&t.jsx("div",{className:"mission-validation-rounds__list",children:Mt.map(st=>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--${st.validatorStatus}`,children:st.validatorStatus}),t.jsx("span",{className:"mission-validation-round__feature",children:st.featureTitle}),t.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",st.implementationAttempt," · reviewer #",st.validatorAttempt]})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),st.failedAssertionIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:st.failedAssertionIds.map(Ze=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ma(Ze),title:`Jump to assertion ${Ze}`,children:Ze},`${st.roundId}-${Ze}`))}):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:"}),st.generatedFixFeatureIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:st.generatedFixFeatureIds.map(Ze=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Di(Ze),title:`Jump to fix feature ${Ze}`,children:Ze},`${st.roundId}-${Ze}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),st.blockedReason&&t.jsx("div",{className:"mission-validation-round__blocked-reason",children:st.blockedReason})]},st.roundId))})]}),fn.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:fn.map(st=>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:()=>Di(st.id),title:`Jump to feature ${st.id}`,children:st.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:ul[st.status].bg,color:ul[st.status].text},children:st.status}),st.loopState&&t.jsx("span",{className:`mission-loop-state mission-loop-state--${st.loopState}`,children:st.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:()=>Di(st.sourceFeatureId),title:`Jump to source feature ${st.sourceFeatureId}`,children:st.sourceFeatureId}),t.jsx("span",{children:"Run:"}),t.jsx("span",{className:"mission-fix-feature__run",children:st.runId})]}),st.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:st.failedAssertionIds.map(Ze=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ma(Ze),title:`Jump to assertion ${Ze}`,children:Ze},`${st.id}-${Ze}`))})]})]},st.id))})]})]}),t.jsxs("div",{className:"mission-slices",children:[H.slices.map(st=>t.jsxs("div",{className:"mission-slice",children:[t.jsxs("div",{className:"mission-slice__header",onClick:()=>ge(st.id),children:[t.jsx("button",{className:"mission-slice__expand",children:A.has(st.id)?t.jsx(un,{size:16}):t.jsx(zn,{size:16})}),t.jsx(Vd,{size:16,className:"mission-slice__icon"}),t.jsx("span",{className:"mission-slice__title",children:st.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:of[st.status].bg,color:of[st.status].text},children:st.status}),t.jsxs("span",{className:"mission-slice__count",children:[st.features?.length||0," features"]}),t.jsx(cf,{state:st.planState??"not_started"}),st.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>ht({type:"slice",id:st.id,title:st.title}),title:"Plan slice","aria-label":"Plan slice",children:t.jsx(oa,{size:14})}),t.jsxs("div",{className:"mission-slice__actions",onClick:Ze=>Ze.stopPropagation(),children:[st.status==="pending"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>z(st.id),title:"Activate slice",children:t.jsx(ss,{size:14})}),st.status==="active"&&st.features?.some(Ze=>Ze.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>xn(st.id),title:"Triage all features",disabled:V,children:V?t.jsx(Nt,{size:14,className:"spinner"}):t.jsx(is,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>xe(st.id),title:"Add feature",children:t.jsx(Cn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Q(st),title:"Edit slice",children:t.jsx(Os,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ke({type:"slice",id:st.id}),title:"Delete slice",children:t.jsx(Sn,{size:14})})]})]}),A.has(st.id)&&t.jsxs("div",{className:"mission-slice__body",children:[ee&&K===H.id&&!ce&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:X.title,onChange:Ze=>Z({...X,title:Ze.target.value}),onKeyDown:Li,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:X.description,onChange:Ze=>Z({...X,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:ue,disabled:V,children:[V?t.jsx(Nt,{size:14,className:"spinner"}):t.jsx(bs,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:M,children:"Cancel"})]})]}),ce===st.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:X.title,onChange:Ze=>Z({...X,title:Ze.target.value}),onKeyDown:Li,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:X.description,onChange:Ze=>Z({...X,description:Ze.target.value}),rows:2}),t.jsxs("select",{value:X.status,onChange:Ze=>Z({...X,status:Ze.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:ue,disabled:V,children:[V?t.jsx(Nt,{size:14,className:"spinner"}):t.jsx(bs,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:M,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-features",children:[st.features?.map(Ze=>t.jsxs("div",{className:"mission-feature","data-mission-feature-id":Ze.id,children:[t.jsxs("div",{className:"mission-feature__header",children:[t.jsx("button",{className:"mission-feature__expand",onClick:()=>qa(Ze.id),title:At===Ze.id?"Collapse details":"Expand to show run history",children:At===Ze.id?t.jsx(un,{size:14}):t.jsx(zn,{size:14})}),t.jsx(zd,{size:14,className:"mission-feature__icon"}),t.jsx("span",{className:"mission-feature__title",children:Ze.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:ul[Ze.status].bg,color:ul[Ze.status].text},children:Ze.status}),Ze.loopState&&Ze.loopState!=="idle"&&t.jsxs("span",{className:`mission-loop-state mission-loop-state--${Ze.loopState}`,title:`Loop state: ${Ze.loopState}`,children:[Ze.loopState==="implementing"&&"⏳",Ze.loopState==="validating"&&"🔄",Ze.loopState==="needs_fix"&&"🔧",Ze.loopState==="passed"&&"✅",Ze.loopState==="blocked"&&"🚫"]}),Ze.generatedFromFeatureId&&t.jsx("button",{className:"mission-feature__lineage",onClick:()=>Di(Ze.generatedFromFeatureId),title:`Generated from feature: ${Ze.generatedFromFeatureId}`,children:"🔗 Fix"}),(Ze.loopState==="validating"||Ze.loopState==="needs_fix")&&(()=>{const Ft=We.get(Ze.id),ln=Tr.get(Ze.id),Ks=Ft?.implementationAttemptCount??ln?.implementationAttempt??Ze.implementationAttemptCount??0,mi=Ft?.retryBudgetRemaining??Math.max(0,i4-Ks);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",Ks," · ",mi," ",mi===1?"retry":"retries"," left"]})})(),Ze.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>Ha(Ze.id),title:"Validate feature",disabled:Ye.has(Ze.id),children:Ye.has(Ze.id)?t.jsx(Nt,{size:14,className:"spinner"}):t.jsx(xs,{size:14})}),Ze.taskId&&t.jsx("span",{className:"mission-feature__task-link",onClick:()=>o?.(Ze.taskId),title:"Click to view task",children:Ze.taskId}),t.jsxs("div",{className:"mission-feature__actions",children:[Ze.status==="defined"&&!Ze.taskId&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Un(Ze.id),title:"Triage — create task",disabled:V||Ge===Ze.id,children:Ge===Ze.id?t.jsx(Nt,{size:14,className:"spinner"}):t.jsx(is,{size:14})}),Ze.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>Zn(Ze.id),title:"Unlink task",children:t.jsx(vm,{size:14})}):Ze.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>qe(Ze.id),title:"Link to task",children:t.jsx(pr,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>dt(Ze),title:"Edit feature",children:t.jsx(Os,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ke({type:"feature",id:Ze.id}),title:"Delete feature",children:t.jsx(Sn,{size:14})})]})]}),Ze.description&&t.jsx("p",{className:"mission-feature__description",children:Ze.description}),Ze.acceptanceCriteria&&t.jsxs("p",{className:"mission-feature__criteria",children:[t.jsx("strong",{children:"Acceptance:"})," ",Ze.acceptanceCriteria]}),yt?.featureId===Ze.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:yt.enrichedDescription}),t.jsxs("div",{className:"mission-triage-preview__actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:rs,disabled:V,children:[V?t.jsx(Nt,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:ts,disabled:V,children:"Cancel"})]})]}),pe===Ze.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:B.title,onChange:Ft=>we({...B,title:Ft.target.value}),onKeyDown:Ka,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:B.description,onChange:Ft=>we({...B,description:Ft.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:B.acceptanceCriteria,onChange:Ft=>we({...B,acceptanceCriteria:Ft.target.value}),rows:2}),t.jsxs("select",{value:B.status,onChange:Ft=>we({...B,status:Ft.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:Wt,disabled:V,children:[V?t.jsx(Nt,{size:14,className:"spinner"}):t.jsx(bs,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Tt,children:"Cancel"})]})]}),At===Ze.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"})}),(zt.get(Ze.id)??[]).map(Ft=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>Va(Ft.id),children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${Ft.status}`,title:Ft.status,children:Ft.status}),t.jsx("span",{className:"mission-run__time",children:new Date(Ft.startedAt).toLocaleString()}),Ft.completedAt&&t.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(Ft.completedAt).getTime()-new Date(Ft.startedAt).getTime())/1e3),"s"]}),Ft.triggerType&&t.jsx("span",{className:"mission-run__trigger",children:Ft.triggerType}),t.jsx("button",{className:"mission-icon-btn",title:Ot===Ft.id?"Hide details":"Show details",children:Ot===Ft.id?t.jsx(un,{size:12}):t.jsx(zn,{size:12})})]}),Ot===Ft.id&&Yt.get(Ft.id)&&t.jsxs("div",{className:"mission-run__details",children:[Ft.summary&&t.jsx("p",{className:"mission-run__summary",children:Ft.summary}),Ft.blockedReason&&t.jsxs("p",{className:"mission-run__blocked-reason",children:[t.jsx("strong",{children:"Blocked:"})," ",Ft.blockedReason]}),Yt.get(Ft.id)?.failures&&Yt.get(Ft.id).failures.length>0&&t.jsxs("div",{className:"mission-run__failures",children:[t.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),Yt.get(Ft.id).failures.map(ln=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:ln.message}),ln.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",ln.expected]}),ln.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",ln.actual]})]},ln.id))]}),(!Yt.get(Ft.id)?.failures||Yt.get(Ft.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},Ft.id)),(!zt.get(Ze.id)||zt.get(Ze.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},Ze.id)),ze&&He===st.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:B.title,onChange:Ze=>we({...B,title:Ze.target.value}),onKeyDown:Ka,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:B.description,onChange:Ze=>we({...B,description:Ze.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:B.acceptanceCriteria,onChange:Ze=>we({...B,acceptanceCriteria:Ze.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Wt,disabled:V,children:[V?t.jsx(Nt,{size:14,className:"spinner"}):t.jsx(bs,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Tt,children:"Cancel"})]})]}),!ze&&(!st.features||st.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(zd,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},st.id)),H.slices.length===0&&!ee&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Vd,{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"}),Je&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:en.bg,color:en.text},children:df(Je.state)}),Je&&Je.totalAssertions>0&&t.jsx("div",{className:"mission-assertions__coverage-bar",title:`${Je.passedAssertions??0} of ${Je.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${(Je.passedAssertions??0)/Je.totalAssertions*100}%`,backgroundColor:(Je.passedAssertions??0)===Je.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>{Ie(!0),St(null),kt({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx(Cn,{size:14})})]}),It&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:ye.title,onChange:st=>kt({...ye,title:st.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:ye.assertion,onChange:st=>kt({...ye,assertion:st.target.value}),rows:2}),t.jsxs("select",{value:ye.status,onChange:st=>kt({...ye,status:st.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:()=>ws(H.id),disabled:V,children:[V?t.jsx(Nt,{size:14,className:"spinner"}):t.jsx(bs,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:es,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(je.get(H.id))?je.get(H.id):[]).map(st=>t.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":st.id,children:[t.jsx("div",{className:"mission-assertion__header",children:Be===st.id?t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:ye.title,onChange:Ze=>kt({...ye,title:Ze.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:ye.assertion,onChange:Ze=>kt({...ye,assertion:Ze.target.value}),rows:2}),t.jsxs("select",{value:ye.status,onChange:Ze=>kt({...ye,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:()=>Bs(st.id,H.id),disabled:V,children:[V?t.jsx(Nt,{size:14,className:"spinner"}):t.jsx(bs,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:es,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(hl[st.status]??hl.pending).bg,color:(hl[st.status]??hl.pending).text},children:st.status}),t.jsx("span",{className:"mission-assertion__title",children:st.title}),(()=>{const Ft=gt.get(st.id)?.length??0;return Ft>0?t.jsxs("span",{className:"mission-assertion__linked-count",title:`${Ft} linked feature${Ft!==1?"s":""}`,children:["(",Ft," linked)"]}):null})(),t.jsx("button",{className:"mission-icon-btn",onClick:()=>wn(st.id),title:"Toggle details",children:be===st.id?t.jsx(un,{size:14}):t.jsx(zn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ns(st),title:"Edit assertion",children:t.jsx(Os,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ke({type:"assertion",id:st.id}),title:"Delete assertion",children:t.jsx(Sn,{size:14})})]})}),be===st.id&&t.jsxs("div",{className:"mission-assertion__body",children:[t.jsx("p",{className:"mission-assertion__text",children:st.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()=>{be!==st.id&&await wn(st.id),Xt(pn===st.id?null:st.id)},title:"Link a feature",children:[t.jsx(pr,{size:12}),"Link Feature"]})]}),pn===st.id&&t.jsx("div",{className:"mission-assertion__feature-picker",children:t.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const Ze=new Set((gt.get(st.id)??[]).map(ln=>ln.id)),Ft=[];return g?.milestones.forEach(ln=>ln.slices.forEach(Ks=>Ft.push(...Ks.features.filter(mi=>!Ze.has(mi.id))))),Ft.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):Ft.map(ln=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>ha(ln.id,st.id),disabled:jt.has(st.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:ln.title}),jt.has(st.id)&&t.jsx(Nt,{size:12,className:"spinner"})]},ln.id))})()})}),(()=>{const Ze=gt.get(st.id)??[];return Ze.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):Ze.map(Ft=>{const ln=`${Ft.id}-${st.id}`,Ks=Jt.has(ln);return t.jsxs("div",{className:"mission-assertion__linked-feature",children:[t.jsx("span",{className:"mission-assertion__linked-feature-title",children:Ft.title}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>pa(Ft.id,st.id),disabled:Ks,title:"Unlink feature",children:Ks?t.jsx(Nt,{size:12,className:"spinner"}):t.jsx(vm,{size:12})})]},Ft.id)})})()]})]})]},st.id)),(!je.get(H.id)||je.get(H.id)?.length===0)&&!It&&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&&!Se&&D===null&&t.jsxs("button",{className:"mission-add-btn",onClick:Ln,children:[t.jsx(Cn,{size:16}),"Add Milestone"]}),Se&&D===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:G.title,onChange:H=>he({...G,title:H.target.value}),onKeyDown:ka,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:G.description,onChange:H=>he({...G,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:Nn,disabled:V,children:[V?t.jsx(Nt,{size:14,className:"spinner"}):t.jsx(bs,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ps,children:"Cancel"})]})]}),g.milestones.length===0&&!Se&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Ia,{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:_t,onChange:H=>Gt(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:[se.length," of ",vt]})]}),!ft&&va&&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:$r,"data-testid":"mission-activity-load-more",children:"Load more"})}),ft?t.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[t.jsx(Nt,{size:18,className:"spinner"}),t.jsx("span",{children:"Loading mission activity..."})]}):se.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:gn,className:"mission-events","data-testid":"mission-activity-events",children:[se.map(H=>{const Ne=!!(H.metadata&&Object.keys(H.metadata).length>0),Je=ae.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 ${d4(H.eventType)}`,children:u4(H.eventType)}),t.jsx("span",{className:"mission-event__time",children:Vl(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()}),Ne&&t.jsxs("div",{className:"mission-event__metadata",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>Dr(H.id),"data-testid":`mission-event-metadata-${H.id}`,children:[Je?"Hide":"Show"," metadata"]}),Je&&t.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(H.metadata,null,2)})]})]},H.id)}),t.jsx("div",{ref:us})]})]})]}):null,Ga=()=>f.map(H=>{const Ne=H,Je=g?.id===Ne.id,Mt=Kr[Ne.status]||{bg:"",text:""},fn=Ne.summary,en=_e.get(Ne.id),An=o4(en),st=!!(fn&&(fn.totalMilestones>0||fn.totalFeatures>0)),Ze=en?.totalTasks??0,Ft=en?.tasksCompleted??0,ln=en?.tasksFailed??0,Ks=en?.estimatedCompletionPercent??fn?.progressPercent??0,mi=st||Ze>0||ln>0||!!en?.lastActivityAt;return t.jsxs("div",{className:`mission-list__item ${Je?"mission-list__item--selected":""}`,onClick:()=>ba(H),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(js,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:Ne.title})]}),t.jsxs("div",{className:"mission-list__item-tags",children:[H.autopilotEnabled&&t.jsx("span",{title:"Autopilot enabled",children:t.jsx(is,{size:12,className:"mission-list__item-autopilot-icon"})}),t.jsx("span",{className:`mission-health-badge mission-health-badge--${An}`,"data-testid":`mission-health-badge-${Ne.id}`,"aria-label":`Mission health: ${An}`}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Mt.bg,color:Mt.text},children:Ne.status})]}),Ne.description&&t.jsx("p",{className:"mission-list__item-description",children:Ne.description}),mi&&t.jsxs("div",{className:"mission-list__item-summary",children:[st&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[fn.completedMilestones,"/",fn.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[fn.completedFeatures,"/",fn.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${Ne.id}`,children:[Ft,"/",Ze," tasks"]}),ln>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:ls=>{ls.stopPropagation(),ba(H)},"data-testid":`mission-failed-${Ne.id}`,title:"View mission failures",children:[ln," failed"]}),t.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${An}`,children:t.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${Ks}%`}})})]}),mi&&t.jsx("div",{className:"mission-list__item-activity",children:t.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${Ne.id}`,children:["Activity ",Vl(en?.lastActivityAt)]})})]}),t.jsxs("div",{className:"mission-list__item-actions",onClick:ls=>ls.stopPropagation(),children:[Ne.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ti(Ne.id),title:"Stop mission",children:t.jsx(Mi,{size:14})}),Ne.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>ga(Ne.id),title:"Resume mission",children:t.jsx(ss,{size:14})}),Ne.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>ui(Ne.id),title:"Start mission",children:t.jsx(ss,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Xn(H),title:"Edit mission",children:t.jsx(Os,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ke({type:"mission",id:Ne.id}),title:"Delete mission",children:t.jsx(Sn,{size:14})})]})]},Ne.id)}),Na=({hideBottomButtons:H=!1}={})=>{const Ne=k&&f.length>0&&!_,Je=!H&&!Ne;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:C.title,onChange:Mt=>$({...C,title:Mt.target.value}),onKeyDown:wa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:C.description,onChange:Mt=>$({...C,description:Mt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Gn,disabled:V,children:[V?t.jsx(Nt,{size:14,className:"spinner"}):t.jsx(bs,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:vs,children:"Cancel"})]})]}),Ne&&t.jsx("div",{className:"mission-list__top-action",children:t.jsxs("button",{className:"btn btn-sm btn-task-create mission-list__primary-cta",onClick:()=>ct(!0),children:[t.jsx(xs,{size:14}),"Plan New Mission"]})}),Ga(),L&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:C.title,onChange:Mt=>$({...C,title:Mt.target.value}),onKeyDown:wa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:C.description,onChange:Mt=>$({...C,description:Mt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:C.status,onChange:Mt=>$({...C,status:Mt.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:C.autopilotEnabled,onChange:Mt=>$({...C,autopilotEnabled:Mt.target.checked})}),t.jsx(is,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Gn,disabled:V,children:[V?t.jsx(Nt,{size:14,className:"spinner"}):t.jsx(bs,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:vs,children:"Cancel"})]})]}),f.length===0&&!_&&t.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large mission-manager__empty--mission",children:[t.jsx(js,{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:()=>ct(!0),children:[t.jsx(xs,{size:14}),"Plan New Mission"]})]}),!_&&t.jsxs("div",{className:"mission-list__footer",children:[Ve.length>0&&t.jsxs("div",{className:"mission-resume-prompt",children:[t.jsx(Ts,{size:16}),t.jsx("span",{children:Ve.length===1?`Resume "${Ve[0].title}"?`:`${Ve.length} interview sessions pending`}),t.jsx("div",{className:"mission-list__resume-actions",children:Ve.map(Mt=>t.jsxs("button",{className:"mission-add-btn",onClick:()=>{Me(Mt.id),ct(!0),me([])},children:[Mt.status==="error"?t.jsx(fs,{size:14}):t.jsx(xs,{size:14}),Mt.status==="error"?"Retry":"Resume"]},Mt.id))})]}),Je&&t.jsx("div",{className:"mission-list__footer-actions",children:t.jsxs("button",{className:"mission-add-btn",onClick:()=>ct(!0),children:[t.jsx(xs,{size:16}),"Plan New Mission"]})})]})]})},Ni=()=>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 ",ie?.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()=>{ie&&(ie.type==="mission"?await hs(ie.id):ie.type==="milestone"?await As(ie.id):ie.type==="slice"?await Ee(ie.id):ie.type==="feature"&&await bn(ie.id))},children:"Delete"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>Ke(null),children:"Cancel"})]})]})}),Qe=()=>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=>De(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:()=>De(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:Mn,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{qe(null),De("")},children:"Cancel"})]})]})}),Dt=t.jsxs("div",{ref:Oi,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:xa,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(Zl,{size:18})}),t.jsx(js,{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(an,{size:18})})]}),k?t.jsxs("div",{className:"mission-manager__body mission-manager__body--stacked",children:[w?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(Nt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(Nt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?ja():Na(),ie&&Ni(),tt&&Qe()]}):t.jsxs("div",{className:"mission-manager__split",children:[t.jsxs("aside",{className:"mission-manager__sidebar","data-testid":"mission-sidebar","aria-label":"Mission list",style:k?void 0:{width:`${E}px`},children:[t.jsx("div",{className:"mission-manager__sidebar-list",children:w?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(Nt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):Na({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:()=>ct(!0),title:"Plan New Mission","aria-label":"Plan New Mission",children:[t.jsx(xs,{size:14}),"Plan New Mission"]})})]}),!k&&t.jsx("div",{className:"mission-manager__sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":cl,"aria-valuemax":dl,"aria-valuenow":E,"aria-label":"Resize mission sidebar",tabIndex:0,onPointerDown:P,onKeyDown:F}),t.jsxs("div",{className:"mission-manager__detail-pane",children:[v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(Nt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?ja():t.jsxs("div",{className:"mission-manager__detail-pane-empty","data-testid":"mission-empty-detail",children:[t.jsx(js,{size:32}),t.jsx("span",{children:"Select a mission to view details"})]}),ie&&Ni(),tt&&Qe()]})]})]}),on=t.jsx(WT,{isOpen:Te,onClose:()=>ct(!1),onMissionCreated:()=>{hn(),a("Mission created from AI interview","success")},projectId:r,resumeSessionId:Xe}),os=rt?t.jsx(t4,{isOpen:!0,onClose:()=>ht(null),onApplied:()=>{ht(null),g&&Ut(g.id)},targetType:rt.type,targetId:rt.id,targetTitle:rt.title,missionContext:g?.title,projectId:r,resumeSessionId:rt.resumeSessionId}):null;return n?t.jsxs(t.Fragment,{children:[Dt,on,os]}):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:Dt}),on,os]})}const p4={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})},hf=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(wi,{remarkPlugins:[ki],components:p4,children:n})})}),pl=2e3;function pf({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),[v,N]=i.useState(null),k=i.useRef(null),E=i.useMemo(()=>s.find(U=>U.id===d),[s,d]),y=i.useMemo(()=>e?s.find(U=>U.id===e.id):void 0,[s,e]),j=m==="agent",P=j&&E?.runtimeConfig?.messageResponseMode==="immediate",F=j&&(g||P),_=d.trim()!==""&&f.trim().length>0&&f.length<=pl,R=i.useCallback(async()=>{if(!(!_||w)){b(!0),N(null);try{const U=m==="agent"?"user-to-agent":"system",C=n?{replyTo:{messageId:n.messageId}}:void 0,$=F;await o0({toId:d.trim(),toType:m,content:f.trim(),type:U,...C?{metadata:C}:{},...$?{wakeImmediately:!0}:{}},a),r()}catch(U){const C=Ce(U)||"Failed to send message";N(C),l?.(C,"error")}finally{b(!1)}}},[_,w,d,m,f,F,n,a,r,l]),L=i.useCallback(U=>{u(U),h("agent")},[]);return i.useEffect(()=>{n&&k.current?.focus()},[n]),i.useEffect(()=>{if(!n||typeof window>"u"||window.visualViewport==null)return;const U=()=>{k.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(an,{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=>L(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(Vn,{size:14}),y?.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:k,className:"message-composer-textarea",placeholder:"Type your message…",value:f,onChange:U=>p(U.target.value),maxLength:pl,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>pl?"over-limit":"",children:[f.length,"/",pl]})})]}),j&&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:P,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:P?"(agent is already set to immediate response mode)":"(one-off override for this message only)"})]})]})}),v&&t.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[t.jsx(Ts,{size:14}),t.jsx("span",{children:v})]})]}),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:R,disabled:!_||w,"data-testid":"message-composer-send",children:w?t.jsxs(t.Fragment,{children:[t.jsx(Nt,{size:14,className:"spin"}),t.jsx("span",{children:"Sending…"})]}):t.jsxs(t.Fragment,{children:[t.jsx(Aa,{size:14}),t.jsx("span",{children:"Send"})]})})]})]})}const Wl=280,fu=.65,yd=16,ff=320;function gu(e){return Math.max(Wl,e*fu)}function wd(e,n){const s=gu(n);return Math.min(Math.max(e,Wl),s)}function gf(e){try{const n=Fn("kb-dashboard-mailbox-sidebar-width",e);if(!n)return ff;const s=Number(n);if(Number.isFinite(s)&&s>0)return s}catch{}return ff}function ta(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 f4(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 g4(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 bf(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function xf(){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 fl(e){return`mailbox-list-message-${e}`}function kd(e){return`mailbox-detail-message-${e}`}function b4(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 x4({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,v]=i.useState(!1),[N,k]=i.useState(null),[E,y]=i.useState(null),[j,P]=i.useState(null),[F,_]=i.useState("inbox"),[R,L]=i.useState(null),[U,C]=i.useState([]),[$,V]=i.useState("pending"),[Y,ne]=i.useState([]),[q,A]=i.useState(0),[I,D]=i.useState(null),[S,G]=i.useState(""),[he,Se]=i.useState(!1),Ue=i.useMemo(()=>new Map(U.map(ie=>[ie.id,ie.name??""])),[U]),ce=i.useCallback((ie,Ke)=>f4(ie,Ke,Ue),[Ue]),X=Zs()==="mobile",Z=!X,[ee,le]=i.useState(()=>gf(e)),K=i.useRef(null),{keyboardOverlap:O,viewportHeight:pe,viewportOffsetTop:ve,keyboardOpen:B}=Yi({enabled:X}),we=i.useMemo(()=>{if(B)return{"--keyboard-overlap":`${O}px`,"--vv-offset-top":`${ve}px`,...pe!=null?{"--vv-height":`${pe}px`}:{}}},[B,O,pe,ve]);i.useEffect(()=>{le(gf(e))},[e]),i.useEffect(()=>{if(!Z)return;const ie=K.current?.clientWidth;ie&&le(Ke=>wd(Ke,ie))},[Z]),i.useEffect(()=>{if(Z)try{ds("kb-dashboard-mailbox-sidebar-width",String(ee),e)}catch{}},[Z,e,ee]);const ze=i.useCallback(ie=>{if(!Z)return;ie.preventDefault();const Ke=K.current;if(!Ke)return;const je=Ke.getBoundingClientRect(),Fe=St=>{const ye=St.clientX-je.left;le(wd(ye,je.width))},Be=()=>{window.removeEventListener("mousemove",Fe),window.removeEventListener("mouseup",Be)};window.addEventListener("mousemove",Fe),window.addEventListener("mouseup",Be)},[Z]),re=i.useCallback(ie=>{if(!Z)return;const Ke=K.current?.clientWidth??0,je=ee/fu+yd,Fe=Math.max(Ke,je),Be=gu(Fe);if(ie.key==="ArrowLeft"||ie.key==="ArrowRight"){ie.preventDefault();const St=ie.key==="ArrowLeft"?-yd:yd;le(ye=>wd(ye+St,Fe));return}if(ie.key==="Home"){ie.preventDefault(),le(Wl);return}ie.key==="End"&&(ie.preventDefault(),le(Be))},[Z,ee]),He=i.useCallback(async()=>{f(!0);try{const ie=await a0({limit:50},e);l(ie),m(ie.unreadCount),s?.(ie.unreadCount)}catch{}finally{f(!1)}},[e,s]),Pe=i.useCallback(async()=>{f(!0);try{const ie=await r0({limit:50},e);d(ie)}catch{}finally{f(!1)}},[e]),tt=i.useCallback(async ie=>{f(!0);try{const Ke=await m0(ie,e);L(Ke)}catch{}finally{f(!1)}},[e]),qe=i.useCallback(async()=>{try{const ie=await Mr(void 0,e);C(ie)}catch{}},[e]),de=i.useCallback(async()=>{try{const ie=await rb(e);m(ie.unreadCount),s?.(ie.unreadCount)}catch{}},[e,s]),De=i.useCallback(async ie=>{f(!0);try{const Ke=await Go({status:ie==="pending"?"pending":void 0,limit:100},e);if(ie==="pending")ne(Ke.requests);else{const[je,Fe,Be]=await Promise.all([Go({status:"approved",limit:100},e),Go({status:"denied",limit:100},e),Go({status:"completed",limit:100},e)]);ne([...je.requests,...Fe.requests,...Be.requests].sort((St,ye)=>ye.updatedAt.localeCompare(St.updatedAt)))}A(Ke.pendingCount)}catch{}finally{f(!1)}},[e]);i.useEffect(()=>{a==="inbox"?He():a==="outbox"?Pe():a==="agents"?qe():a==="approvals"&&De($)},[a,He,Pe,qe,De,$]),i.useEffect(()=>{j&&tt(j)},[j,tt]),i.useEffect(()=>{de()},[de]),i.useEffect(()=>{qe()},[qe]),i.useEffect(()=>{if(typeof EventSource>"u")return;const ie=e?`?projectId=${encodeURIComponent(e)}`:"",Ke=()=>{de(),a==="inbox"?He():a==="outbox"?Pe():a==="approvals"&&De($),j&&tt(j)};return li(`/api/events${ie}`,{events:{"message:sent":Ke,"message:received":Ke,"message:read":Ke,"message:deleted":Ke,"approval:requested":Ke,"approval:updated":Ke,"approval:decided":Ke}})},[e,a,j,de,He,Pe,tt,De,$]);const Te=i.useCallback(async ie=>{if(g(ie),!ie.read&&a==="inbox")try{const Ke=await l0(ie.id,e);Ke&&l(Fe=>Fe&&{...Fe,messages:Fe.messages.map(Be=>Be.id===Ke.id?Ke:Be),unreadCount:Math.max(0,Fe.unreadCount-1)});const je=Math.max(0,u-1);m(je),s?.(je)}catch{}try{const Ke=await u0(ie.fromId,ie.fromType,e);w(Ke)}catch{w([ie])}},[e,u,s,a]);i.useEffect(()=>{const ie=xf();if(!ie)return;const Ke=[...o?.messages??[],...c?.messages??[],...R?.inbox??[],...R?.outbox??[],...x].find(je=>je.id===ie);Ke&&Te(Ke)},[o,c,R,x,Te]),i.useEffect(()=>{const ie=xf();if(!ie)return;const Ke=document.getElementById(kd(ie));if(!Ke)return;Ke.scrollIntoView({behavior:"smooth",block:"center"}),Ke.classList.add("mailbox-message-highlight");const je=window.setTimeout(()=>{Ke.classList.remove("mailbox-message-highlight")},2e3);return()=>{window.clearTimeout(je)}},[p,x]);const ct=i.useCallback(()=>{g(null),w([])},[]),Ve=i.useCallback(async()=>{try{const ie=await c0(e);m(0),s?.(0),l(Ke=>Ke&&{...Ke,messages:Ke.messages.map(je=>({...je,read:!0})),unreadCount:0}),n?.(`Marked ${ie.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[e,n,s]),me=i.useCallback(async ie=>{try{await d0(ie,e),g(null),w([]),a==="inbox"?He():a==="outbox"?Pe():j&&tt(j),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,a,j,He,Pe,tt,n]),oe=i.useCallback(ie=>{k({id:ie.fromId,type:ie.fromType}),y({messageId:ie.id,preview:bf(ie.content,120)}),v(!0)},[]),Me=i.useCallback(()=>{v(!1),k(null),y(null),n?.("Message sent","success"),a==="outbox"?Pe():a==="agents"&&j&&tt(j),de()},[a,Pe,j,tt,n,de]),Xe=i.useCallback(()=>{k(a==="agents"&&j?{id:j,type:"agent"}:null),y(null),v(!0)},[a,j]),rt=i.useCallback(()=>{v(!1),k(null),y(null)},[]),ht=i.useCallback(async ie=>{try{const Ke=await Wm(ie.id,e);D(Ke),G("")}catch{n?.("Failed to load approval request","error")}},[e,n]),yt=i.useCallback(async ie=>{if(!(!I||he)){Se(ie);try{await h0(I.id,{decision:ie,comment:S||void 0},e),await De($);const Ke=await Wm(I.id,e);D(Ke),G(""),n?.(`Request ${ie==="approve"?"approved":"denied"}`,"success")}catch{n?.("Failed to submit decision","error")}finally{Se(!1)}}},[I,he,S,e,De,$,n]),Re=()=>{if(!p||b)return null;const ie=b4(x,p);return t.jsxs("div",{className:"mailbox-message-detail","data-testid":"mailbox-message-detail",id:kd(p.id),children:[t.jsxs("div",{className:"mailbox-message-detail-header",children:[X&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:ct,"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:g4(p.type)}),t.jsx("span",{className:"mailbox-message-time",children:ta(p.createdAt)})]}),t.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>oe(p),"data-testid":"mailbox-reply",children:[t.jsx(qi,{size:14}),t.jsx("span",{children:"Reply"})]}),t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>me(p.id),"data-testid":"mailbox-delete",children:[t.jsx(Sn,{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(Vn,{size:14}):t.jsx(Xa,{size:14}),ce(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(Vn,{size:14}):t.jsx(Xa,{size:14}),ce(p.toId,p.toType)]})]})]}),ie.length>1&&t.jsxs("div",{className:"mailbox-conversation","data-testid":"mailbox-conversation",children:[t.jsx("div",{className:"mailbox-conversation-label",children:"Conversation"}),ie.map(Ke=>{const je=Ke.metadata?.replyTo?.messageId,Fe=je?ie.find(Be=>Be.id===je):void 0;return t.jsxs("div",{id:kd(Ke.id),className:`mailbox-conversation-msg ${Ke.id===p.id?"current":""}`,children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:ce(Ke.fromId,Ke.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:ta(Ke.createdAt)})]}),je&&t.jsxs("div",{className:"mailbox-reply-context-static","data-testid":`mailbox-reply-context-${Ke.id}`,children:["↪ Replying to ",Fe?bf(Fe.content,60):`message ${je}`]}),t.jsx(hf,{content:Ke.content,className:"mailbox-conversation-msg-body"})]},Ke.id)})]}),ie.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(hf,{content:p.content,className:"mailbox-message-body",testId:"mailbox-message-body"})]})]})},Ge=()=>t.jsxs(t.Fragment,{children:[a==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!o&&t.jsx(jd,{}),o&&o.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[t.jsx(Ma,{size:32}),t.jsx("p",{children:"No messages in your inbox"})]}),o?.messages.map(ie=>t.jsxs("div",{id:fl(ie.id),className:`mailbox-item ${ie.read?"":"unread"}`,onClick:()=>Te(ie),"data-testid":`mailbox-item-${ie.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ie.fromType==="agent"?t.jsx(Vn,{size:16}):t.jsx(Xa,{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:ce(ie.fromId,ie.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:ta(ie.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ie.content.slice(0,80),ie.content.length>80?"…":""]})]}),!ie.read&&t.jsx("div",{className:"mailbox-item-unread-dot","data-testid":`mailbox-unread-dot-${ie.id}`})]},ie.id))]}),a==="outbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!c&&t.jsx(jd,{}),c&&c.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[t.jsx(Aa,{size:32}),t.jsx("p",{children:"No sent messages"})]}),c?.messages.map(ie=>t.jsxs("div",{id:fl(ie.id),className:"mailbox-item",onClick:()=>Te(ie),"data-testid":`mailbox-item-${ie.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ie.toType==="agent"?t.jsx(Vn,{size:16}):t.jsx(Xa,{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: ",ce(ie.toId,ie.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:ta(ie.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ie.content.slice(0,80),ie.content.length>80?"…":""]})]})]},ie.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 ${$==="pending"?"active":""}`,onClick:()=>{V("pending"),D(null)},"data-testid":"mailbox-approval-filter-pending",children:"Pending"}),t.jsx("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${$==="history"?"active":""}`,onClick:()=>{V("history"),D(null)},"data-testid":"mailbox-approval-filter-history",children:"History"})]}),t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-approval-list",children:[Y.length===0&&!h&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-approval-empty",children:[t.jsx(Ma,{size:32}),t.jsx("p",{children:$==="pending"?"No pending approvals":"No historical approvals"})]}),Y.map(ie=>t.jsxs("div",{className:"mailbox-item mailbox-approval-item",onClick:()=>void ht(ie),"data-testid":`mailbox-approval-item-${ie.id}`,children:[t.jsx("div",{className:`status-dot mailbox-approval-status-dot mailbox-approval-status-dot--${ie.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:[ie.agentId," · ",ie.actionCategory]}),t.jsx("span",{className:"mailbox-item-time",children:ta(ie.createdAt)})]}),t.jsx("div",{className:"mailbox-item-preview",children:ie.actionSummary})]}),t.jsx("span",{className:`mailbox-approval-status mailbox-approval-status--${ie.status}`,children:ie.status})]},ie.id))]})]}),a==="agents"&&t.jsx("div",{className:"mailbox-agents","data-testid":"mailbox-agents",children:U.length===0?t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Vn,{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:j??"",onChange:ie=>{P(ie.target.value||null),_("inbox")},"data-testid":"mailbox-agent-select",children:[t.jsx("option",{value:"",children:"Select an agent…"}),U.map(ie=>t.jsx("option",{value:ie.id,children:ie.name||ie.id},ie.id))]})}),t.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:Xe,"data-testid":"mailbox-compose-btn",children:[t.jsx(qi,{size:14}),t.jsx("span",{children:"Compose"})]})]}),j&&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(Ma,{size:12}),t.jsx("span",{children:"Inbox"}),R&&R.unreadCount>0&&t.jsx("span",{className:"mailbox-tab-badge",children:R.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(Aa,{size:12}),t.jsx("span",{children:"Outbox"})]})]}),t.jsxs("div",{className:"mailbox-agents-content",children:[!j&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Vn,{size:32}),t.jsx("p",{children:"Select an agent to view their mailbox"})]}),j&&h&&!R&&t.jsx(jd,{}),j&&R&&F==="inbox"&&R.inbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Ma,{size:32}),t.jsx("p",{children:"No received messages for this agent"})]}),j&&R&&F==="outbox"&&R.outbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Aa,{size:32}),t.jsx("p",{children:"No sent messages for this agent"})]}),j&&R&&F==="inbox"&&R.inbox.map(ie=>t.jsxs("div",{id:fl(ie.id),className:`mailbox-item ${ie.read?"":"unread"}`,onClick:()=>Te(ie),"data-testid":`mailbox-item-${ie.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ie.fromType==="agent"?t.jsx(Vn,{size:16}):t.jsx(Xa,{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:ce(ie.fromId,ie.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:ta(ie.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ie.content.slice(0,80),ie.content.length>80?"…":""]})]})]},ie.id)),j&&R&&F==="outbox"&&R.outbox.map(ie=>t.jsxs("div",{id:fl(ie.id),className:"mailbox-item",onClick:()=>Te(ie),"data-testid":`mailbox-item-${ie.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ie.toType==="agent"?t.jsx(Vn,{size:16}):t.jsx(Xa,{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: ",ce(ie.toId,ie.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:ta(ie.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ie.content.slice(0,80),ie.content.length>80?"…":""]})]})]},ie.id))]})]})})]}),at=()=>b?t.jsx(pf,{recipient:N,replyContext:E,agents:U,projectId:e,onSend:Me,onCancel:rt,addToast:n}):p?Re():a==="approvals"&&I?t.jsxs("div",{className:"mailbox-message-detail mailbox-approval-detail","data-testid":"mailbox-approval-detail",children:[X&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:()=>D(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:I.actionCategory}),t.jsx("span",{className:"mailbox-message-time",children:I.status})]})}),t.jsxs("div",{className:"mailbox-message-body",children:[t.jsx("strong",{children:I.actionSummary}),t.jsxs("p",{children:["Requester: ",I.requester.actorName," (",I.agentId,")"]}),I.taskId&&t.jsxs("p",{children:["Task: ",I.taskId]}),t.jsxs("p",{children:["Requested: ",ta(I.createdAt)]})]}),t.jsx("div",{className:"mailbox-conversation","data-testid":"mailbox-approval-history",children:I.history.map(ie=>t.jsxs("div",{className:"mailbox-conversation-msg",children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:ie.eventType}),t.jsx("span",{children:ie.actor.actorName})]}),ie.note&&t.jsx("div",{className:"mailbox-item-preview",children:ie.note})]},ie.id))}),I.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:S,onChange:ie=>G(ie.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 yt("deny"),disabled:he!==!1,"data-testid":"mailbox-approval-deny",children:"Deny"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>void yt("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(Ta,{size:24}),t.jsx("p",{children:"Select a message to read"})]});return t.jsxs("div",{className:"mailbox-view",style:we,"data-testid":"mailbox-view",children:[t.jsxs("div",{className:"mailbox-header",children:[t.jsxs("div",{className:"mailbox-title",children:[t.jsx(Ta,{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:Xe,title:"Compose message","data-testid":"mailbox-header-compose",children:[t.jsx(qi,{size:14}),t.jsx("span",{children:"Compose"})]}),a==="inbox"&&u>0&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:Ve,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[t.jsx(fm,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{a==="inbox"?He():a==="outbox"?Pe():a==="approvals"?De($):j&&tt(j)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?t.jsx(Nt,{size:14,className:"spin"}):t.jsx(fs,{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(Ma,{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(Aa,{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),D(null)},"data-testid":"mailbox-tab-agents",children:[t.jsx(Vn,{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),D(null)},"data-testid":"mailbox-tab-approvals",children:[t.jsx(fm,{size:14}),t.jsx("span",{children:"Approvals"}),q>0&&t.jsx("span",{className:"mailbox-tab-badge","data-testid":"mailbox-approvals-pending-badge",children:q})]})]}),t.jsx("div",{className:"mailbox-content","data-testid":"mailbox-content",children:Z?t.jsxs("div",{className:"mailbox-split-layout","data-testid":"mailbox-split-layout",ref:K,children:[t.jsx("div",{className:"mailbox-split-list-pane","data-testid":"mailbox-split-list-pane",style:{width:`${ee}px`},children:Ge()}),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":Wl,"aria-valuemax":Math.round(gu(K.current?.clientWidth??ee/fu)),"aria-valuenow":Math.round(ee),onMouseDown:ze,onKeyDown:re}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:at()})]}):t.jsxs(t.Fragment,{children:[Re(),a==="approvals"&&I&&at(),b&&t.jsx(pf,{recipient:N,replyContext:E,agents:U,projectId:e,onSend:Me,onCancel:rt,addToast:n}),!p&&!I&&!b&&Ge()]})})]})}function jd(){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 v4=640;function y4({isOpen:e,onClose:n,onImport:s,tasks:a,projectId:r}){ji(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,v]=i.useState(null),[N,k]=i.useState([]),[E,y]=i.useState(null),[j,P]=i.useState(null),[F,_]=i.useState(!1),[R,L]=i.useState([]),[U,C]=i.useState(!1),[$,V]=i.useState(""),Y=i.useRef(!1),ne=i.useRef(null);Ti(ne,e,"fusion:github-modal-size");const q=Gi(n),[A,I]=i.useState(!1),[D,S]=i.useState("list"),G=i.useRef(null),he=new Set;for(const me of a){const oe=me.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);oe&&he.add(oe[1]);const Me=me.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);Me&&he.add(Me[1])}i.useEffect(()=>{if(e)return l(""),d(""),m(""),w([]),v(null),k([]),y(null),g("issues"),P(null),_(!1),L([]),C(!0),V(""),G.current=null,Y.current=!0,uN().then(me=>{if(Y.current)if(L(me),C(!1),me.length===1){const oe=me[0];l(oe.owner),d(oe.repo),V(oe.name)}else me.length>1&&(l(""),d(""),V(""))}).catch(()=>{Y.current&&C(!1)}),()=>{Y.current=!1}},[e]);const Se=i.useCallback(me=>{if(V(me),me==="")l(""),d("");else{const oe=R.find(Me=>Me.name===me);oe&&(l(oe.owner),d(oe.repo))}},[R]),Ue=i.useCallback(async()=>{if(!o.trim()||!c.trim()){P("Repository must be selected");return}f(!0),P(null),w([]),v(null);try{const me=u.split(",").map(Me=>Me.trim()).filter(Boolean),oe=await oN(o.trim(),c.trim(),30,me.length>0?me:void 0);w(oe),oe.length===0&&P("No open issues found")}catch(me){P(Ce(me)||"Failed to fetch issues")}finally{f(!1)}},[o,c,u]),ce=i.useCallback(async()=>{if(!o.trim()||!c.trim()){P("Repository must be selected");return}f(!0),P(null),k([]),y(null);try{const me=await cN(o.trim(),c.trim(),30);k(me),me.length===0&&P("No open pull requests found")}catch(me){P(Ce(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};G.current?.owner===me.owner&&G.current?.repo===me.repo&&G.current?.labels===me.labels&&G.current?.tab===me.tab||(G.current=me,p==="issues"?Ue():ce())},[o,c,u,p,e,h,F,Ue,ce]),i.useEffect(()=>{if(!e)return;const me=oe=>{oe.key==="Escape"&&n()};return document.addEventListener("keydown",me),()=>document.removeEventListener("keydown",me)},[e,n]),i.useEffect(()=>{if(!e)return;const me=()=>{I(window.innerWidth<=v4)};return me(),window.addEventListener("resize",me),()=>window.removeEventListener("resize",me)},[e]);const Ae=i.useCallback(me=>{v(me),A&&S("preview")},[A]),X=i.useCallback(me=>{y(me),A&&S("preview")},[A]),Z=i.useCallback(()=>{S("list")},[]),ee=i.useCallback(async()=>{if(p==="issues"){if(b===null)return;_(!0),P(null);try{const me=await lN(o.trim(),c.trim(),b,r);s(me),v(null),A&&D==="preview"&&S("list")}catch(me){const oe=Ce(me);oe?.includes("already imported")?P(oe):P(oe||"Failed to import issue")}finally{_(!1)}}else{if(E===null)return;_(!0),P(null);try{const me=await dN(o.trim(),c.trim(),E,r);s(me),y(null),A&&D==="preview"&&S("list")}catch(me){const oe=Ce(me);oe?.includes("already imported")?P(oe):P(oe||"Failed to import pull request")}finally{_(!1)}}},[p,b,E,o,c,s,A,D]),le=x.find(me=>me.number===b),K=N.find(me=>me.number===E);if(!e)return null;const O=R.length>0,pe=R.length===1,ve=x.filter(me=>he.has(me.html_url)).length,B=N.filter(me=>he.has(me.html_url)).length,we=j==="No open issues found",ze=j==="No open pull requests found",re=p==="issues"?we:ze,He=!!j&&!we&&x.length===0&&!h,Pe=!!j&&!ze&&N.length===0&&!h,tt=p==="issues"?He:Pe,qe=h||x.length>0||we||He,de=h||N.length>0||ze||Pe,De=p==="issues"?qe:de,Te=!!j&&x.length>0&&!we,ct=!!j&&N.length>0&&!ze,Ve=p==="issues"?Te:ct;return t.jsx("div",{className:"modal-overlay open",...q,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"),y(null)},disabled:h||F,children:[t.jsx(ec,{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"),v(null)},disabled:h||F,children:[t.jsx(Js,{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(Nt,{size:16,className:"spin"}),t.jsx("span",{children:"Detecting…"})]}):O?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:R[0].name}),t.jsxs("span",{className:"github-import-remote-pill__repo",children:[R[0].owner,"/",R[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:$,onChange:me=>Se(me.target.value),disabled:h||F,"aria-label":"Select Git remote",children:[t.jsx("option",{value:"",children:"Select remote…"}),R.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"&&Ue(),disabled:h||F||!O,"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"?Ue:ce,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(Nt,{size:14,className:"spin"}):t.jsx(fs,{size:14}),t.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!U&&!O&&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"})]}),Ve&&t.jsx("div",{className:"form-error github-import-banner",role:"alert",children:j}),t.jsxs("div",{className:"github-import-workspace",children:[t.jsxs("section",{className:`github-import-list-pane ${A?"mobile":""} ${D==="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:[ve," imported"]})]}),p==="pulls"&&N.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[N.length," pull request",N.length===1?"":"s"]}),t.jsxs("span",{children:[B," imported"]})]})]}),t.jsxs("div",{className:"github-import-pane-content",children:[!De&&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(Nt,{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."})]})]}),tt&&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:j})]})}),re&&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 oe=he.has(me.html_url);return t.jsxs("div",{className:`issue-item ${b===me.number?"selected":""} ${oe?"imported":""}`,onClick:()=>!oe&&Ae(me.number),children:[t.jsx("input",{type:"radio",name:"issue",checked:b===me.number,onChange:()=>Ae(me.number),disabled:oe,"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(Me=>t.jsx("span",{className:"label-chip",children:Me.name},Me.name))})]}),oe&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},me.number)})}),p==="pulls"&&N.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:N.map(me=>{const oe=he.has(me.html_url);return t.jsxs("div",{className:`issue-item ${E===me.number?"selected":""} ${oe?"imported":""}`,onClick:()=>!oe&&X(me.number),children:[t.jsx("input",{type:"radio",name:"pull",checked:E===me.number,onChange:()=>X(me.number),disabled:oe,"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]})]}),oe&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},me.number)})})]})]}),t.jsxs("section",{className:`github-import-preview-pane ${A?"mobile":""} ${D==="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:Z,"data-testid":"github-import-back-button","aria-label":`Back to ${p==="issues"?"issues":"pull requests"} list`,children:[t.jsx(Fa,{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"&&le?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Issue #",le.number]}),t.jsx("div",{className:"preview-title",children:le.title}),t.jsx("div",{className:"preview-body",children:le.body?le.body.slice(0,200)+(le.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"&&K?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Pull Request #",K.number]}),t.jsx("div",{className:"preview-title",children:K.title}),t.jsxs("div",{className:"preview-branch",children:[t.jsx("strong",{children:"Branch:"})," ",K.headBranch," → ",K.baseBranch]}),t.jsx("div",{className:"preview-body",children:K.body?K.body.slice(0,200)+(K.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:E===null)||F,children:F?t.jsx(Nt,{size:14,className:"spin"}):"Import"})]})]})})}function ai({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(zn,{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 w4=["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 jo(e){return e&&da.includes(e)?e:Ms}function Nd(e){return{...e,priority:jo(e.priority)}}function k4(e,n){return e&&n?`${e}/${n}`:""}function j4(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 N4({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([]),[v,N]=i.useState(null),k=i.useRef(!1),E=i.useRef(!1),[y,j]=i.useState(""),[P,F]=i.useState(!0),[_,R]=i.useState(!1),[L,U]=i.useState(!1),[C,$]=i.useState(null),[V,Y]=i.useState(0),ne=i.useRef(null),q=i.useRef(null),A=i.useRef(null),I=i.useRef(null),D=i.useRef(null),S=i.useRef(null),G=i.useRef(null),[he,Se]=i.useState(c??null),Ue=i.useMemo(()=>Ua(),[]),{isLockedByOther:ce,takeControl:Ae,isLoading:X}=xc(e?he:null),{activeTabMap:Z,broadcastUpdate:ee,broadcastCompleted:le,broadcastLock:K,broadcastUnlock:O,broadcastHeartbeat:pe}=Ir(),[ve,B]=i.useState(void 0),[we,ze]=i.useState(void 0),[re,He]=i.useState("medium"),[Pe,tt]=i.useState(""),[qe,de]=i.useState([]),[De,Te]=i.useState(!1),[ct,Ve]=i.useState(null),[me,oe]=i.useState([]),[Me,Xe]=i.useState([]),[rt,ht]=i.useState({}),yt=i.useRef(null),[Re,Ge]=i.useState([]),[at,ie]=i.useState(!1),[Ke,je]=i.useState(c??null),[Fe,Be]=i.useState(!!c),[St,ye]=i.useState(null),[kt,It]=i.useState(!1),Ie=i.useRef(!1),be=i.useRef(null),ot=i.useRef(""),gt=i.useRef(null),xt=i.useRef(null);Ti(q,e,"fusion:planning-modal-size");const jt=Zs(),{keyboardOverlap:Bt,viewportHeight:Jt,viewportOffsetTop:Vt,keyboardOpen:pn}=Yi({enabled:jt==="mobile"});ji(jt==="mobile"&&e),i.useEffect(()=>{const fe=q.current;fe&&(pn?(fe.style.setProperty("--keyboard-overlap",`${Bt}px`),fe.style.setProperty("--vv-offset-top",`${Vt}px`),Jt!==null?fe.style.setProperty("--vv-height",`${Jt}px`):fe.style.removeProperty("--vv-height")):(fe.style.removeProperty("--keyboard-overlap"),fe.style.removeProperty("--vv-offset-top"),fe.style.removeProperty("--vv-height")))},[pn,Bt,Vt,Jt]),i.useEffect(()=>{ot.current=y},[y]),i.useEffect(()=>{const fe=be.current;if(!fe)return;fe.scrollHeight-fe.scrollTop-fe.clientHeight<32&&(fe.scrollTop=fe.scrollHeight)},[y]),i.useEffect(()=>{if(m.type!=="loading"){$(null),Y(0);return}const fe=Date.now();$(fe),Y(0);const ft=setInterval(()=>{Y(Math.max(0,Math.floor((Date.now()-fe)/1e3)))},1e3);return()=>clearInterval(ft)},[m.type]),i.useEffect(()=>{if(m.type!=="loading")return;const fe=I.current;if(!fe)return;let ft=!1;const vt=setInterval(async()=>{try{const et=await Ai(fe);if(ft||!et||I.current!==fe)return;if(et.status==="awaiting_input"&&et.currentQuestion){const _t=JSON.parse(et.currentQuestion);h({type:"question",session:{sessionId:fe,currentQuestion:_t,summary:null}}),j("")}else if(et.status==="complete"&&et.result){const _t=Nd(JSON.parse(et.result));h({type:"summary",session:{sessionId:fe,currentQuestion:null,summary:_t},summary:_t}),N(_t),j("")}}catch{}},8e3);return()=>{ft=!0,clearInterval(vt)}},[m.type]);const Xt=i.useCallback(()=>{u(""),h({type:"initial"}),p(null),x([]),b([]),N(null),j(""),R(!1),U(!1),B(void 0),ze(void 0),He("medium"),tt(""),I.current=null,Se(null)},[]),mn=k4(ve,we),Ht=i.useCallback((fe,ft)=>{if(!fe||!ft)return rt.provider&&rt.modelId?`${rt.provider}/${rt.modelId}`:"Using default";const lt=qe.find(vt=>vt.provider===fe&&vt.id===ft);return lt?`${lt.provider}/${lt.id}`:`${fe}/${ft}`},[qe,rt.modelId,rt.provider]),Zt=i.useCallback(async()=>{Te(!0),Ve(null);try{const fe=await Fs();de(fe.models),oe(fe.favoriteProviders),Xe(fe.favoriteModels),ht({provider:fe.resolvedPlanningProvider,modelId:fe.resolvedPlanningModelId})}catch(fe){Ve(Ce(fe)||"Failed to load models")}finally{Te(!1)}},[]),tn=i.useCallback(fe=>{oe(ft=>{const lt=ft,et=lt.includes(fe)?lt.filter(_t=>_t!==fe):[fe,...lt];return Pn({favoriteProviders:et,favoriteModels:Me}).catch(()=>{oe(lt)}),et})},[Me]),dn=i.useCallback(fe=>{Xe(ft=>{const lt=ft,et=lt.includes(fe)?lt.filter(_t=>_t!==fe):[fe,...lt];return Pn({favoriteProviders:me,favoriteModels:et}).catch(()=>{Xe(lt)}),et})},[me]),qt=i.useCallback(fe=>{A.current?.close();const ft=()=>I.current!==fe,lt=hS(fe,l,{onThinking:vt=>{ft()||(j(et=>et+vt),ee({sessionId:fe,status:"generating",needsInput:!1,owningTabId:Ue,type:"planning",title:d.trim()||void 0,projectId:l??null}))},onQuestion:vt=>{if(ft())return;R(!1),U(!1),sr(l);const et=ot.current.trim();et&&b(_t=>_t[_t.length-1]?.thinkingOutput===et?_t:[..._t,{thinkingOutput:et}]),h({type:"question",session:{sessionId:fe,currentQuestion:vt,summary:null}}),j(""),ee({sessionId:fe,status:"awaiting_input",needsInput:!0,owningTabId:Ue,type:"planning",title:d.trim()||void 0,projectId:l??null})},onSummary:vt=>{if(ft())return;R(!1),U(!1),sr(l);const et=ot.current.trim();et&&b(_t=>_t[_t.length-1]?.thinkingOutput===et?_t:[..._t,{thinkingOutput:et}]),h({type:"summary",session:{sessionId:fe,currentQuestion:null,summary:vt},summary:vt}),N(vt),j(""),ee({sessionId:fe,status:"complete",needsInput:!1,owningTabId:Ue,type:"planning",title:d.trim()||void 0,projectId:l??null})},onError:vt=>{const et=vt||"Session failed while contacting the AI.";R(!0),(async()=>{try{const _t=await Ai(fe);if(_t&&(_t.status==="generating"||_t.status==="awaiting_input")){qt(fe);return}}catch{}R(!1),U(!1),p(null),h(_t=>_t.type==="question"||_t.type==="summary"||_t.type==="error"?{type:"error",session:_t.session,errorMessage:et}:{type:"error",session:{sessionId:fe,currentQuestion:null,summary:null},errorMessage:et}),j(""),I.current=fe,ee({sessionId:fe,status:"error",needsInput:!1,owningTabId:Ue,type:"planning",title:d.trim()||void 0,projectId:l??null}),le({sessionId:fe,status:"error"})})()},onComplete:()=>{R(!1),U(!1),I.current=null,le({sessionId:fe,status:"complete"})},onConnectionStateChange:vt=>{R(vt==="reconnecting")}});A.current=lt},[le,ee,d,l,Ue]),ke=i.useCallback(async fe=>{const ft=fe??d;if(ft.trim()){p(null),j(""),b([]),x([]),R(!1),h({type:"loading"});try{const lt=ve&&we?{planningModelProvider:ve,planningModelId:we}:void 0,vt=Pe.trim()?Number.parseInt(Pe,10):void 0,et=D.current,{sessionId:_t}=await JN(ft.trim(),l,lt,{planningDepth:re,customQuestionCount:Number.isInteger(vt)?vt:void 0},et??void 0);D.current=null,I.current=_t,Se(_t),je(_t),qt(_t),x([])}catch(lt){R(!1),p(Ce(lt)||"Failed to start planning session"),h({type:"initial"}),I.current=null,Se(null)}}},[qt,Pe,d,re,we,ve,l]);i.useEffect(()=>{e&&m.type==="initial"&&ne.current?.focus()},[e,m.type]),i.useEffect(()=>{e&&Zt()},[e,Zt]),i.useEffect(()=>{if(e&&o&&!k.current&&m.type==="initial"){u(o);const fe=setTimeout(()=>{k.current=!0,ke(o)},0);return()=>clearTimeout(fe)}else if(e&&!o&&!k.current&&!E.current&&m.type==="initial"){E.current=!0;const fe=MT(l);fe&&u(fe)}},[e,o,m.type,ke,l]);const $e=i.useCallback(async fe=>{A.current?.close(),A.current=null,p(null),j(""),x([]),b([]),N(null),U(!1),h({type:"loading"});try{const ft=await Ai(fe);if(!ft){je(null),Be(!1),h({type:"initial"});return}I.current=fe,Se(fe);const lt=xr(ft.conversationHistory);if(b(lt),x(lt.map(vt=>vt.response).filter(vt=>!!(vt&&typeof vt=="object"&&!Array.isArray(vt)))),ft.status==="draft"){let vt="",et,_t;try{const Gt=ft.inputPayload?JSON.parse(ft.inputPayload):null;Gt&&typeof Gt.initialPlan=="string"&&(vt=Gt.initialPlan),Gt&&typeof Gt.modelProvider=="string"&&typeof Gt.modelId=="string"&&(et=Gt.modelProvider,_t=Gt.modelId)}catch{}u(vt),B(et),ze(_t),D.current=fe,xt.current=vt?{sessionId:fe,initialPlan:vt.trim(),modelProvider:et,modelId:_t}:null,h({type:"initial"})}else if(ft.status==="awaiting_input"&&ft.currentQuestion){sr(l);const vt=JSON.parse(ft.currentQuestion);if(h({type:"question",session:{sessionId:fe,currentQuestion:vt,summary:null}}),ft.thinkingOutput){const et=ft.thinkingOutput.trim();et&&b(_t=>_t[_t.length-1]?.thinkingOutput===et?_t:[..._t,{thinkingOutput:et}])}qt(fe)}else if(ft.status==="complete"&&ft.result){sr(l);const vt=Nd(JSON.parse(ft.result));h({type:"summary",session:{sessionId:fe,currentQuestion:null,summary:vt},summary:vt}),N(vt)}else ft.status==="generating"?(h({type:"loading"}),ft.thinkingOutput&&j(ft.thinkingOutput),qt(fe)):ft.status==="error"&&h({type:"error",session:{sessionId:fe,currentQuestion:null,summary:null},errorMessage:ft.error||"Session failed"})}catch{p("Failed to load session"),h({type:"initial"})}},[qt,l]);i.useEffect(()=>{!e||!c||I.current!==c&&G.current!==c&&(je(c),Be(!0),$e(c))},[e,c]),i.useEffect(()=>{e&&Ke&&(c&&c===Ke||$e(Ke))},[e]);const Ye=i.useCallback(async()=>{ie(!0);try{const ft=(await Ru(l,{includeCompleted:!0,includeArchived:kt})).filter(lt=>lt.type==="planning").sort((lt,vt)=>Date.parse(vt.updatedAt)-Date.parse(lt.updatedAt));Ge(ft)}catch{}finally{ie(!1)}},[l,kt]);i.useEffect(()=>{e&&Ye()},[e,Ye]);const ut=i.useRef(!1);i.useEffect(()=>{const fe=ut.current&&!at;ut.current=at,fe&&jt==="mobile"&&(Fe||c||Ke||Re.length>0||Be(!0))},[jt,Fe,c,Ke,at,Re.length]),i.useEffect(()=>{if(!e)return;const fe=l?`?projectId=${encodeURIComponent(l)}`:"",ft=vt=>{try{const et=JSON.parse(vt.data);if(et.type!=="planning")return;Ge(_t=>{const Gt=_t.findIndex(pt=>pt.id===et.id);return(Gt>=0?[..._t.slice(0,Gt),et,..._t.slice(Gt+1)]:[et,..._t]).sort((pt,gn)=>Date.parse(gn.updatedAt)-Date.parse(pt.updatedAt))})}catch{}},lt=vt=>{try{const et=JSON.parse(vt.data);Ge(_t=>_t.filter(Gt=>Gt.id!==et))}catch{}};return li(`/api/events${fe}`,{events:{"ai_session:updated":ft,"ai_session:deleted":lt},onReconnect:()=>{Ye()}})},[e,l,Ye]);const We=i.useCallback(fe=>{if(Ke===fe){Be(!0);return}je(fe),Be(!0),$e(fe)},[$e,Ke]),$t=i.useCallback(()=>{A.current?.close(),A.current=null,D.current=null,S.current&&(clearTimeout(S.current),S.current=null),c&&(G.current=c),Xt(),je(null),Be(!0)},[Xt,c]),At=i.useCallback(()=>{Be(!1)},[]),wt=i.useCallback(async(fe,ft)=>{const lt=ft.trim();if(!(!lt||xt.current?.sessionId===fe&&xt.current.initialPlan===lt&&xt.current.modelProvider===ve&&xt.current.modelId===we))try{await s0(fe,{initialPlan:lt,modelProvider:ve&&we?ve:void 0,modelId:ve&&we?we:void 0},l),xt.current={sessionId:fe,initialPlan:lt,modelProvider:ve,modelId:we}}catch{}},[we,ve,l]);i.useEffect(()=>{if(gt.current&&(clearTimeout(gt.current),gt.current=null),!(!e||m.type!=="initial"||!Ke))return gt.current=setTimeout(()=>{wt(Ke,d)},500),()=>{gt.current&&(clearTimeout(gt.current),gt.current=null)}},[d,e,Ke,wt,m.type]),i.useEffect(()=>{xt.current=null},[Ke]),i.useEffect(()=>()=>{gt.current&&(clearTimeout(gt.current),gt.current=null)},[]);const zt=i.useCallback(async fe=>{const ft=vt=>vt==="generating"||vt==="awaiting_input",lt=Re.find(vt=>vt.id===fe);if(lt&&ft(lt.status))try{await Yg(fe,l,Ue)}catch{}try{await ab(fe)}catch{}le({sessionId:fe,status:"complete",timestamp:Date.now()}),Ge(vt=>vt.filter(et=>et.id!==fe)),Ke===fe&&(A.current?.close(),A.current=null,Xt(),je(null),Be(!1)),ye(null)},[le,Re,l,Xt,Ke,Ue]),Lt=i.useCallback(async fe=>{const lt=Re.find(vt=>vt.id===fe)?.archived===!0;try{lt?await X1(fe):await Q1(fe)}catch{return}Ge(vt=>!lt&&!kt?vt.filter(et=>et.id!==fe):vt.map(et=>et.id===fe?{...et,archived:!lt}:et)),!lt&&Ke===fe&&!kt&&(A.current?.close(),A.current=null,Xt(),je(null),Be(!1))},[Re,Xt,Ke,Be,kt]);i.useEffect(()=>{e||(k.current=!1,E.current=!1,R(!1),U(!1),Se(null))},[e]),i.useEffect(()=>{if(!e){yt.current&&(O(yt.current,Ue),yt.current=null);return}if(he&&yt.current!==he){yt.current&&O(yt.current,Ue),K(he,Ue),yt.current=he;return}!he&&yt.current&&(O(yt.current,Ue),yt.current=null)},[K,O,e,he,Ue]),i.useEffect(()=>{if(!e||!he||yt.current!==he)return;pe(Ue);const fe=setInterval(()=>{pe(Ue)},3e4);return()=>{clearInterval(fe)}},[pe,e,he,Ue]),i.useEffect(()=>()=>{S.current&&(clearTimeout(S.current),S.current=null),A.current?.close(),A.current=null,yt.current&&(O(yt.current,Ue),yt.current=null)},[O,Ue]),i.useEffect(()=>{if(!e)return;const fe=()=>{A.current?.close(),A.current=null};return window.addEventListener("beforeunload",fe),()=>window.removeEventListener("beforeunload",fe)},[e]);const Ot=i.useCallback((fe,ft)=>{gt.current&&(clearTimeout(gt.current),gt.current=null),(async()=>{try{await wt(fe,ft),await i0(fe,l)}catch{}})()},[l,wt]),nn=i.useCallback(()=>{if(jt!=="mobile")return;const fe=document.activeElement;fe instanceof HTMLElement&&fe.blur(),window.scrollTo(0,0),requestAnimationFrame(()=>{window.scrollTo(0,0)})},[jt]),Yt=i.useCallback(()=>{d&&m.type==="initial"&&_T(d,l);const fe=D.current;fe&&d.trim()&&Ot(fe,d),D.current=null,S.current&&(clearTimeout(S.current),S.current=null),A.current?.close(),A.current=null,R(!1),U(!1),nn(),n()},[Ot,d,n,l,nn,m.type]);i.useEffect(()=>{if(!e)return;const fe=ft=>{ft.key==="Escape"&&Yt()};return document.addEventListener("keydown",fe),()=>document.removeEventListener("keydown",fe)},[e,Yt]);const rn=i.useCallback(async fe=>{if(m.type!=="question")return;const{session:ft}=m,lt=ft.sessionId,vt=ft.currentQuestion;if(!vt){p("No active question in session");return}p(null),x(et=>[...et,fe]),b(et=>{const _t=ot.current.trim();let Gt=et;return _t&&Gt[Gt.length-1]?.thinkingOutput!==_t&&(Gt=[...Gt,{thinkingOutput:_t}]),[...Gt,{question:vt,response:fe}]}),h({type:"loading"}),j("");try{await Pm(lt,fe,l,Ue)}catch(et){p(Ce(et)||"Failed to submit response"),h({type:"question",session:ft})}},[l,Ue,m]),_e=i.useCallback(async()=>{if(m.type!=="summary")return;const{session:fe,summary:ft}=m,lt=fe.sessionId;I.current=lt,Se(lt),p(null),U(!1),j(""),h({type:"loading"}),qt(lt);try{await Pm(lt,{refine:!0},l,Ue)}catch(vt){A.current?.close(),A.current=null,p(Ce(vt)||"Failed to refine plan"),h({type:"summary",session:fe,summary:v??ft})}},[qt,v,l,Ue,m]),it=i.useCallback(async()=>{const fe=I.current;if(fe){try{await XN(fe,l,Ue)}catch{}A.current?.close(),A.current=null,R(!1),U(!1),h({type:"error",session:{sessionId:fe,currentQuestion:null,summary:null},errorMessage:"Generation stopped by user. You can retry or start a new session."}),j("")}},[l,Ue]),bt=i.useCallback(async()=>{if(m.type!=="error")return;const fe=m.session;p(null),U(!0),j(""),h({type:"loading"}),qt(fe.sessionId);try{I.current=fe.sessionId,Se(fe.sessionId),await QN(fe.sessionId,l,Ue)}catch(ft){let lt=ft;if((Ce(ft)||"").includes("not in an error state"))try{const et=await Ai(fe.sessionId);if(!et)throw new Error("Failed to refresh planning session.");if(I.current=et.id,Se(et.id),et.status==="generating")j(et.thinkingOutput??""),h({type:"loading"});else if(et.status==="awaiting_input"){if(!et.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const _t=JSON.parse(et.currentQuestion);if(sr(l),h({type:"question",session:{sessionId:et.id,currentQuestion:_t,summary:null}}),et.thinkingOutput){const Gt=et.thinkingOutput.trim();Gt&&b(ae=>ae[ae.length-1]?.thinkingOutput===Gt?ae:[...ae,{thinkingOutput:Gt}])}A.current?.isConnected()||qt(et.id)}else if(et.status==="complete"){if(!et.result)throw new Error("Planning session is complete but has no result.");const _t=Nd(JSON.parse(et.result));sr(l),h({type:"summary",session:{sessionId:et.id,currentQuestion:null,summary:_t},summary:_t}),N(_t)}else et.status==="error"&&h({type:"error",session:{sessionId:et.id,currentQuestion:null,summary:null},errorMessage:et.error||"Retry failed. Please try again."});R(!1);return}catch(et){lt=et}A.current?.close(),A.current=null,h({type:"error",session:fe,errorMessage:Ce(lt)||"Retry failed. Please try again."}),R(!1)}finally{U(!1)}},[qt,l,Ue,m]),Rt=i.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const fe=m.session.sessionId,ft=await ZN(fe,v??void 0,l);s(ft),je(null),Ge(lt=>lt.filter(vt=>vt.id!==fe)),le({sessionId:fe,status:"complete",timestamp:Date.now()}),Yt()}catch(fe){p(Ce(fe)||"Failed to create task"),h({type:"summary",session:m.session,summary:m.summary})}}},[le,v,m,l,s,Yt]),se=i.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const fe=await eS(m.session.sessionId,v??void 0,l);Se(fe.sessionId),h({type:"breakdown",sessionId:fe.sessionId,subtasks:fe.subtasks.map(ft=>({...ft,priority:jo(ft.priority)})),dirty:!1})}catch(fe){p(Ce(fe)||"Failed to start breakdown"),h({type:"summary",session:m.session,summary:m.summary})}}},[v,m,l]),te=i.useCallback(async()=>{if(m.type==="breakdown"){p(null),h({type:"creating"});try{const fe=m.sessionId,ft=await tS(fe,m.subtasks.map(lt=>({...lt,priority:jo(lt.priority)})),l);a(ft.tasks),Ge(lt=>lt.filter(vt=>vt.id!==fe)),le({sessionId:fe,status:"complete",timestamp:Date.now()}),u(""),h({type:"initial"}),p(null),x([]),b([]),N(null),j(""),B(void 0),ze(void 0),He("medium"),tt(""),I.current=null,Se(null),je(null),Yt()}catch(fe){p(Ce(fe)||"Failed to create tasks"),h({type:"breakdown",sessionId:m.sessionId,subtasks:m.subtasks,dirty:m.dirty})}}},[le,Yt,m,a,l]),Oe=i.useCallback(async()=>{if(m.type!=="question"||g.length===0)return;const fe=m.session.sessionId;p(null),h({type:"loading"});try{const ft=await YN(fe,l,Ue);x(ft.history.map(lt=>lt.response&&typeof lt.response=="object"&&!Array.isArray(lt.response)?lt.response:{[lt.question.id]:lt.response})),b(ft.history.map(lt=>({question:lt.question,response:lt.response&&typeof lt.response=="object"&&!Array.isArray(lt.response)?lt.response:{[lt.question.id]:lt.response},thinkingOutput:lt.thinkingOutput}))),j(""),h({type:"question",session:{...m.session,currentQuestion:ft.currentQuestion,summary:null}})}catch(ft){p(Ce(ft)||"Failed to go back to the previous question"),h({type:"question",session:m.session})}},[l,g.length,Ue,m]),mt=()=>m.type==="question"?Math.min(g.length+1,3):3,Pt=he?Z.get(he):null,sn=Pt&&Pt.tabId!==Ue,In=ce&&(!sn||Pt.stale);return e?t.jsx("div",{className:"modal-overlay open",onMouseDown:fe=>{Ie.current=fe.target===fe.currentTarget},onClick:fe=>{fe.target===fe.currentTarget&&Ie.current&&Yt(),Ie.current=!1},role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",ref:q,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[Fe&&t.jsx("button",{className:"modal-back planning-mobile-back",onClick:At,"aria-label":"Back to sessions",title:"Back to sessions",children:t.jsx(Zl,{size:18})}),t.jsx(Pi,{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:Yt,"aria-label":"Close",children:t.jsx(an,{size:20})})})]}),t.jsxs("div",{className:`planning-modal-body planning-modal-body--split ${Fe?"planning-modal-body--show-detail":"planning-modal-body--show-list"}`,children:[t.jsx(M4,{sessions:Re,loading:at,selectedSessionId:Ke,pendingDeleteId:St,showArchived:kt,onToggleShowArchived:()=>It(fe=>!fe),onArchive:fe=>void Lt(fe),onSelectSession:We,onNewSession:$t,onRequestDelete:ye,onConfirmDelete:fe=>void zt(fe),onCancelDelete:()=>ye(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(xs,{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:fe=>{const ft=fe.target.value;u(ft),!(D.current||ft.trim().length===0)&&(S.current&&clearTimeout(S.current),S.current=setTimeout(()=>{if(D.current)return;const lt=ft.trim();if(!lt)return;GN(lt,l,ve&&we?{planningModelProvider:ve,planningModelId:we}:void 0).then(et=>{D.current=et.sessionId,Ge(_t=>_t.some(ae=>ae.id===et.sessionId)?_t:[{id:et.sessionId,type:"planning",status:"draft",title:et.title,preview:lt.length>80?`${lt.slice(0,79).trimEnd()}…`:lt,projectId:l??null,lockedByTab:null,updatedAt:new Date().toISOString(),archived:!1},..._t].sort((ae,pt)=>Date.parse(pt.updatedAt)-Date.parse(ae.updatedAt))),je(et.sessionId)}).catch(()=>{})},300))},onKeyDown:fe=>{fe.key==="Enter"&&!fe.shiftKey&&d.trim()&&(fe.preventDefault(),ke())},onBlur:()=>{const fe=D.current;fe&&d.trim()&&Ot(fe,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:w4.map((fe,ft)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>u(fe),children:fe.length>40?fe.slice(0,40)+"...":fe},ft))})]}),t.jsx(ai,{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",De&&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(Ns,{id:"planning-modal-model",label:"Planning Model",value:mn,onChange:fe=>{const{provider:ft,modelId:lt}=j4(fe);B(ft),ze(lt)},models:qe,disabled:De,favoriteProviders:me,onToggleFavorite:tn,favoriteModels:Me,onToggleModelFavorite:dn}),ct&&t.jsxs("div",{className:"form-hint form-hint-error",children:[ct," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{Zt()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${ve&&we?"model-badge-custom":"model-badge-default"}`,children:Ht(ve,we)})})]}),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(fe=>t.jsx("button",{type:"button",className:`planning-depth-chip btn ${re===fe.value?"btn-primary planning-depth-chip-active":""}`,onClick:()=>He(fe.value),"aria-pressed":re===fe.value,children:fe.label},fe.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:fe=>tt(fe.target.value),placeholder:"Auto"})]})]})]})]})})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>ke(),disabled:!d.trim(),children:[t.jsx(Pi,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),m.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(Nt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:y?"AI is thinking...":"Generating next question..."}),C&&t.jsxs("div",{className:"planning-elapsed",children:["Thinking… (",V,"s)"]}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>F(!P),type:"button",children:P?"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(Ay,{size:14}),t.jsx("span",{className:"icon-ml-6",children:"Stop"})]})}),P&&y&&t.jsx("div",{className:"planning-thinking-output",ref:be,children:t.jsx("pre",{children:y})})]})]}),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(oi,{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 bt(),disabled:L,children:[L?t.jsx(Nt,{size:14,className:"spin"}):t.jsx(fs,{size:14}),t.jsx("span",{className:"icon-ml-6",children:L?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Yt,disabled:L,children:"Dismiss"})]})]})]})}),m.type==="creating"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(Nt,{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(S4,{question:m.session.currentQuestion,progress:mt(),historyEntries:w,onSubmit:rn,onBack:g.length>0?Oe:void 0})}),m.type==="summary"&&v&&t.jsx(C4,{summary:v,historyEntries:w,onSummaryChange:N,tasks:r,onCreateTask:Rt,onBreakIntoTasks:se,onRefine:()=>{_e()},isLoading:!1}),m.type==="breakdown"&&t.jsx(_4,{subtasks:m.subtasks,dirty:m.dirty,isLoading:!1,onUpdateSubtasks:fe=>h({...m,subtasks:fe,dirty:!0}),onCreateTasks:te,onBack:()=>{const ft={sessionId:m.sessionId,currentQuestion:null,summary:v??null};v&&h({type:"summary",session:ft,summary:v})}})]}),ce&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(ac,{size:16}),t.jsx("span",{children:In?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),In&&t.jsx("button",{type:"button",onClick:()=>{Ae()},disabled:X,className:"btn btn-primary session-lock-take-control",children:X?"Taking control...":"Take Control"})]})})]})]})}):null}function S4({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(oi,{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(Wn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!1?"selected":""}`,onClick:()=>l({[e.id]:!1}),children:[t.jsx(an,{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(Fa,{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(Eo,{size:16,className:"icon-ml-4"})]})]})]})}function C4({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=jo(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(ai,{summary:"Show user Q&A",className:"planning-summary-qa-disclosure",children:[t.jsx(oi,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Wn,{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:da.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(Fa,{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(Nt,{size:16,className:"spin icon-mr-8"}),"Creating..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Wn,{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(Nt,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):t.jsxs(t.Fragment,{children:[t.jsx(ic,{size:16,className:"icon-mr-8"}),"Break into Tasks"]})})]})]})]})}function vf(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 E4(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",priority:Ms,dependsOn:[]}}function _4({subtasks:e,dirty:n,isLoading:s,onUpdateSubtasks:a,onCreateTasks:r,onBack:o}){const[l,c]=i.useState(null),[d,u]=i.useState(null),[m,h]=i.useState(null),f=i.useRef([]),p=i.useMemo(()=>e.length===0||e.some(j=>!j.title.trim())?!0:vf(e),[e]),g=i.useCallback((j,P)=>{a(e.map(F=>F.id===j?{...F,...P}:F))},[e,a]),x=i.useCallback(()=>{a([...e,E4(e.length+1)])},[e,a]),w=i.useCallback(j=>{a(e.filter(P=>P.id!==j).map(P=>({...P,dependsOn:P.dependsOn.filter(F=>F!==j)})))},[e,a]),b=i.useCallback((j,P)=>{if(P<0||P>=e.length)return;const F=[...e],[_]=F.splice(j,1);F.splice(P,0,_),a(F)},[e,a]),v=i.useCallback(j=>P=>{c(j),P.dataTransfer.setData("text/plain",j),P.dataTransfer.effectAllowed="move"},[]),N=i.useCallback(()=>{c(null),u(null),h(null)},[]),k=i.useCallback(j=>P=>{if(P.preventDefault(),j===l)return;const F=P.currentTarget.getBoundingClientRect(),_=F.top+F.height/2,R=P.clientY<_?"before":"after";u(j),h(R)},[l]),E=i.useCallback(j=>P=>{P.preventDefault();const F=P.dataTransfer.getData("text/plain");if(!F||F===j){N();return}const _=e.findIndex($=>$.id===F),R=e.findIndex($=>$.id===j);if(_===-1||R===-1){N();return}const L=[...e],[U]=L.splice(_,1);let C=R;m==="after"&&_<R&&C--,m==="after"&&C++,L.splice(C,0,U),a(L),N()},[e,m,a,N]),y=i.useCallback(j=>{const P=j.currentTarget.getBoundingClientRect(),F=j.clientX,_=j.clientY;(F<P.left||F>P.right||_<P.top||_>P.bottom)&&(u(null),h(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(ic,{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((j,P)=>{const F=l===j.id,_=d===j.id,R=["task-detail-section","subtask-item",F?"subtask-item-dragging":"",_?"subtask-item-drop-target":"",_&&m==="before"?"subtask-item-drop-before":"",_&&m==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:R,"data-testid":`subtask-item-${P}`,draggable:!s,onDragStart:v(j.id),onDragEnd:N,onDragOver:k(j.id),onDrop:E(j.id),onDragLeave:y,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(sc,{size:16}),t.jsx("strong",{children:j.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>b(P,P-1),disabled:s||P===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(Ra,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>b(P,P+1),disabled:s||P===e.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(Co,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>w(j.id),disabled:s,children:[t.jsx(Sn,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:L=>{f.current[P]=L},value:j.title,onChange:L=>g(j.id,{title:L.target.value}),onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),P<e.length-1&&f.current[P+1]?.focus())},disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:j.description,onChange:L=>g(j.id,{description:L.target.value}),disabled:s})]}),t.jsxs("div",{className:"planning-summary-meta-row",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`${j.id}-size`,children:"Size"}),t.jsxs("select",{id:`${j.id}-size`,className:"planning-size-select",value:j.suggestedSize,onChange:L=>g(j.id,{suggestedSize:L.target.value}),disabled:s,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:`${j.id}-priority`,children:"Priority"}),t.jsx("select",{id:`${j.id}-priority`,className:"planning-size-select",value:jo(j.priority),onChange:L=>g(j.id,{priority:L.target.value}),disabled:s,children:da.map(L=>t.jsx("option",{value:L,children:L[0].toUpperCase()+L.slice(1)},L))})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[e.slice(0,P).filter(L=>L.id!==j.id).map(L=>{const U=j.dependsOn.includes(L.id);return t.jsxs("label",{className:`planning-dep-chip ${U?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:U,onChange:()=>{const C=U?j.dependsOn.filter($=>$!==L.id):[...j.dependsOn,L.id];g(j.id,{dependsOn:C})},disabled:s}),t.jsx("span",{className:"planning-dep-id",children:L.id}),t.jsx("span",{className:"planning-dep-title",children:L.title||"Untitled"})]},L.id)}),P===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),P>0&&e.slice(0,P).filter(L=>L.id!==j.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},j.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:x,disabled:s,children:[t.jsx(Cn,{size:16,className:"icon-mr-6"})," Add subtask"]}),vf(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:o,disabled:s,children:[t.jsx(Fa,{size:16,className:"icon-mr-4"}),"Back to Summary"]}),t.jsx("button",{className:"btn btn-primary",onClick:r,disabled:s||p,children:s?t.jsxs(t.Fragment,{children:[t.jsx(Nt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]})}function M4({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(Kw,{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(A4,{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(R4,{status:f.status}),t.jsx("span",{"aria-hidden":!0,children:" · "}),t.jsx("span",{children:P4(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(ry,{size:14}):t.jsx(So,{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(Sn,{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 A4({status:e}){switch(e){case"generating":return t.jsx(Nt,{size:14,className:"spin planning-sidebar-status-icon planning-sidebar-status-generating"});case"awaiting_input":return t.jsx(Fd,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-awaiting"});case"complete":return t.jsx(Wn,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-complete"});case"error":return t.jsx(Ts,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-error"});default:return t.jsx(Wi,{size:14,className:"planning-sidebar-status-icon"})}}function R4({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 P4(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 I4(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function yf(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 T4({isOpen:e,onClose:n,initialDescription:s,onTasksCreated:a,parentTaskId:r,projectId:o,resumeSessionId:l}){const c=Zs();ji(e);const{keyboardOverlap:d,viewportHeight:u,viewportOffsetTop:m,keyboardOpen:h}=Yi({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,v]=i.useState([]),[N,k]=i.useState(""),[E,y]=i.useState(!0),[j,P]=i.useState(!1),[F,_]=i.useState(!1),[R,L]=i.useState(s),[U,C]=i.useState(null),[$,V]=i.useState(!1),[Y,ne]=i.useState("project-default"),[q,A]=i.useState(""),[I,D]=i.useState(""),[S,G]=i.useState("shared"),[he,Se]=i.useState(null),[Ue,ce]=i.useState(null),[Ae,X]=i.useState(null),Z=i.useRef(null),ee=i.useRef([]),le=i.useRef(!1),K=i.useRef(null),O=p.type==="generating"||p.type==="editing"||p.type==="creating"||p.type==="error"?p.sessionId:null,pe=i.useMemo(()=>Ua(),[]),{isLockedByOther:ve,takeControl:B,isLoading:we}=xc(e?O:null),{activeTabMap:ze,broadcastUpdate:re,broadcastCompleted:He,broadcastLock:Pe,broadcastUnlock:tt,broadcastHeartbeat:qe}=Ir(),de=i.useMemo(()=>x.length===0||x.some(Ie=>!Ie.title.trim())||(Y==="existing"||Y==="custom-new")&&!q.trim()?!0:yf(x),[Y,q,x]),De=p.type==="generating"||p.type==="editing"||p.type==="error",Te=O?ze.get(O):null,{confirm:ct}=ci(),Ve=Te&&Te.tabId!==pe,me=!!(Ve&&!Te.stale),oe=ve&&(!Ve||Te.stale),Me=i.useCallback(()=>{R&&AT(R,o),Z.current?.close(),Z.current=null,g({type:"initial"}),w([]),v([]),k(""),y(!0),P(!1),_(!1),C(null),V(!1),ne("project-default"),A(""),D(""),G("shared"),le.current=!1},[R,o]),Xe=i.useCallback(()=>{Z.current?.close(),Z.current=null,n()},[n]),rt=i.useCallback(async()=>{if(!(($||p.type==="editing"||p.type==="creating")&&!await ct({title:"Discard Changes",message:"Close subtask breakdown? Unsaved changes will be lost.",danger:!0}))){if(O)try{await Zg(O,o,pe)}catch{}Me(),n()}},[$,n,Me,O,pe,p.type,o,ct]),ht=i.useCallback(Ie=>{Z.current?.close(),Z.current=AS(Ie,o,{onThinking:be=>{k(ot=>ot+be),re({sessionId:Ie,status:"generating",needsInput:!1,owningTabId:pe,type:"subtask",title:R.trim()||void 0,projectId:o??null})},onSubtasks:be=>{P(!1),_(!1),fd(o),w(be),g({type:"editing",sessionId:Ie}),V(!1),re({sessionId:Ie,status:"awaiting_input",needsInput:!0,owningTabId:pe,type:"subtask",title:R.trim()||void 0,projectId:o??null})},onError:be=>{const ot=be||"Session failed while contacting the AI.";P(!1),_(!1),C(null),g({type:"error",sessionId:Ie,errorMessage:ot}),re({sessionId:Ie,status:"error",needsInput:!1,owningTabId:pe,type:"subtask",title:R.trim()||void 0,projectId:o??null}),He({sessionId:Ie,status:"error"})},onComplete:()=>{He({sessionId:Ie,status:"complete"})},onConnectionStateChange:be=>{P(be==="reconnecting")}})},[He,re,R,o,pe]),yt=i.useCallback(async()=>{if(R.trim()){C(null),v([]),k(""),P(!1);try{const{sessionId:Ie}=await ES(R.trim(),o);g({type:"generating",sessionId:Ie}),ht(Ie)}catch(Ie){C(Ce(Ie)||"Failed to start subtask breakdown"),g({type:"initial"})}}},[ht,R,o]);i.useEffect(()=>{if(!e){Me();return}if(e&&s&&!le.current)L(s),le.current=!0,yt();else if(e&&!s&&!le.current){const Ie=RT(o);Ie&&L(Ie)}},[e,s,yt,Me]),i.useEffect(()=>{!e||!l||p.type!=="initial"||(async()=>{try{const Ie=await Ai(l);if(!Ie)return;const be=xr(Ie.conversationHistory);if(v(be),Ie.status==="generating"||Ie.status==="awaiting_input")k(Ie.thinkingOutput??""),g({type:"generating",sessionId:l}),ht(l);else if(Ie.status==="complete"&&Ie.result){fd(o);const ot=JSON.parse(Ie.result);w(ot),g({type:"editing",sessionId:l})}else Ie.status==="error"&&(C(null),g({type:"error",sessionId:l,errorMessage:Ie.error??"Session encountered an error"}))}catch(Ie){C(Ce(Ie)||"Failed to resume session")}})()},[ht,e,l,p.type,o]),i.useEffect(()=>{if(!e){K.current&&(tt(K.current,pe),K.current=null);return}if(O&&K.current!==O){K.current&&tt(K.current,pe),Pe(O,pe),K.current=O;return}!O&&K.current&&(tt(K.current,pe),K.current=null)},[Pe,tt,e,O,pe]),i.useEffect(()=>{if(!e||!O||K.current!==O)return;qe(pe);const Ie=setInterval(()=>{qe(pe)},3e4);return()=>{clearInterval(Ie)}},[qe,e,O,pe]),i.useEffect(()=>()=>{Z.current?.close(),K.current&&(tt(K.current,pe),K.current=null)},[tt,pe]),i.useEffect(()=>{if(!e)return;const Ie=be=>{be.key==="Escape"&&(be.preventDefault(),rt())};return document.addEventListener("keydown",Ie),()=>document.removeEventListener("keydown",Ie)},[e,rt]);const Re=i.useCallback((Ie,be)=>{w(ot=>ot.map(gt=>gt.id===Ie?{...gt,...be}:gt)),V(!0)},[]),Ge=i.useCallback(()=>{w(Ie=>[...Ie,I4(Ie.length+1)]),V(!0)},[]),at=i.useCallback(Ie=>{w(be=>be.filter(ot=>ot.id!==Ie).map(ot=>({...ot,dependsOn:ot.dependsOn.filter(gt=>gt!==Ie)}))),V(!0)},[]),ie=i.useCallback(Ie=>be=>{Se(Ie),be.dataTransfer.setData("text/plain",Ie),be.dataTransfer.effectAllowed="move"},[]),Ke=i.useCallback(()=>{Se(null),ce(null),X(null)},[]),je=i.useCallback(Ie=>be=>{if(be.preventDefault(),Ie===he)return;const ot=be.currentTarget.getBoundingClientRect(),gt=ot.top+ot.height/2,xt=be.clientY<gt?"before":"after";ce(Ie),X(xt)},[he]),Fe=i.useCallback(Ie=>be=>{be.preventDefault();const ot=be.dataTransfer.getData("text/plain");if(!ot||ot===Ie){Se(null),ce(null),X(null);return}w(gt=>{const xt=gt.findIndex(pn=>pn.id===ot),jt=gt.findIndex(pn=>pn.id===Ie);if(xt===-1||jt===-1)return gt;const Bt=[...gt],[Jt]=Bt.splice(xt,1);let Vt=jt;return Ae==="after"&&xt<jt&&Vt--,Ae==="after"&&Vt++,Bt.splice(Vt,0,Jt),Bt}),V(!0),Se(null),ce(null),X(null)},[Ae]),Be=i.useCallback(Ie=>{const be=Ie.currentTarget.getBoundingClientRect(),ot=Ie.clientX,gt=Ie.clientY;(ot<be.left||ot>be.right||gt<be.top||gt>be.bottom)&&(ce(null),X(null))},[]),St=i.useCallback((Ie,be)=>{be<0||be>=x.length||(w(ot=>{const gt=[...ot],[xt]=gt.splice(Ie,1);return gt.splice(be,0,xt),gt}),V(!0))},[x.length]),ye=i.useCallback(Ie=>{ee.current[Ie+1]?.focus()},[]),kt=i.useCallback(async()=>{if(!(!O||de)){C(null),g({type:"creating",sessionId:O});try{const Ie=await RS(O,x,r,o,{branchSelection:{mode:Y,...Y==="existing"||Y==="custom-new"?{branchName:q}:{},...I.trim()?{baseBranch:I.trim()}:{}},branchAssignment:{mode:S}});a(Ie.tasks),Me(),n()}catch(Ie){C(Ce(Ie)||"Failed to create tasks"),g({type:"editing",sessionId:O})}}},[I,S,Y,q,de,n,a,r,o,Me,O,x]),It=i.useCallback(async()=>{if(p.type!=="error")return;const Ie=p.sessionId;C(null),_(!0),k(""),g({type:"generating",sessionId:Ie}),ht(Ie);try{await _S(Ie,o,pe)}catch(be){let ot=be;if((Ce(be)||"").includes("not in an error state"))try{const xt=await Ai(Ie);if(!xt)throw new Error("Failed to refresh subtask session.");if(v(xr(xt.conversationHistory)),xt.status==="generating"||xt.status==="awaiting_input")k(xt.thinkingOutput??""),g({type:"generating",sessionId:xt.id}),Z.current?.isConnected()||ht(xt.id);else if(xt.status==="complete"){if(!xt.result)throw new Error("Subtask session is complete but has no result.");fd(o);const jt=JSON.parse(xt.result);w(jt),g({type:"editing",sessionId:xt.id}),V(!1)}else xt.status==="error"&&g({type:"error",sessionId:xt.id,errorMessage:xt.error??"Retry failed. Please try again."});P(!1);return}catch(xt){ot=xt}Z.current?.close(),Z.current=null,g({type:"error",sessionId:Ie,errorMessage:Ce(ot)||"Retry failed. Please try again."}),P(!1)}finally{_(!1)}},[ht,o,pe,p]);return e?t.jsx("div",{className:"modal-overlay open",onClick:Ie=>Ie.target===Ie.currentTarget&&void rt(),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(ic,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Subtask Breakdown"})]}),t.jsxs("div",{className:"modal-header-actions",children:[De&&t.jsx("button",{className:"modal-send-to-background",onClick:Xe,title:"Send to background","aria-label":"Send to background",children:t.jsx(Ao,{size:16})}),t.jsx("button",{className:"modal-close",onClick:()=>void rt(),"aria-label":"Close",children:t.jsx(an,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[U&&t.jsx("div",{className:"form-error planning-error",children:U}),j&&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:R})]})}),p.type==="generating"&&t.jsxs("div",{className:"planning-loading",children:[b.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(oi,{entries:b,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsx(Nt,{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:()=>y(!E),type:"button",children:E?"Hide thinking":"Show thinking"}),E&&N&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:N})})]})]}),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(oi,{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 It(),disabled:F,children:[F?t.jsx(Nt,{size:14,className:"spin"}):t.jsx(fs,{size:14}),t.jsx("span",{className:"icon-ml-6",children:F?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:()=>void rt(),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(oi,{entries:b}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Wn,{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:Y,onChange:Ie=>ne(Ie.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"})]})]}),(Y==="existing"||Y==="custom-new")&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Branch name"}),t.jsx("input",{value:q,onChange:Ie=>A(Ie.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:I,onChange:Ie=>D(Ie.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:S,onChange:Ie=>G(Ie.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((Ie,be)=>{const ot=he===Ie.id,gt=Ue===Ie.id,xt=["task-detail-section","subtask-item",ot?"subtask-item-dragging":"",gt?"subtask-item-drop-target":"",gt&&Ae==="before"?"subtask-item-drop-before":"",gt&&Ae==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:xt,"data-testid":`subtask-item-${be}`,draggable:p.type!=="creating",onDragStart:ie(Ie.id),onDragEnd:Ke,onDragOver:je(Ie.id),onDrop:Fe(Ie.id),onDragLeave:Be,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(sc,{size:16}),t.jsx("strong",{children:Ie.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>St(be,be-1),disabled:p.type==="creating"||be===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(Ra,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>St(be,be+1),disabled:p.type==="creating"||be===x.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(Co,{})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>at(Ie.id),disabled:p.type==="creating",children:[t.jsx(Sn,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:jt=>{ee.current[be]=jt},value:Ie.title,onChange:jt=>Re(Ie.id,{title:jt.target.value}),onKeyDown:jt=>{jt.key==="Enter"&&(jt.preventDefault(),ye(be))},disabled:p.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:8,value:Ie.description,onChange:jt=>Re(Ie.id,{description:jt.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:Ie.suggestedSize,onChange:jt=>Re(Ie.id,{suggestedSize:jt.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(jt=>jt.id!==Ie.id).map(jt=>{const Bt=Ie.dependsOn.includes(jt.id);return t.jsxs("label",{className:`planning-dep-chip ${Bt?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:Bt,onChange:()=>{const Jt=Bt?Ie.dependsOn.filter(Vt=>Vt!==jt.id):[...Ie.dependsOn,jt.id];Re(Ie.id,{dependsOn:Jt})},disabled:p.type==="creating"}),t.jsx("span",{className:"planning-dep-id",children:jt.id}),t.jsx("span",{className:"planning-dep-title",children:jt.title||"Untitled"})]},jt.id)}),be===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),be>0&&x.slice(0,be).filter(jt=>jt.id!==Ie.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},Ie.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:Ge,disabled:p.type==="creating",children:[t.jsx(Cn,{size:16,className:"icon-mr-6"})," Add subtask"]}),yf(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 rt(),disabled:p.type==="creating",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:()=>void kt(),disabled:p.type==="creating"||de,children:p.type==="creating"?t.jsxs(t.Fragment,{children:[t.jsx(Nt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]}),ve&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(ac,{size:16}),t.jsx("span",{children:oe?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),oe&&t.jsx("button",{type:"button",onClick:()=>{B()},disabled:we,className:"btn btn-primary session-lock-take-control",children:we?"Taking control...":"Take Control"})]})})]})]})}):null}const $4=5,D4=1e3,L4=45e3;function gl(){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),v=i.useRef(gl()),N=i.useCallback(C=>{p.current.add(C);const $=v.current;return $.data.length>0&&($.data.forEach(V=>C(V)),$.data=[]),()=>p.current.delete(C)},[]),k=i.useCallback(C=>(g.current.add(C),()=>g.current.delete(C)),[]),E=i.useCallback(C=>{x.current.add(C);const $=v.current;return $.connected&&(C($.connected),$.connected=null),()=>x.current.delete(C)},[]),y=i.useCallback(C=>{w.current.add(C);const $=v.current;return $.scrollback&&(C($.scrollback),$.scrollback=null),()=>w.current.delete(C)},[]),j=i.useCallback(C=>(b.current.add(C),()=>b.current.delete(C)),[]),P=i.useCallback(C=>{const $=d.current;$?.readyState===WebSocket.OPEN&&$.send(JSON.stringify({type:"input",data:C}))},[]),F=i.useCallback((C,$)=>{const V=d.current;V?.readyState===WebSocket.OPEN&&V.send(JSON.stringify({type:"resize",cols:C,rows:$}))},[]),_=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),v.current=gl()},[]),R=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),v.current=gl()},[]),L=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 C=r.current;let V=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(e)}`;n&&(V+=`&projectId=${encodeURIComponent(n)}`);const Y=new WebSocket(Ii(V));d.current=Y,Y.onopen=()=>{if(r.current!==C){Y.close();return}v.current=gl(),a("connected"),u.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===C&&Y.readyState===WebSocket.OPEN&&Y.send(JSON.stringify({type:"ping"}))},L4)},Y.onmessage=ne=>{if(r.current===C)try{const q=JSON.parse(ne.data),A=v.current;switch(q.type){case"data":q.data&&(p.current.size===0&&A.data.push(q.data),p.current.forEach(I=>I(q.data)));break;case"scrollback":q.data&&(A.scrollback=q.data,w.current.forEach(I=>I(q.data)));break;case"connected":q.shell&&q.cwd&&(A.connected={shell:q.shell,cwd:q.cwd},x.current.forEach(I=>I({shell:q.shell,cwd:q.cwd})));break;case"exit":q.exitCode!==void 0&&g.current.forEach(I=>I(q.exitCode));break;case"ping":Y.readyState===WebSocket.OPEN&&Y.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},Y.onclose=ne=>{if(r.current!==C)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(I=>I());return}if(u.current++,u.current>$4){a("disconnected");return}const q=D4*Math.pow(2,u.current-1);a("reconnecting");const A=r.current;m.current=setTimeout(()=>{r.current===A&&(f.current||L())},Math.min(q,16e3))},Y.onerror=()=>{}},[e,n]),U=i.useCallback(()=>{u.current=0,R(),L()},[R,L]);return i.useEffect(()=>(c&&(_(),u.current=0,a("disconnected")),e?L():a("disconnected"),R),[e,n,c,L,R,_]),{connectionStatus:s,sendInput:P,resize:F,onData:N,onExit:k,onConnect:E,onScrollback:y,reconnect:U,onSessionInvalid:j}}const iv="kb-terminal-tabs",z4=15e3,F4=15e3;function wf(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function kf(e){if(typeof window>"u")return[];try{const n=Fn(iv,e);if(n)return JSON.parse(n)}catch{}return[]}function Sd(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function jf(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 B4(e){const[n,s]=i.useState(()=>kf(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(kf(e)),r(!1),l(!0),d(null)},[e]),i.useEffect(()=>{try{ds(iv,JSON.stringify(n),e)}catch{}},[e,n]),i.useEffect(()=>{let E=!1;const y=h.current;return(async()=>{if(!E)try{const P=await jf(yN(e),z4,"listTerminalSessions");if(E||y!==h.current)return;const F=new Set(P.map(_=>_.id));l(!0),s(_=>{if(E||y!==h.current)return _;const L=_.map($=>({...$,_verified:F.has($.sessionId)})).filter($=>$._verified);if(L.length===0)return[];const U=L.map(({_verified:$,...V})=>V);return U.find($=>$.isActive)?U:U.map(($,V)=>({...$,isActive:V===0}))}),r(!0)}catch(P){if(E||y!==h.current)return;const F=Sd(P);F||console.warn("Failed to validate terminal sessions with server:",P),l(!F),r(!0)}})(),()=>{E=!0}},[e]),i.useEffect(()=>{if(n.length===0&&a&&o){const E=h.current,y=setTimeout(()=>{jf(Vo(void 0,void 0,void 0,e),F4,"createTerminalSession").then(j=>{if(E!==h.current)return;const P={id:wf(),sessionId:j.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(F=>F.length>0?F:[...F.map(R=>({...R,isActive:!1})),P]),d(null)}).catch(j=>{if(E!==h.current)return;Sd(j)||console.error(j);const P=j instanceof Error?j.message:typeof j=="string"?j:"Failed to create terminal session";d(P)})},0);return()=>clearTimeout(y)}},[a,o,n.length,u]);const f=i.useCallback(async()=>{const E=await Vo(void 0,void 0,void 0,e),y={id:wf(),sessionId:E.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(j=>[...j.map(F=>({...F,isActive:!1})),y]),y},[n.length]),p=i.useCallback(async()=>f(),[f]),g=i.useCallback(E=>{s(y=>{const j=y.find(R=>R.id===E);if(!j)return y;_m(j.sessionId,e).catch(R=>{console.warn(`Failed to kill terminal session ${j.sessionId}:`,R)});const P=y.findIndex(R=>R.id===E),F=j.isActive,_=y.filter(R=>R.id!==E);if(_.length===0)return[];if(F){const R=Math.min(P,_.length-1);return _.map((L,U)=>({...L,isActive:U===R}))}return _})},[]),x=i.useCallback(E=>{s(y=>{let j=!1;const P=y.map(F=>F.id===E?(j=!0,{...F,isActive:!0}):{...F,isActive:!1});return j?P:y})},[]),w=i.useCallback((E,y)=>{s(j=>j.map(P=>P.id===E?{...P,title:y}:P))},[]),b=i.useCallback(async()=>{s(j=>{const P=j.find(F=>F.isActive);return P&&_m(P.sessionId,e).catch(F=>{console.warn(`Failed to kill old session ${P.sessionId}:`,F)}),j});const E=n.find(j=>j.isActive);if(!E)return;const y=await Vo(void 0,void 0,void 0,e);s(j=>j.map(P=>P.id===E.id?{...P,sessionId:y.sessionId}:P))},[n]),v=i.useCallback(async()=>{const E=n.find(y=>y.isActive);if(E)try{const y=await Vo(void 0,void 0,void 0,e);s(j=>j.map(P=>P.id===E.id?{...P,sessionId:y.sessionId}:P)),d(null)}catch(y){Sd(y)||console.error(y);const j=y instanceof Error?y.message:typeof y=="string"?y:"Failed to create terminal session";d(j)}},[n]),N=n.find(E=>E.isActive)??null,k=i.useCallback(()=>{d(null),h.current+=1,m(E=>E+1)},[]);return{tabs:n,activeTab:N,isReady:a,bootstrapError:c,createTab:p,closeTab:g,setActiveTab:x,updateTabTitle:w,restartActiveTab:b,retryBootstrap:k,replaceActiveTabSession:v}}const U4=1e4,H4=[500,1500,3e3],av="kb-terminal-font-size",ro=14,q4=8,V4=32,W4='"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 K4(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 G4(e){return`\x1B${e}`}const J4=[{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 oo(e){return Math.min(V4,Math.max(q4,e))}function Y4(){if(typeof window>"u")return ro;try{const e=window.localStorage.getItem(av);if(!e)return ro;const n=Number.parseInt(e,10);return Number.isFinite(n)?oo(n):ro}catch{return ro}}function Q4(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 X4(e){return new Promise(n=>setTimeout(n,e))}async function Z4(e,n=H4){let s;for(let a=0;a<=n.length;a+=1)try{return await e()}catch(r){if(!Q4(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 X4(o)}throw s??new Error("Dynamic import failed")}function Nf(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}function e$(){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=t$()-e.offsetTop-e.height;return a>=30&&a>80?a:0}let Cd=null;function t$(){return Cd===null&&(Cd=window.innerHeight),Cd}function n$({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),[v,N]=i.useState(()=>Y4()),[k,E]=i.useState(!1),[y,j]=i.useState(null),P=i.useRef(null),F=i.useRef(null),_=i.useRef(!1);Ti(F,e,"fusion:terminal-modal-size");const R=i.useRef(null),L=i.useRef(null),U=i.useRef(!1),C=i.useRef(!1),$=i.useRef(null),V=i.useRef(()=>{}),Y=i.useRef(null),ne=i.useRef(0),q=i.useRef(v),A=i.useRef(null),I=i.useRef(a);ne.current=g,q.current=v;const D=i.useCallback(Re=>{if(Re&&C.current!==Re)return;const Ge=L.current,at=R.current,ie=$.current;if(!(!Ge||!at)&&!(Re&&C.current!==Re))try{Ge.fit(),ie&&ie(at.cols,at.rows)}catch{}},[]);i.useEffect(()=>{e&&p(Re=>Re+1)},[e]),i.useEffect(()=>{if(!e||!Nf())return;const Re=window.visualViewport;if(!Re)return;const Ge=()=>{const at=e$();x(at),b(Re.height),at>0&&F.current?.scrollIntoView&&F.current.scrollIntoView({block:"end",behavior:"smooth"}),A.current!==null&&(cancelAnimationFrame(A.current),A.current=null);const ie=typeof C.current=="string"?C.current:void 0;A.current=requestAnimationFrame(()=>{A.current=null,D(ie)})};return Ge(),Re.addEventListener("resize",Ge),Re.addEventListener("scroll",Ge),()=>{Re.removeEventListener("resize",Ge),Re.removeEventListener("scroll",Ge),A.current!==null&&(cancelAnimationFrame(A.current),A.current=null),x(0),b(null)}},[D,e]),i.useEffect(()=>{if(!e)return;const Re=F.current;if(!Re||typeof ResizeObserver>"u")return;let Ge=null;const at=new ResizeObserver(()=>{Ge!==null&&cancelAnimationFrame(Ge),Ge=requestAnimationFrame(()=>{Ge=null;const ie=typeof C.current=="string"?C.current:void 0;D(ie)})});return at.observe(Re),()=>{at.disconnect(),Ge!==null&&cancelAnimationFrame(Ge)}},[D,e]);const{tabs:S,activeTab:G,isReady:he,bootstrapError:Se,createTab:Ue,closeTab:ce,setActiveTab:Ae,updateTabTitle:X,restartActiveTab:Z,retryBootstrap:ee,replaceActiveTabSession:le}=B4(a),{connectionStatus:K,sendInput:O,resize:pe,onData:ve,onConnect:B,onExit:we,onScrollback:ze,reconnect:re,onSessionInvalid:He}=O4(G?.sessionId??null,a);$.current=pe,V.current=O,i.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(av,String(v))}catch{}},[v]);const Pe=i.useCallback(()=>{const Re=R.current;if(Re)try{L.current?.fit(),pe(Re.cols,Re.rows)}catch{}},[pe]);i.useEffect(()=>{if(!e||!he)return;const Re=G?.sessionId;if(!Re)return;const Ge=I.current!==a;if(Ge&&(I.current=a),C.current===Re&&R.current&&!Ge)return;R.current&&(C.current!==Re||Ge)&&(R.current.dispose(),R.current=null,L.current=null,C.current=!1,Y.current&&(window.removeEventListener("resize",Y.current),Y.current=null),u(!1),h(null));let at=!0,ie;return(async()=>{const je=Z4(()=>Promise.all([kn(()=>import("./vendor-xterm-DzcZoU0P.js").then(ye=>ye.x),__vite__mapDeps([5,1,6])),kn(()=>import("./addon-fit-C7jRorKK.js").then(ye=>ye.a),__vite__mapDeps([8,1])),kn(()=>import("./addon-web-links-CkJwd4cQ.js").then(ye=>ye.a),__vite__mapDeps([9,1]))])),Fe=new Promise((ye,kt)=>{ie=setTimeout(()=>{kt(new Error("xterm initialization timed out"))},U4)});let Be,St;try{const[{Terminal:ye},{FitAddon:kt},{WebLinksAddon:It}]=await Promise.race([je,Fe]);if(!at||!P.current||R.current)return;Be=new ye({cursorBlink:!0,cursorStyle:"block",fontSize:q.current,fontFamily:W4,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}),St=new kt,Be.loadAddon(St);const Ie=new It;if(Be.loadAddon(Ie),!Nf())try{const{WebglAddon:gt}=await kn(async()=>{const{WebglAddon:jt}=await import("./addon-webgl-BjvOw43o.js").then(Bt=>Bt.a);return{WebglAddon:jt}},__vite__mapDeps([10,1])),xt=new gt;xt.onContextLoss(()=>{xt.dispose()}),Be.loadAddon(xt)}catch{}Be.open(P.current),ie&&clearTimeout(ie);const be=P.current?.querySelector(".xterm-helper-textarea");if(be&&be.focus(),P.current)try{P.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{St.fit();const gt=P.current?.querySelector(".xterm-helper-textarea");gt&&gt.focus()},50),R.current=Be,L.current=St,C.current=Re,ne.current>0&&(A.current!==null&&(cancelAnimationFrame(A.current),A.current=null),A.current=requestAnimationFrame(()=>{A.current=null,D(Re)})),Be.onData(gt=>{C.current===Re&&V.current(gt)});const ot=()=>{if(C.current===Re&&L.current&&R.current)try{L.current.fit();const{cols:gt,rows:xt}=R.current;$.current?.(gt,xt)}catch{}};window.addEventListener("resize",ot),Y.current&&window.removeEventListener("resize",Y.current),Y.current=ot,u(!0),h(null)}catch(ye){if(ie&&clearTimeout(ie),!at)return;const kt=ye instanceof Error?ye.message:"xterm initialization failed";h(kt)}})(),()=>{at=!1,ie&&clearTimeout(ie)}},[D,e,he,G?.sessionId,a]),i.useEffect(()=>{e||(R.current&&(R.current.dispose(),R.current=null),L.current=null,C.current=!1,Y.current&&(window.removeEventListener("resize",Y.current),Y.current=null),u(!1),h(null),U.current=!1,o(null),c(null),E(!1),j(null))},[e]),i.useEffect(()=>{if(!d||!R.current||!G)return;const Re=G.sessionId,Ge=Fe=>{C.current===Re&&R.current?.write(Fe)},at=ve(Fe=>{Ge(Fe)}),ie=ze(Fe=>{Ge(Fe)}),Ke=B(Fe=>{X(G.id,Tu(Fe.shell)||Fe.shell)}),je=we(Fe=>{C.current===Re&&(c(Fe),R.current?.write(`\r
687
- \x1B[33m[Process exited with code ${Fe}]\x1B[0m\r
688
- `))});return()=>{at(),ie(),Ke(),je()}},[d,G?.sessionId,G?.id,G,K,ve,ze,B,we,X]),i.useEffect(()=>{K==="connected"&&s&&U.current!==s&&G&&(U.current=s,setTimeout(()=>{O(s+`
689
- `)},500))},[K,s,O,G,f]),i.useEffect(()=>{if(!d||!R.current)return;R.current.options.fontSize=v,A.current!==null&&(cancelAnimationFrame(A.current),A.current=null);const Re=requestAnimationFrame(()=>{A.current=null,Pe()});return A.current=Re,()=>{A.current===Re&&(cancelAnimationFrame(Re),A.current=null)}},[v,d,Pe]),i.useEffect(()=>{if(!e)return;const Re=Ge=>{if(!(!Ge.ctrlKey&&!Ge.metaKey)){if(Ge.code==="Equal"||Ge.code==="NumpadAdd"){Ge.preventDefault(),N(at=>oo(at+1));return}if(Ge.code==="Minus"||Ge.code==="NumpadSubtract"){Ge.preventDefault(),N(at=>oo(at-1));return}if(Ge.code==="Digit0"||Ge.code==="Numpad0"){Ge.preventDefault(),N(ro);return}}};return window.addEventListener("keydown",Re),()=>window.removeEventListener("keydown",Re)},[e,Pe]),i.useEffect(()=>{if(!e)return;const Re=Ge=>{Ge.key==="Escape"&&n()};return document.addEventListener("keydown",Re),()=>document.removeEventListener("keydown",Re)},[e,n]),i.useEffect(()=>{K==="connected"&&R.current&&setTimeout(()=>{if(!R.current||!P.current)return;const Re=P.current.querySelector(".xterm-helper-textarea");Re&&Re.focus();try{P.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[K]);const tt=i.useCallback(()=>{if(!P.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;R.current?.focus();const Ge=P.current.querySelector(".xterm-helper-textarea");if(!Ge)return;Ge.autocapitalize="off",Ge.autocomplete="off",Ge.autocorrect="off",Ge.spellcheck=!1,Ge.setAttribute("inputmode","text");try{Ge.focus({preventScroll:!0})}catch{Ge.focus()}const at=Ge.value.length;Ge.setSelectionRange(at,at)},[]);i.useEffect(()=>He(()=>{R.current?.clear(),c(null),U.current=!1,R.current&&(R.current.dispose(),R.current=null),L.current=null,C.current=!1,Y.current&&(window.removeEventListener("resize",Y.current),Y.current=null),u(!1),h(null),le().catch(Ge=>{console.error("Failed to replace invalid terminal session:",Ge)})}),[He,le]);const qe=i.useCallback(Re=>{Re.target===Re.currentTarget&&(_.current=!0)},[]),de=i.useCallback(Re=>{_.current&&Re.target===Re.currentTarget&&n(),_.current=!1},[n]),De=i.useCallback(()=>{R.current?.clear()},[]),Te=i.useCallback(async()=>{R.current?.clear(),c(null),U.current=!1;try{await Z()}catch(Re){o(Ce(Re)||"Failed to restart terminal session")}},[Z]),ct=i.useCallback(()=>{R.current&&(R.current.dispose(),R.current=null),L.current=null,C.current=!1,Y.current&&(window.removeEventListener("resize",Y.current),Y.current=null),h(null),u(!1)},[]),Ve=i.useCallback(()=>{window.location.reload()},[]),me=i.useCallback(()=>{N(Re=>oo(Re+1))},[]),oe=i.useCallback(()=>{N(Re=>oo(Re-1))},[]),Me=i.useCallback(Re=>{j(Ge=>Ge===Re?null:Re)},[]),Xe=i.useCallback(Re=>{if(y==="ctrl"){O(K4(Re)),j(null);return}if(y==="alt"){O(G4(Re)),j(null);return}O(Re)},[O,y]),rt=i.useCallback(Re=>{O(Re),j(null)},[O]);if(!e)return null;const ht=()=>{switch(K){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}},yt=!he||!G&&!Se;return t.jsx("div",{className:"modal-overlay open",onMouseDown:qe,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:[S.map(Re=>t.jsxs("div",{className:`terminal-tab ${Re.isActive?"terminal-tab--active":""}`,onClick:()=>Ae(Re.id),title:Re.title,role:"tab","aria-selected":Re.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:Re.title}),S.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:Ge=>{Ge.stopPropagation(),ce(Re.id)},title:"Close tab",children:"×"})]},Re.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:Ue,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(Vi,{size:16}),ht()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[K==="disconnected"&&G&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:re,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(fs,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:Te,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(fs,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:De,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[t.jsx(Sn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),t.jsxs("button",{className:"terminal-clear-btn terminal-clear-btn--shortcut",onClick:()=>E(Re=>!Re),"data-testid":"terminal-shortcut-toggle",title:"Shortcuts","aria-pressed":k,children:[t.jsx(Ew,{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(an,{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:[yt&&!Se&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),Se&&!G&&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: ",Se]}),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(fs,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Ve,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(fs,{size:14}),"Refresh page"]})]})]})}),m&&G&&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:ct,"data-testid":"terminal-reinit-btn",children:[t.jsx(fs,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Ve,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(fs,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:P,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:tt,onTouchStart:tt},G?.sessionId)]}),k&&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 ${y==="ctrl"?"is-active":""}`,"data-testid":"terminal-modifier-ctrl",onClick:()=>Me("ctrl"),"aria-pressed":y==="ctrl",children:"Ctrl"}),t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${y==="alt"?"is-active":""}`,"data-testid":"terminal-modifier-alt",onClick:()=>Me("alt"),"aria-pressed":y==="alt",children:"Alt"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>rt("\x1B"),children:"ESC"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>rt(" "),children:"Tab"})]}),J4.map(Re=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>Xe(Re.key),title:Re.description,children:Re.label},Re.label))]}),t.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[t.jsxs("span",{className:`terminal-connection-status ${K}`,children:[K==="connected"&&"Connected",K==="connecting"&&"Connecting...",K==="reconnecting"&&"Reconnecting...",K==="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:oe,"data-testid":"terminal-font-size-decrease","aria-label":"Decrease terminal font size",children:t.jsx(Qw,{size:14})}),t.jsxs("span",{className:"terminal-font-size-value","data-testid":"terminal-font-size-value",children:[v,"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(Cn,{size:14})})]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • ⌨ Shortcuts panel • Esc close"})]})]})})}const Gr={name:"",command:""};function Sf(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function s$(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function i$({isOpen:e,onClose:n,addToast:s,projectId:a,onRunScript:r}){ji(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(Gr),[x,w]=i.useState(!1),[b,v]=i.useState(null),[N,k]=i.useState(null),E=Gi(n),y=i.useCallback(async()=>{try{d(!0);const V=await vo(a);l(V)}catch(V){s(Ce(V)||"Failed to load scripts","error")}finally{d(!1)}},[s,a]);i.useEffect(()=>{e&&y()},[e,y]);const j=i.useCallback(()=>{m(!0),f(null),g(Gr),k(null)},[]),P=i.useCallback((V,Y)=>{f(V),m(!1),g({name:V,command:Y}),k(null)},[]),F=i.useCallback(()=>{f(null),m(!1),g(Gr),k(null)},[]),_=i.useCallback(V=>{g(Y=>({...Y,name:V})),V&&!Sf(V)?k("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):k(null)},[]),R=i.useCallback(async()=>{const V=p.name.trim(),Y=p.command.trim();if(!V){s("Script name is required","error");return}if(!Sf(V)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!Y){s("Script command is required","error");return}w(!0);try{await SS(V,Y,a),s(h?"Script updated":"Script created","success"),f(null),m(!1),g(Gr),k(null),await y()}catch(ne){const q=Ce(ne);q?.includes("already exists")?s("A script with this name already exists","error"):s(q||"Failed to save script","error")}finally{w(!1)}},[p,h,s,y,a]),L=i.useCallback(async V=>{try{await CS(V,a),s("Script deleted","success"),v(null),h===V&&(f(null),g(Gr)),await y()}catch(Y){s(Ce(Y)||"Failed to delete script","error")}},[h,s,y,a]),U=i.useCallback((V,Y)=>{r&&r(V,Y)},[r]);if(!e)return null;const C=u||h!==null,$=Object.entries(o).map(([V,Y])=>({name:V,command:Y}));return t.jsx("div",{className:"modal-overlay open",...E,"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(Vi,{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(Nt,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),"Loading scripts..."]}):C?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:V=>_(V.target.value),placeholder:"e.g., build, test, lint",disabled:x||h!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:N?"var(--color-error)":void 0}}),N&&t.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:N}),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:V=>g(Y=>({...Y,command:V.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:R,disabled:x||!!N,"data-testid":"script-save-btn",children:x?t.jsxs(t.Fragment,{children:[t.jsx(Nt,{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:$.length===0?"No scripts defined":`${$.length} script${$.length===1?"":"s"}`}),t.jsxs("button",{className:"btn btn-primary",onClick:j,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx(Cn,{size:14}),"Add Script"]})]}),$.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(Vi,{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:$.map(V=>t.jsx("div",{className:"script-card","data-testid":`script-${V.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:V.name})}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:V.command,children:s$(V.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(V.name,V.command),title:"Run script","aria-label":`Run ${V.name}`,"data-testid":`run-script-${V.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[t.jsx(ss,{size:12}),"Run"]}),t.jsx("button",{className:"btn-icon",onClick:()=>P(V.name,V.command),title:"Edit","aria-label":`Edit ${V.name}`,"data-testid":`edit-script-${V.name}`,children:t.jsx(Cn,{size:14,style:{transform:"rotate(45deg)"}})}),b===V.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>L(V.name),title:"Confirm delete","aria-label":`Confirm delete ${V.name}`,"data-testid":`confirm-delete-script-${V.name}`,style:{color:"var(--color-error)"},children:t.jsx(Sn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>v(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${V.name}`,children:t.jsx(an,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>v(V.name),title:"Delete","aria-label":`Delete ${V.name}`,"data-testid":`delete-script-${V.name}`,children:t.jsx(Sn,{size:14})})]})]})},V.name))})]})})]})})}function a$(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 zN(e,o==="."?void 0:o,s);x||r(b.entries)}catch(b){x||(m(Ce(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 r$(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(N=>{o(N),x(null)},[]);i.useEffect(()=>{if(!e||!n){o(""),c(""),u(null),x(null);return}let N=!1;async function k(){h(!0),x(null);try{const E=await FN(e,n,a);N||(o(E.content),c(E.content),u(E.mtime))}catch(E){N||(x(Ce(E)||"Failed to load file"),o(""),c(""),u(null))}finally{N||h(!1)}}return k(),()=>{N=!0}},[e,n,s,a]);const b=r!==l,v=i.useCallback(async()=>{if(!(!e||!n||!b)){p(!0),x(null);try{const N=await BN(e,n,r,a);c(r),u(N.mtime)}catch(N){throw x(Ce(N)||"Failed to save file"),N}finally{p(!1)}}},[e,n,r,b,a]);return{content:r,setContent:w,originalContent:l,loading:m,saving:f,error:g,save:v,hasChanges:b,mtime:d}}const o$=1e4;function l$(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function c$(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function d$(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 ON(e);if(u)return;s(l$(f.project)),r(f.tasks.map(c$)),d(null)}catch(f){u||d(Ce(f)||"Failed to load workspaces")}finally{u||l(!1)}}m();const h=window.setInterval(()=>{m()},o$);return()=>{u=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:a,loading:o,error:c}}function u$(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function m$(e){return e?new Date(e).toLocaleDateString():""}function Cf(e,n){return Q0(e,n)}const Jr={visible:!1,x:0,y:0,entry:null,entryFullPath:""},Ed={type:null,entry:null,entryFullPath:""},h$=200,p$=500,Ef=10;function f$({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 v=e-x,N=n-w;v+h.width>p-b&&(v=p-b-h.width),N+h.height>g-b&&(N=g-b-h.height),v<b&&(v=b),N<b&&(N=b),c({x:v+x,y:N+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:ra,disabled:!1},{id:"move",label:"Move",icon:ek,disabled:!1},{id:"rename",label:"Rename",icon:Os,disabled:!1},...d?[{id:"download-zip",label:"Download as ZIP",icon:So,disabled:!1}]:[{id:"download",label:"Download",icon:Fy,disabled:!1}],{id:"divider",label:"",icon:ra,disabled:!0},{id:"delete",label:"Delete",icon:Sn,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 g$({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 b$({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(Jr),[f,p]=i.useState(Ed),[g,x]=i.useState(!1),[w,b]=i.useState(null),[v,N]=i.useState(!1),[k,E]=i.useState(null),y=i.useRef(null),j=i.useRef(null),P=i.useRef(null),F=i.useRef(!1),_=i.useCallback(()=>{y.current!==null&&(window.clearTimeout(y.current),y.current=null),j.current!==null&&(window.clearTimeout(j.current),j.current=null)},[]),R=i.useCallback(()=>{_(),P.current=null,N(!1),E(null)},[_]);i.useEffect(()=>()=>{_()},[_]);const L=i.useCallback((I,D,S,G)=>{h({visible:!0,x:I,y:D,entry:S,entryFullPath:G})},[]),U=i.useCallback((I,D,S)=>{if(I.touches.length!==1)return;const G=I.touches[0];G&&(R(),P.current={x:G.clientX,y:G.clientY},j.current=window.setTimeout(()=>{N(!0),E(S)},h$),y.current=window.setTimeout(()=>{const he=P.current;he&&(F.current=!0,N(!1),E(null),_(),L(he.x,he.y,D,S))},p$))},[R,_,L]),C=i.useCallback(I=>{const D=P.current,S=I.touches[0];!D||!S||(Math.abs(S.clientX-D.x)>Ef||Math.abs(S.clientY-D.y)>Ef)&&R()},[R]),$=i.useCallback(()=>{R()},[R]);i.useEffect(()=>{if(!m.visible)return;const I=document.querySelector(".file-browser-list"),D=()=>{F.current=!1,R(),h(Jr)};return I?.addEventListener("scroll",D),()=>I?.removeEventListener("scroll",D)},[R,m.visible]),i.useEffect(()=>{if(!m.visible)return;const I=D=>{D.key==="Escape"&&(F.current=!1,h(Jr))};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[m.visible]);const V=i.useCallback((I,D)=>{I.preventDefault(),I.stopPropagation(),R(),F.current=!1,L(I.clientX,I.clientY,D,Cf(n,D.name))},[R,n,L]),Y=i.useCallback(I=>{if(!m.entry)return;F.current=!1;const D=m.entry,S=m.entryFullPath;if(h(Jr),I==="download"){if(!c)return;const G=Jg(c,S,u);window.open(Ii(G),"_blank");return}if(I==="download-zip"){if(!c)return;const G=KN(c,S,u);window.open(Ii(G),"_blank");return}p({type:I,entry:D,entryFullPath:S}),b(null)},[m,c,u]),ne=i.useCallback(async I=>{if(!(!f.type||!f.entry||!c)){x(!0),b(null);try{switch(f.type){case"copy":await HN(c,f.entryFullPath,I,u);break;case"move":await qN(c,f.entryFullPath,I,u);break;case"rename":await WN(c,f.entryFullPath,I,u);break;case"delete":await VN(c,f.entryFullPath,u);break}p(Ed),d?.()}catch(D){b(Ce(D)||"Operation failed")}finally{x(!1)}}},[f,c,d,u]),q=i.useCallback(()=>{p(Ed),b(null)},[]),A=i.useCallback((I,D)=>{if(F.current){F.current=!1;return}m.visible||(I.type==="directory"?a(D):s(D))},[m.visible,a,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(Nt,{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(X0(n))},children:[t.jsx(zn,{size:16,style:{transform:"rotate(-90deg)"}}),"Up one level"]}),t.jsx("span",{className:"file-browser-path",children:n==="."?"Root":Ar(n)})]}),t.jsx("div",{className:"file-browser-list",children:e.length===0?t.jsx("div",{className:"file-browser-empty",children:"(empty directory)"}):e.map(I=>{const D=Cf(n,I.name),S=v&&k===D;return t.jsxs("div",{className:`file-node file-node--${I.type} ${S?"file-node--long-pressing":""}`,onClick:()=>A(I,D),onContextMenu:G=>V(G,I),onTouchStart:G=>U(G,I,D),onTouchMove:C,onTouchEnd:$,onTouchCancel:$,children:[t.jsx("div",{className:"file-node-icon",children:I.type==="directory"?t.jsx(ys,{size:16}):t.jsx(Lg,{size:16})}),t.jsx("div",{className:"file-node-name",children:I.name}),I.type==="file"&&I.size!==void 0&&t.jsx("div",{className:"file-node-size",children:u$(I.size)}),I.mtime&&t.jsx("div",{className:"file-node-time",children:m$(I.mtime)})]},I.name)})}),m.visible&&m.entry&&t.jsx(f$,{x:m.x,y:m.y,entry:m.entry,onAction:Y,onClose:()=>{F.current=!1,h(Jr)}}),f.type&&f.entry&&t.jsx(g$,{type:f.type,entry:f.entry,entryFullPath:f.entryFullPath,onConfirm:ne,onCancel:q,loading:g,error:w})]})}function x$(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function v$({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=x$(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(v=>!v)},[]),b=i.useCallback(v=>{u.current&&(u.current.scrollTop=v.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(Dg,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${h?"btn-primary":""}`,onClick:x,disabled:h,"aria-label":"Preview mode",children:[t.jsx(Er,{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(Rl,{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(Rl,{size:14})})]}),h?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(wi,{remarkPlugins:[ki],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},(v,N)=>t.jsx("div",{className:"file-editor-line-number",children:N+1},`line-${N+1}`))}),t.jsx("textarea",{className:`file-editor-textarea ${c?"file-editor-textarea--wrap":""}`,value:e,onChange:v=>n(v.target.value),onScroll:b,readOnly:s,spellCheck:!1,"aria-label":a?`Editor for ${a}`:"File editor"})]})]})}function y$(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function w$({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(bm,{size:14}):t.jsx(Hd,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(un,{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(bm,{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(Hd,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:y$(c.title)})]},c.id))]})]})]})}const k$=768,j$=280,bl=180,xl=500,_f="fusion:file-browser-sidebar-width",Mf="kb-files-line-numbers",rv=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),N$=new Set([...rv,".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 _d(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return N$.has(n)}function S$(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return rv.has(n)}function C$({initialWorkspace:e="project",onClose:n,onWorkspaceChange:s,projectId:a}){const{projectName:r,workspaces:o}=d$(a),l=i.useRef(null);Ti(l,!0,"fusion:files-modal-size");const c=Gi(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(j$),[v,N]=i.useState(!1),{entries:k,currentPath:E,setPath:y,loading:j,error:P,refresh:F}=a$(d,!0,a),{content:_,setContent:R,originalContent:L,loading:U,saving:C,error:$,save:V,hasChanges:Y,mtime:ne}=r$(d,m,!0,a);i.useEffect(()=>{u(e)},[e]),i.useEffect(()=>{const Z=()=>{p(window.innerWidth<=k$)};return Z(),window.addEventListener("resize",Z),()=>window.removeEventListener("resize",Z)},[]),i.useEffect(()=>{m||x("list")},[m]),i.useEffect(()=>{try{const Z=localStorage.getItem(_f);if(!Z)return;const ee=Number.parseInt(Z,10);if(!Number.isNaN(ee)){const le=Math.max(bl,Math.min(xl,ee));b(le)}}catch{}},[]),i.useEffect(()=>{const Z=Fn(Mf,a);N(Z==="true")},[a]),i.useEffect(()=>{const Z=ee=>{ee.key==="Escape"&&n(),(ee.metaKey||ee.ctrlKey)&&ee.key==="s"&&(ee.preventDefault(),Y&&!C&&V())};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[n,Y,C,V]);const q=i.useCallback(Z=>{h(Z),f&&x("editor")},[f]),A=i.useCallback(()=>{x("list")},[]),I=i.useCallback(()=>{R(L)},[L,R]),D=i.useCallback(Z=>{u(Z),h(null),x("list"),s?.(Z)},[s]),S=i.useCallback(Z=>{try{localStorage.setItem(_f,String(Z))}catch{}},[]),G=i.useCallback(Z=>{if(f)return;Z.preventDefault(),Z.stopPropagation();const ee=Z.currentTarget;typeof ee.setPointerCapture=="function"&&ee.setPointerCapture(Z.pointerId);const le=Z.clientX,K=w;let O=K;document.body.style.userSelect="none";const pe=B=>{const we=B.clientX-le,ze=Math.max(bl,Math.min(xl,K+we));O=ze,b(ze)},ve=B=>{typeof ee.releasePointerCapture=="function"&&ee.releasePointerCapture(B.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",pe),document.removeEventListener("pointerup",ve),S(O)};document.addEventListener("pointermove",pe),document.addEventListener("pointerup",ve)},[f,S,w]),he=i.useCallback(Z=>{if(f)return;const ee=20;if(Z.key!=="ArrowLeft"&&Z.key!=="ArrowRight")return;Z.preventDefault();const le=Z.key==="ArrowLeft"?-ee:ee,K=Math.max(bl,Math.min(xl,w+le));b(K),S(K)},[f,S,w]),Se=i.useCallback(()=>{N(Z=>{const ee=!Z;return ds(Mf,String(ee),a),ee})},[a]),ce=`Files — ${i.useMemo(()=>d==="project"?"Project":o.find(Z=>Z.id===d)?.id??d,[d,o])}`,Ae=i.useMemo(()=>!m||!S$(m)?null:Jg(d,m,a),[m,d,a]),X=Z=>{const ee=new Blob([Z]).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(ys,{size:18}),t.jsx("span",{children:ce}),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 ${v?"btn-primary":""}`,onClick:Se,"aria-label":"Toggle line numbers","aria-pressed":v,title:"Toggle line numbers",children:[t.jsx($w,{size:14}),t.jsx("span",{children:"Line #"})]}),t.jsx(w$,{currentWorkspace:d,projectName:r,workspaces:o,onSelect:D}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(an,{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(b$,{entries:k,currentPath:E,onSelectFile:q,onNavigate:y,loading:j,error:P,onRetry:F,workspace:d,onRefresh:F,projectId:a})}),!f&&t.jsx("div",{className:"file-browser-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":bl,"aria-valuemax":xl,"aria-valuenow":w,"aria-label":"Resize sidebar",tabIndex:0,onPointerDown:G,onKeyDown:he}),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(Fa,{size:16}),t.jsx("span",{children:"Back"})]}),m,_d(m)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(iw,{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:!Ae&&Y&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:I,disabled:C,children:[t.jsx(fk,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void V(),disabled:C,children:[t.jsx(Ug,{size:14}),C?"Saving...":"Save"]})]})})]}),$&&!Ae&&t.jsx("div",{className:"file-browser-error-banner",children:$}),Ae?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:Ae,alt:m??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(v$,{content:_,onChange:R,filePath:m,readOnly:_d(m),showLineNumbers:v&&!_d(m)})}),!Ae&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:X(_)}),Y&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(ys,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}const E$=i.lazy(()=>kn(()=>import("./TodoView-CTmIfy2M.js"),__vite__mapDeps([11,1,5,6,12])).then(e=>({default:e.TodoView})));function _$({onClose:e,projectId:n,addToast:s,onPlanningMode:a}){const r=Gi(e),l=Zs()==="mobile",{keyboardOverlap:c,viewportHeight:d,viewportOffsetTop:u,keyboardOpen:m}=Yi({enabled:l});ji(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(Iw,{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(an,{size:20})})]}),t.jsx("div",{className:"todo-modal-body",children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(E$,{projectId:n,addToast:s,onPlanningMode:a,onClose:e,mobileKeyboardActive:l&&m})})})]})})}function M$(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 Bj();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:Ce(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 A$(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 R$(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const ov="kb-usage-hidden-windows",lv="kb-usage-modal-size",cv="kb-usage-provider-order";function Af(e){const n=Fn(lv,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 Rf(e){const n=Fn(ov,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 P$(e,n){ds(ov,JSON.stringify(e),n)}function Pf(e){const n=Fn(cv,e);if(!n)return[];try{const s=JSON.parse(n);return Array.isArray(s)?s.filter(a=>typeof a=="string"):[]}catch{return[]}}function If(e,n){ds(cv,JSON.stringify(e),n)}function dv(e,n,s){return s[e]?.includes(n)??!1}function I$({window:e,viewMode:n,isHidden:s,onToggleHidden:a}){const r=R$(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),v=Math.floor(b/24),N=b%24;v>0&&N>0?u=`resets in ${v}d ${N}h`:v>0?u=`resets in ${v}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(Er,{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:A$(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(Ro,{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(Lk,{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(Wn,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:m.message})]})]})]})}function T$(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 $$({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 v=s[e.name]?.length??0,N=()=>{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(Tn,{provider:T$(e.name),size:"md"}),t.jsx("span",{className:"usage-provider-name",children:e.name}),v>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 (",v,")"]})]}),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(Ri,{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(un,{size:14})})]}),N(),t.jsx("div",{className:"usage-provider-drag-handle","aria-hidden":"true",children:t.jsx(sc,{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((k,E)=>{const y=dv(e.name,k.label,s);return t.jsx(I$,{window:k,viewMode:n,isHidden:y,onToggleHidden:()=>a(e.name,k.label)},`${e.name}-${k.label}-${E}`)})}):e.status==="ok"?t.jsx("div",{className:"usage-provider-empty",children:"No usage data available"}):null]})}function D$(){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 L$({isOpen:e,onClose:n,projectId:s,anchorRect:a}){const{providers:r,loading:o,error:l,lastUpdated:c,refresh:d}=M$({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,v]=i.useState(()=>Rf(s)),[N,k]=i.useState(()=>Pf(s)),[E,y]=i.useState(null),[j,P]=i.useState(null),[F,_]=i.useState(null),R=i.useRef(null),L=i.useRef(null),U=i.useRef(e),C=i.useRef(!1),[$,V]=i.useState(()=>Af(s));i.useEffect(()=>{V(Af(s))},[s]),i.useEffect(()=>{if(!e||!h)return;const B=L.current;if(!B||typeof ResizeObserver>"u")return;let we=null;const ze=new ResizeObserver(re=>{const He=re[0];if(!He)return;const{width:Pe,height:tt}=He.contentRect;Pe<=0||tt<=0||(we&&clearTimeout(we),we=setTimeout(()=>{ds(lv,JSON.stringify({width:Math.round(Pe),height:Math.round(tt)}),s)},250))});return ze.observe(B),()=>{we&&clearTimeout(we),ze.disconnect()}},[e,h,s]),i.useEffect(()=>{e||(C.current=!1)},[e]),i.useEffect(()=>{r.length>0&&(C.current=!0)},[r.length]),i.useEffect(()=>{if(typeof window>"u")return;const B=window.matchMedia?.("(pointer: coarse)"),we=()=>{f(window.innerWidth>=769),g(B?.matches??!1)};return we(),window.addEventListener("resize",we),B?.addEventListener?.("change",we),()=>{window.removeEventListener("resize",we),B?.removeEventListener?.("change",we)}},[]),i.useEffect(()=>{!U.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&d(),U.current=e},[e,c,d]),i.useEffect(()=>{const B=Fn("kb-usage-view-mode",s);if(B==="used"||B==="remaining"){w(B);return}w("used")},[s]);const Y=i.useCallback(B=>{w(B),ds("kb-usage-view-mode",B,s)},[s]);i.useEffect(()=>{v(Rf(s)),k(Pf(s))},[s]),i.useEffect(()=>{P$(b,s)},[b,s]);const ne=i.useCallback((B,we)=>{v(ze=>{if(dv(B,we,ze)){const re=(ze[B]??[]).filter(He=>He!==we);if(re.length===0){const{[B]:He,...Pe}=ze;return Pe}return{...ze,[B]:re}}return{...ze,[B]:[...ze[B]??[],we]}})},[]),q=i.useCallback(B=>{v(we=>{if(!we[B])return we;const{[B]:ze,...re}=we;return re})},[]),A=i.useCallback(B=>{if(N.length===0)return B;const we=new Map(B.map(re=>[re.name,re])),ze=[];for(const re of N){const He=we.get(re);He&&(ze.push(He),we.delete(re))}return[...ze,...we.values()]},[N]),I=i.useCallback((B,we)=>{B.dataTransfer.effectAllowed="move",B.dataTransfer.setData("text/plain",we),y(we)},[]),D=i.useCallback((B,we)=>{if(!E||E===we)return;B.preventDefault(),B.dataTransfer.dropEffect="move";const{top:ze,height:re}=B.currentTarget.getBoundingClientRect(),He=ze+re/2,Pe=B.clientY<He?"before":"after";P(we),_(Pe)},[E]),S=i.useCallback((B,we)=>{B.preventDefault();const ze=E??B.dataTransfer.getData("text/plain");if(!ze||ze===we){P(null),_(null);return}const He=A(r).map(qe=>qe.name).filter(qe=>qe!==ze),Pe=He.indexOf(we);if(Pe<0){P(null),_(null);return}const tt=F==="after"?Pe+1:Pe;He.splice(tt,0,ze),If(He,s),k(He),P(null),_(null)},[E,F,s,r,A]),G=i.useCallback(()=>{y(null),P(null),_(null)},[]),he=i.useCallback((B,we)=>{const ze=A(r).map(qe=>qe.name),re=ze.indexOf(B),He=re+we;if(re<0||He<0||He>=ze.length)return;const Pe=[...ze],[tt]=Pe.splice(re,1);Pe.splice(He,0,tt),If(Pe,s),k(Pe)},[s,r,A]),Se=i.useCallback(async()=>{m(!0),await d(),m(!1)},[d]);i.useEffect(()=>{if(!e)return;const B=we=>{we.key==="Escape"&&n()};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[e,n]);const Ue=i.useCallback(B=>{B.target===B.currentTarget&&n()},[n]);if(!e)return null;const ce=!!(a&&h),Ae=8,X=12,ee=$?.width??420,le=ce?Math.min((a?.bottom??0)+Ae,window.innerHeight-X):void 0,K=ce?Math.max(8,(a?.right??0)-ee):void 0,O=h&&$?{width:$.width,height:$.height}:{},pe=A(r),ve=t.jsxs("div",{ref:L,className:`usage-modal${ce?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:ce?{position:"fixed",top:le,left:K,...O}:O,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:()=>Y("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:()=>Y("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(an,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:R,children:(o||!C.current&&!l)&&r.length===0?t.jsx(D$,{}):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:Se,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,we)=>t.jsx($$,{provider:B,viewMode:x,hiddenWindows:b,onToggleWindow:ne,onShowAllHidden:q,isDragging:E===B.name,isDragOver:j===B.name,dragOverPosition:j===B.name?F:null,onDragStart:ze=>I(ze,B.name),onDragOver:ze=>D(ze,B.name),onDragLeave:()=>{j===B.name&&(P(null),_(null))},onDrop:ze=>S(ze,B.name),onDragEnd:G,isTouchReorderMode:p,canMoveUp:we>0,canMoveDown:we<pe.length-1,onMoveUp:()=>he(B.name,-1),onMoveDown:()=>he(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:Se,disabled:o||u,"data-testid":"usage-refresh-btn",children:[t.jsx(fs,{size:14,className:u?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]});return ce?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"usage-popover-backdrop",onClick:n,"data-testid":"usage-modal-overlay"}),ve]}):t.jsx("div",{className:"modal-overlay open",onClick:Ue,"data-testid":"usage-modal-overlay",children:ve})}function uv(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 Kl(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 O$={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},mv={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},z$={cron:Pg,webhook:Hg,api:Ig,manual:is},F$={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},B$={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function U$({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(Wn,{size:12}):t.jsx(_o,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:uv(n)})]})}function H$({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"} ${Kl(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(Wn,{size:12}):t.jsx(_o,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:Kl(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:mv[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:uv(r)}),s?t.jsx(Ri,{size:12}):t.jsx(un,{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 q$({routine:e,onEdit:n,onDelete:s,onRun:a,onToggle:r,running:o,lastRunOutput:l}){const[c,d]=i.useState(!1),{confirm:u}=ci(),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=O$[e.trigger.type],f=z$[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}),mv[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(tc,{size:10}):t.jsx(ys,{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(Nt,{className:"spinner"}):t.jsx(ss,{})}),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(xi,{}):t.jsx(ss,{})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(Os,{})}),t.jsx("button",{className:"btn-icon",onClick:m,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(Sn,{})})]})]}),t.jsxs("div",{className:"routine-card-meta",children:[e.steps&&e.steps.length>0?t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(Ia,{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(Wi,{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:F$[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:B$[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:Kl(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:Kl(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(U$,{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(Ri,{size:12}):t.jsx(un,{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(H$,{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 V$({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(Vi,{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(Lw,{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(xs,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function Md(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function W$(e){return e==="command"?{id:Md(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:Md(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:Md(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function K$({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,v]=i.useState(e.taskDescription??""),[N,k]=i.useState(e.taskColumn??"triage"),[E,y]=i.useState(e.timeoutMs),[j,P]=i.useState(e.continueOnFailure??!1),[F,_]=i.useState({}),[R,L]=i.useState([]),[U,C]=i.useState(!1),[$,V]=i.useState(null);i.useEffect(()=>{let I=!1;return C(!0),V(null),Fs().then(D=>{I||L(D.models)}).catch(D=>{I||V(D instanceof Error?D.message:"Failed to load models")}).finally(()=>{I||C(!1)}),()=>{I=!0}},[]);const Y=i.useCallback(()=>{const I={};return a.trim()||(I.name="Step name is required"),o==="command"&&!c.trim()&&(I.command="Command is required"),o==="ai-prompt"&&!u.trim()&&(I.prompt="Prompt is required"),o==="create-task"&&!b.trim()&&(I.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(h||p)&&(!h||!p)&&(I.modelProvider="Both model provider and model ID must be set together"),E!==void 0&&E<1e3&&(I.timeoutMs="Timeout must be at least 1 second (1000ms)"),_(I),Object.keys(I).length===0},[a,o,c,u,b,h,p,E]),ne=h&&p?`${h}/${p}`:"",q=i.useCallback(I=>{if(!I)f(""),g("");else{const D=I.indexOf("/");D!==-1&&(f(I.slice(0,D)),g(I.slice(D+1)))}},[]),A=i.useCallback(()=>{if(!Y())return;const I={...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"?N: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:E||void 0,continueOnFailure:j};o!=="ai-prompt"&&delete I.prompt,o!=="create-task"&&(delete I.taskTitle,delete I.taskDescription,delete I.taskColumn),n(I)},[Y,n,e,a,o,c,u,x,b,N,h,p,E,j]);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:I=>r(I.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:I=>l(I.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:I=>d(I.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:I=>m(I.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(Ns,{id:`step-model-${e.id}`,label:"Model",models:R,value:ne,onChange:q,placeholder:"Use default",disabled:U}),$&&t.jsx("small",{className:"field-error",children:$}),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:I=>w(I.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:I=>v(I.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:N,onChange:I=>k(I.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(Ns,{id:`step-task-model-${e.id}`,label:"Model",models:R,value:ne,onChange:q,placeholder:"Use default",disabled:U}),$&&t.jsx("small",{className:"field-error",children:$}),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:E??"",onChange:I=>y(I.target.value?Number(I.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:j,onChange:I=>P(I.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 G$({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=W$(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(K$,{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(sc,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(V$,{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(Ri,{})}),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(un,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(u.id),title:"Edit","aria-label":`Edit ${u.name}`,children:t.jsx(Os,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(u.id),title:"Delete","aria-label":`Delete ${u.name}`,children:t.jsx(Sn,{})})]})]})},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(Cn,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx(Cn,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx(Cn,{size:14}),"Add Create Task Step"]})]})]})}const hv={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},J$={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function Y$(e){const n=e.trim();for(const[s,a]of Object.entries(hv))if(a===n)return s;return"custom"}function Q$(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function X$(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 Z$(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 eD=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],tD=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function Tf(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function $f({routine:e,onSubmit:n,onCancel:s,scope:a,projectId:r,onScopeChange:o}){const l=!!e,c=e?Z$(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":Y$(c.cronExpression)),[v,N]=i.useState(c.webhookPath),[k,E]=i.useState(c.webhookSecret),[y,j]=i.useState(c.endpoint),[P,F]=i.useState(e?.executionPolicy??"queue"),[_,R]=i.useState(e?.catchUpPolicy??"run_one"),[L,U]=i.useState(e?.enabled??!0),C=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,$=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[V,Y]=i.useState(e?.steps&&e.steps.length>0&&!C&&!$?"advanced":"simple"),[ne,q]=i.useState(()=>C?"ai-prompt":$?"create-task":"command"),[A,I]=i.useState(e?.command??""),[D,S]=i.useState(e?.steps??[]),[G,he]=i.useState(!1),[Se,Ue]=i.useState(e?.timeoutMs??3e5),[ce,Ae]=i.useState(C?e.steps?.[0]?.prompt??"":""),[X,Z]=i.useState($?e.steps?.[0]?.taskTitle??"":""),[ee,le]=i.useState($?e.steps?.[0]?.taskDescription??"":""),[K,O]=i.useState($?e.steps?.[0]?.taskColumn??"triage":"triage"),[pe,ve]=i.useState(C||$?e.steps?.[0]?.modelProvider??"":""),[B,we]=i.useState(C||$?e.steps?.[0]?.modelId??"":""),[ze,re]=i.useState([]),[He,Pe]=i.useState(!1),[tt,qe]=i.useState(null),[de,De]=i.useState(a??"global"),[Te,ct]=i.useState({}),[Ve,me]=i.useState(!1),oe=i.useRef(!0);i.useEffect(()=>()=>{oe.current=!1},[]),i.useEffect(()=>{a&&De(a)},[a]),i.useEffect(()=>{let ye=!1;return Pe(!0),qe(null),Fs().then(kt=>{ye||re(kt.models)}).catch(kt=>{ye||qe(kt instanceof Error?kt.message:"Failed to load models")}).finally(()=>{ye||Pe(!1)}),()=>{ye=!0}},[]);const Me=pe&&B?`${pe}/${B}`:"",Xe=i.useCallback(ye=>{if(!ye){ve(""),we("");return}const kt=ye.indexOf("/");kt!==-1&&(ve(ye.slice(0,kt)),we(ye.slice(kt+1)))},[]),rt=i.useCallback(()=>{const ye={};if(d.trim()||(ye.name="Name is required"),de==="project"&&!r&&(ye.scope="Project-specific entries require an active project."),f==="cron"&&w==="custom"&&(g.trim()?Q$(g)||(ye.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):ye.cronExpression="Cron expression is required"),f==="webhook"&&!v.trim()&&(ye.webhookPath="Webhook path is required"),f==="api"&&!y.trim()&&(ye.endpoint="API endpoint is required"),V==="simple")ne==="command"&&!A.trim()&&(ye.command="Command is required"),ne==="ai-prompt"&&!ce.trim()&&(ye.prompt="Prompt is required"),ne==="create-task"&&!ee.trim()&&(ye.taskDescription="Task description is required"),(pe.trim()&&!B.trim()||!pe.trim()&&B.trim())&&(ye.model="Both model provider and model ID must be set, or both must be empty");else{D.length===0&&(ye.steps="At least one step is required"),G&&(ye.stepsEditing="Please save or cancel all step edits before saving the routine");const kt=[];D.forEach((It,Ie)=>{It.name?.trim()||kt.push(`Step ${Ie+1}: Name is required`),It.type==="command"&&!It.command?.trim()&&kt.push(`Step ${Ie+1}: Command is required`),It.type==="ai-prompt"&&!It.prompt?.trim()&&kt.push(`Step ${Ie+1}: Prompt is required`),It.type==="create-task"&&!It.taskDescription?.trim()&&kt.push(`Step ${Ie+1}: Task description is required`)}),kt.length>0&&(ye.steps=kt.join("; "))}return Se<1e3&&(ye.timeoutMs="Timeout must be at least 1 second (1000ms)"),ct(ye),Object.keys(ye).length===0},[d,f,g,w,v,y,de,r,V,ne,A,ce,ee,pe,B,D,G,Se]),ht=i.useCallback(async ye=>{if(ye.preventDefault(),!!rt()){me(!0);try{let kt=e?.scope??de??(r?"project":"global");kt==="project"&&!r&&(kt="global");const It=X$(f,g,v,k,y);let Ie,be;V==="simple"?ne==="command"?Ie=A.trim()||void 0:ne==="ai-prompt"?be=[{id:Tf(),type:"ai-prompt",name:d.trim(),prompt:ce.trim(),modelProvider:pe.trim()||void 0,modelId:B.trim()||void 0}]:be=[{id:Tf(),type:"create-task",name:d.trim(),taskTitle:X.trim()||void 0,taskDescription:ee.trim(),taskColumn:K,modelProvider:pe.trim()||void 0,modelId:B.trim()||void 0}]:be=D;const ot={name:d.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:It,command:Ie,steps:be,timeoutMs:Se,executionPolicy:P,catchUpPolicy:_,enabled:L,scope:kt};await n(ot)}finally{oe.current&&me(!1)}}},[rt,n,d,m,f,g,v,k,y,V,ne,A,ce,pe,B,X,ee,K,D,Se,P,_,L,de,r,e?.scope,e?.agentId]),yt="routine-name-error",Re="routine-cron-error",Ge="routine-webhook-error",at="routine-endpoint-error",ie="routine-command-error",Ke="routine-prompt-error",je="routine-task-description-error",Fe="routine-model-error",Be="routine-timeout-error",St=i.useCallback(ye=>{b(ye),ye!=="custom"&&x(hv[ye])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:ht,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:ye=>u(ye.target.value),"aria-invalid":!!Te.name,"aria-describedby":Te.name?yt:void 0}),Te.name&&t.jsx("small",{id:yt,className:"field-error",children:Te.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:ye=>h(ye.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:()=>{De("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(tc,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${de==="project"?" active":""}`,onClick:()=>{De("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(ys,{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."}),Te.scope&&t.jsx("small",{className:"field-error",children:Te.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(Pg,{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(Hg,{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(Ig,{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(is,{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:ye=>St(ye.target.value),children:Object.entries(J$).map(([ye,kt])=>t.jsx("option",{value:ye,children:kt},ye))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:g,onChange:ye=>x(ye.target.value),disabled:w!=="custom","aria-invalid":!!Te.cronExpression,"aria-describedby":Te.cronExpression?Re:void 0}),Te.cronExpression?t.jsx("small",{id:Re,className:"field-error",children:Te.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:v,onChange:ye=>N(ye.target.value),"aria-invalid":!!Te.webhookPath,"aria-describedby":Te.webhookPath?Ge:void 0}),Te.webhookPath?t.jsx("small",{id:Ge,className:"field-error",children:Te.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:k,onChange:ye=>E(ye.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:y,onChange:ye=>j(ye.target.value),"aria-invalid":!!Te.endpoint,"aria-describedby":Te.endpoint?at:void 0}),Te.endpoint?t.jsx("small",{id:at,className:"field-error",children:Te.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${V==="simple"?" active":""}`,onClick:()=>Y("simple"),role:"radio","aria-checked":V==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${V==="advanced"?" active":""}`,onClick:()=>Y("advanced"),role:"radio","aria-checked":V==="advanced",children:"Multi-Step"})]}),t.jsx("small",{children:V==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),V==="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:()=>q("command"),role:"radio","aria-checked":ne==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${ne==="ai-prompt"?" active":""}`,onClick:()=>q("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:()=>q("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:ye=>I(ye.target.value),"aria-invalid":!!Te.command,"aria-describedby":Te.command?ie:void 0}),Te.command?t.jsx("small",{id:ie,className:"field-error",children:Te.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:ce,onChange:ye=>Ae(ye.target.value),rows:3,"aria-invalid":!!Te.prompt,"aria-describedby":Te.prompt?Ke:void 0}),Te.prompt?t.jsx("small",{id:Ke,className:"field-error",children:Te.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(Ns,{id:"routine-model",label:"Model",models:ze,value:Me,onChange:Xe,placeholder:"Use default",disabled:He}),tt&&t.jsx("small",{className:"field-error",children:tt}),Te.model&&t.jsx("small",{id:Fe,className:"field-error",children:Te.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:X,onChange:ye=>Z(ye.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:ye=>le(ye.target.value),rows:4,"aria-invalid":!!Te.taskDescription,"aria-describedby":Te.taskDescription?je:void 0}),Te.taskDescription?t.jsx("small",{id:je,className:"field-error",children:Te.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:K,onChange:ye=>O(ye.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(Ns,{id:"routine-task-model",label:"Executor Model",models:ze,value:Me,onChange:Xe,placeholder:"Use default",disabled:He}),tt&&t.jsx("small",{className:"field-error",children:tt}),Te.model&&t.jsx("small",{id:Fe,className:"field-error",children:Te.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(G$,{steps:D,onChange:S,onEditingChange:he}),Te.steps&&t.jsx("small",{className:"field-error",children:Te.steps}),Te.stepsEditing&&t.jsx("small",{className:"field-error",children:Te.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:Se,onChange:ye=>Ue(Number(ye.target.value)),"aria-invalid":!!Te.timeoutMs,"aria-describedby":Te.timeoutMs?Be:void 0}),Te.timeoutMs?t.jsx("small",{id:Be,className:"field-error",children:Te.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:P,onChange:ye=>F(ye.target.value),children:eD.map(ye=>t.jsx("option",{value:ye.value,children:ye.label},ye.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:ye=>R(ye.target.value),children:tD.map(ye=>t.jsx("option",{value:ye.value,children:ye.label},ye.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:L,onChange:ye=>U(ye.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:Ve,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:Ve,children:Ve?"Saving…":l?"Save Changes":"Create Routine"})]})]})}const nD=3e4;function sD({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);Ti(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 C=await pS(w);l(C),g($=>{const V={...$};for(const Y of C){const ne=V[Y.id];if(!ne||!Y.lastRunResult)continue;const q=Y.lastRunResult;q.success===ne.success&&(q.output||"")===ne.output&&(q.error||"")===(ne.error||"")&&delete V[Y.id]}return V})}catch(C){n(Ce(C)||"Failed to load routines","error")}},[n,w]);i.useEffect(()=>{b()},[b]),i.useEffect(()=>{const C=setInterval(()=>{b()},nD);return()=>clearInterval(C)},[b]),i.useEffect(()=>{const C=$=>{$.key==="Escape"&&(c!=="list"?(d("list"),m(void 0)):e())};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[e,c]);const v=Gi(e),N=i.useCallback(async C=>{try{await fS(C,w),n("Routine created","success"),d("list"),await b()}catch($){n(Ce($)||"Failed to create routine","error")}},[n,b,w]),k=i.useCallback(C=>{m(C),d("edit")},[]),E=i.useCallback(async C=>{if(u)try{await $m(u.id,C,w),n("Routine updated","success"),d("list"),m(void 0),await b()}catch($){n(Ce($)||"Failed to update routine","error")}},[u,n,b,w]),y=i.useCallback(async C=>{try{await gS(C.id,w),n(`Deleted "${C.name}"`,"success"),await b()}catch($){n(Ce($)||"Failed to delete routine","error")}},[n,b,w]),j=i.useCallback(async C=>{f(C.id);try{const{result:$}=await bS(C.id,w);g(V=>({...V,[C.id]:{output:$.output||"",error:$.error,success:$.success}})),$.success?n(`"${C.name}" completed successfully`,"success"):n(`"${C.name}" failed: ${$.error||"Unknown error"}`,"error"),await b()}catch($){n(Ce($)||"Failed to run routine","error")}finally{f(null)}},[n,b,w]),P=i.useCallback(async C=>{try{await $m(C.id,{enabled:!C.enabled},w),n(`"${C.name}" ${C.enabled?"disabled":"enabled"}`,"success"),await b()}catch($){n(Ce($)||"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(C=>{r(C),d("list"),m(void 0),g({})},[]),R=()=>c==="create"?t.jsx($f,{onSubmit:N,onCancel:F,scope:a,projectId:s}):c==="edit"&&u?t.jsx($f,{routine:u,onSubmit:E,onCancel:F,scope:a,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(is,{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(Cn,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map(C=>t.jsx(q$,{routine:C,onEdit:k,onDelete:y,onRun:j,onToggle:P,running:h===C.id,lastRunOutput:p[C.id]??null},C.id))}),L=()=>R(),U=c==="list"&&o.length>0;return t.jsx("div",{className:"modal-overlay open",...v,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(is,{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(an,{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(tc,{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(ys,{size:14}),"Project"]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(is,{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(Cn,{size:14}),"New Automation"]})})]}),t.jsx("div",{className:"schedule-modal-content",id:"scheduled-tasks-content",children:L()})]})})}const iD=3e4,bu=new Map,Ad=new Map;function Df(e){return e??"default"}function Lf(e){const n=bu.get(e);return n?Date.now()>=n.expiresAt?(bu.delete(e),null):n:null}function aD(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 rD(e){const n=Ad.get(e);if(n)return n;const s=xo().then(({providers:a,ghCli:r})=>{const l={...aD(a,r),ghCli:r,expiresAt:Date.now()+iD};return bu.set(e,l),l}).finally(()=>{Ad.delete(e)});return Ad.set(e,s),s}function pv(e){const n=Df(e),s=Lf(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=Df(e),p=Lf(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 rD(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 fv({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(an,{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 oD({isOpen:e,onClose:n,projectId:s,tasks:a,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const{confirm:d}=ci(),u=Zs();ji(e);const{keyboardOverlap:m,viewportHeight:h,viewportOffsetTop:f,keyboardOpen:p}=Yi({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,v]=i.useState([]),[N,k]=i.useState(""),[E,y]=i.useState(""),[j,P]=i.useState([]),[F,_]=i.useState(!1),[R,L]=i.useState(""),[U,C]=i.useState(""),[$,V]=i.useState(""),[Y,ne]=i.useState(""),[q,A]=i.useState(""),[I,D]=i.useState("default"),[S,G]=i.useState(!1),[he,Se]=i.useState([]),[Ue,ce]=i.useState(!1),[Ae,X]=i.useState(void 0),[Z,ee]=i.useState(Ms),[le,K]=i.useState(void 0),[O,pe]=i.useState(!1),[ve,B]=i.useState(""),[we,ze]=i.useState(null),[re,He]=i.useState([]),[Pe,tt]=i.useState(!1),[qe,de]=i.useState(!1),De=i.useRef(null),[Te,ct]=i.useState(!1),[Ve,me]=i.useState(""),oe=i.useRef(null),{hasAiProvider:Me,hasGithub:Xe,loading:rt}=pv(s),{nodes:ht}=uc(),yt=i.useCallback(be=>{ce(!0),Se(be)},[]),Re=i.useCallback(()=>{ce(!1)},[]),Ge=i.useCallback(async()=>{if(re.length>0){tt(!0);return}de(!0);try{const be=await Mr(void 0,s);He(be),tt(!0)}catch(be){const ot=Ce(be);o(ot?`Failed to load agents: ${ot}`:"Failed to load agents","error"),tt(!1)}finally{de(!1)}},[re.length,s,o]);i.useEffect(()=>{if(!Pe)return;const be=ot=>{De.current&&!De.current.contains(ot.target)&&tt(!1)};return document.addEventListener("mousedown",be),()=>document.removeEventListener("mousedown",be)},[Pe]),i.useEffect(()=>{if(!Te)return;const be=ot=>{oe.current&&!oe.current.contains(ot.target)&&(ct(!1),me(""))};return document.addEventListener("mousedown",be),()=>document.removeEventListener("mousedown",be)},[Te]);const at=a.filter(be=>!b.includes(be.id)).sort((be,ot)=>{const gt=ot.createdAt.localeCompare(be.createdAt);if(gt!==0)return gt;const xt=parseInt(be.id.slice(be.id.lastIndexOf("-")+1),10)||0;return(parseInt(ot.id.slice(ot.id.lastIndexOf("-")+1),10)||0)-xt}),ie=Ve?at.filter(be=>be.id.toLowerCase().includes(Ve.toLowerCase())||be.title&&be.title.toLowerCase().includes(Ve.toLowerCase())||be.description&&be.description.toLowerCase().includes(Ve.toLowerCase())):at,Ke=(be,ot)=>be.length>ot?be.slice(0,ot)+"…":be,je=ve.trim(),Fe=je.length>0&&!dc.test(je);i.useEffect(()=>{const be=x.trim()!==""||b.length>0||j.length>0||R!==""||U!==""||$!==""||Y!==""||he.length>0||we!==null||Ae!==void 0||Z!==Ms||le!==void 0||N!==""||E!==""||O||je!=="";G(be)},[x,b,j,R,U,$,Y,he,we,Ae,Z,le,N,E,O,je]);const Be=i.useCallback(async()=>{S&&!await d({title:"Discard Changes",message:"You have unsaved changes. Discard them?",danger:!0})||(j.forEach(be=>URL.revokeObjectURL(be.previewUrl)),P([]),w(""),v([]),L(""),C(""),V(""),ne(""),A(""),D("default"),Se([]),ce(!1),ze(null),tt(!1),X(void 0),ee(Ms),K(void 0),k(""),y(""),G(!1),pe(!1),B(""),n())},[S,n,j,d]),St=i.useCallback(async()=>{const be=x.trim();if(!(!be||F||Fe)){_(!0);try{const ot=R.indexOf("/"),gt=U.indexOf("/"),xt=$.indexOf("/"),jt=await r({title:void 0,description:be,column:"triage",dependencies:b.length?b:void 0,enabledWorkflowSteps:Ue?he.length>0?he:[]:void 0,...we?{assignedAgentId:we}:{},modelPresetId:I==="preset"&&q||void 0,modelProvider:R&&ot!==-1?R.slice(0,ot):void 0,modelId:R&&ot!==-1?R.slice(ot+1):void 0,validatorModelProvider:U&&gt!==-1?U.slice(0,gt):void 0,validatorModelId:U&&gt!==-1?U.slice(gt+1):void 0,planningModelProvider:$&&xt!==-1?$.slice(0,xt):void 0,planningModelId:$&&xt!==-1?$.slice(xt+1):void 0,thinkingLevel:Y!==""?Y:void 0,reviewLevel:Ae,priority:Z,nodeId:le,branch:N.trim()===""?void 0:N.trim(),baseBranch:E.trim()===""?void 0:E.trim(),...O||je!==""?{githubTracking:{enabled:O,...je!==""?{repoOverride:je}:{}}}:{}});if(j.length>0){const Bt=[];for(const Jt of j)try{await lc(jt.id,Jt.file,s)}catch{Bt.push(Jt.file.name)}Bt.length>0&&o(`Failed to upload: ${Bt.join(", ")}`,"error")}j.forEach(Bt=>URL.revokeObjectURL(Bt.previewUrl)),P([]),w(""),v([]),L(""),C(""),V(""),ne(""),A(""),D("default"),Se([]),ce(!1),ze(null),tt(!1),X(void 0),ee(Ms),K(void 0),k(""),y(""),o(`Created ${jt.id}`,"success"),n()}catch(ot){o(Ce(ot)||"Failed to create task","error")}finally{_(!1)}}},[x,b,j,R,U,$,Y,F,r,o,n,s,I,q,he,Ue,we,Ae,Z,le,N,E]),ye=i.useCallback(be=>{be.key==="Escape"&&(be.preventDefault(),Be())},[Be]),It=(we?re.find(be=>be.id===we):void 0)?.name??we,Ie=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:oe,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>ct(be=>!be),disabled:F,"data-testid":"dep-trigger",children:b.length>0?`${b.length} selected`:"Add dependencies"}),Te&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Ve,onChange:be=>me(be.target.value),onClick:be=>be.stopPropagation()}),ie.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):ie.map(be=>t.jsxs("div",{className:`dep-dropdown-item${b.includes(be.id)?" selected":""}`,onClick:()=>{v(b.includes(be.id)?b.filter(ot=>ot!==be.id):[...b,be.id]),ct(!1),me("")},onMouseDown:ot=>ot.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:be.id}),t.jsx("span",{className:"dep-dropdown-title",children:Ke(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:()=>v(b.filter(ot=>ot!==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:De,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{Pe?tt(!1):Ge()},disabled:F,"data-testid":"new-task-agent-button",children:[t.jsx(Vn,{size:12,style:{verticalAlign:"middle"}}),It?` ${It}`:" 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"}),qe&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!qe&&re.map(be=>t.jsxs("div",{className:`dep-dropdown-item${we===be.id?" selected":""}`,onMouseDown:ot=>ot.preventDefault(),onClick:()=>{ze(be.id===we?null:be.id),tt(!1)},"data-testid":`agent-option-${be.id}`,children:[t.jsx(Vn,{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)),!qe&&re.length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),we&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:be=>be.preventDefault(),onClick:()=>{ze(null),tt(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:Be,onKeyDown:ye,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:Be,disabled:F,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!rt&&t.jsx(fv,{hasAiProvider:Me,hasGithub:Xe}),t.jsx(Jx,{mode:"create",description:x,onDescriptionChange:w,dependencies:b,onDependenciesChange:v,executorModel:R,onExecutorModelChange:L,validatorModel:U,onValidatorModelChange:C,presetMode:I,onPresetModeChange:D,selectedPresetId:q,onSelectedPresetIdChange:A,selectedWorkflowSteps:he,onWorkflowStepsChange:yt,onDefaultOnApplied:Re,pendingImages:j,onImagesChange:P,tasks:a,projectId:s,disabled:F,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:Be,planningModel:$,onPlanningModelChange:V,thinkingLevel:Y,onThinkingLevelChange:ne,reviewLevel:Ae,onReviewLevelChange:X,priority:Z,onPriorityChange:ee,branch:N,onBranchChange:k,baseBranch:E,onBaseBranchChange:y,nodeId:le,onNodeIdChange:K,nodeOptions:ht,githubTrackingEnabled:O,onGithubTrackingEnabledChange:pe,githubRepoOverride:ve,onGithubRepoOverrideChange:B,renderBelowPrimary:Ie,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Be,disabled:F,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:St,disabled:!x.trim()||F||Fe,children:F?"Creating...":"Create Task"})]})]})}):null}function gi(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 Of(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function lD(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function cD(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function dD(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function uD(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 vl(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function mD(e){if(!e)return"Not yet";const n=new Date(e);return Number.isNaN(n.getTime())?"Not yet":n.toLocaleString()}function hD({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,v]=i.useState(null),[N,k]=i.useState(null),[E,y]=i.useState(null),j=i.useCallback(async X=>{l(!0);try{const Z=await XS(s);r(Z),d(null),y(Date.now()),X?.preserveKillResult||v(null)}catch(Z){d(Z instanceof Error?Z.message:"Failed to load system stats")}finally{l(!1)}},[s]);i.useEffect(()=>{if(!e)return;j();const X=window.setInterval(()=>{j()},5e3);return()=>{window.clearInterval(X)}},[e,j]),i.useEffect(()=>{if(!e)return;(async()=>{try{const Z=await Ki();m(Z.vitestAutoKillEnabled??!0),f(Z.vitestKillThresholdPct??90),k(null)}catch(Z){k(Z instanceof Error?Z.message:"Failed to load vitest settings")}})()},[e]),i.useEffect(()=>{if(!e)return;const X=Z=>{Z.key==="Escape"&&n()};return document.addEventListener("keydown",X),()=>document.removeEventListener("keydown",X)},[e,n]);const P=i.useMemo(()=>{if(!a)return[];const X=a.systemStats,Z=vl(lD(X.heapUsed,X.heapLimit)),ee=vl(cD(X.rss,X.systemTotalMem));return[{label:"RSS",value:gi(X.rss),detail:Of(X.rss,X.systemTotalMem),className:ee},{label:"Heap Used",value:gi(X.heapUsed),detail:`of ${gi(X.heapTotal)}`,className:Z},{label:"Heap Limit",value:gi(X.heapLimit),detail:"V8 limit"},{label:"External",value:gi(X.external)},{label:"Array Buffers",value:gi(X.arrayBuffers)}]},[a]),F=i.useCallback(async X=>{m(X);try{await Pn({vitestAutoKillEnabled:X}),k(null)}catch(Z){k(Z instanceof Error?Z.message:"Failed to save vitest settings")}},[]),_=i.useCallback(async X=>{const Z=Math.min(99,Math.max(50,Number.isFinite(X)?Math.round(X):90));f(Z);try{await Pn({vitestKillThresholdPct:Z}),k(null)}catch(ee){k(ee instanceof Error?ee.message:"Failed to save vitest settings")}},[]),R=i.useCallback(async()=>{if(!p){if(!x){w(!0);return}g(!0);try{const X=await ZS(s);v(X),w(!1),await j({preserveKillResult:!0})}catch(X){d(X instanceof Error?X.message:"Failed to kill vitest processes")}finally{g(!1)}}},[x,p,j,s]);if(!e)return null;const L=a?.systemStats,U=o&&!!a,C=E?`Updated ${new Date(E).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`:"Waiting for first update",$=a?.taskStats,V=L?L.systemTotalMem-L.systemFreeMem:0,Y=L?dD(V,L.systemTotalMem):"normal",ne=L?vl(Y):"",q=L&&Number.isFinite(L.systemTotalMem)&&L.systemTotalMem>0?Math.max(0,Math.min(100,V/L.systemTotalMem*100)):0,A=L?`System memory used: ${q.toFixed(1)}% (${gi(V)} of ${gi(L.systemTotalMem)})`:"System memory usage unavailable",I=a?.vitestProcessCount,D=uD(L?.cpuPercent??null,L?.cpuCount??0),S=vl(D),G=L?.cpuPercent??null,he=G===null?0:Math.max(0,Math.min(100,G)),Se=G===null?"Sampling…":`${G.toFixed(1)}%`,Ue=G===null?"App CPU usage unavailable: waiting for another sample":`App CPU usage: ${G.toFixed(1)}%`,ce=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":"",Ae=mD(a?.vitestLastAutoKillAt);return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"system-stats-modal-title",onClick:X=>{X.target===X.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(fr,{}),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:C})]}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void j(),title:"Refresh","aria-label":"Refresh system stats",children:t.jsx(fs,{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(an,{})})]})]}),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:P.map(X=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:X.label}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${X.className}`.trim(),children:X.value}),X.detail?t.jsx("span",{className:"system-stats-modal__detail",children:X.detail}):null]})]},X.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 ${S}`.trim(),children:Se}),t.jsx("span",{className:"system-stats-modal__detail",children:G===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--${D}`,role:"progressbar","aria-valuenow":Math.round(he),"aria-valuemin":0,"aria-valuemax":100,"aria-label":Ue,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${D}`,style:{width:`${he}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Load Avg"}),t.jsx("dd",{children:L?.loadAvg.map(X=>X.toFixed(2)).join(" ")??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Cores"}),t.jsx("dd",{children:L?.cpuCount??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Platform"}),t.jsx("dd",{children:L?.platform??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Node"}),t.jsx("dd",{children:L?.nodeVersion??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"PID"}),t.jsx("dd",{children:L?.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:L?gi(V):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:L?`${Of(V,L.systemTotalMem)} of ${gi(L.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--${Y}`,role:"progressbar","aria-valuenow":Math.round(q),"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--${Y}`,style:{width:`${q}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Free"}),t.jsx("dd",{children:L?gi(L.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:$?.total??0})]}),Object.entries($?.byColumn??{}).map(([X,Z])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:X}),t.jsx("dd",{children:Z})]},X))]})]}),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:$?.agents.idle??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"active"}),t.jsx("dd",{children:$?.agents.active??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"running"}),t.jsx("dd",{children:$?.agents.running??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"error"}),t.jsx("dd",{children:$?.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(Nk,{}),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:I??"—"})]})}),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 R(),disabled:p||I===0,children:[t.jsx(_k,{}),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:X=>{F(X.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:X=>{const Z=Number.parseInt(X.target.value,10);_(Number.isNaN(Z)?90:Z)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:h,"aria-label":"Kill threshold (%)",onChange:X=>{const Z=Number.parseInt(X.target.value,10);_(Number.isNaN(Z)?90:Z)},onBlur:()=>{_(h)}})]})]}),b&&t.jsxs("p",{className:ce,children:["Killed ",b.killed," processes"]}),t.jsxs("p",{className:"system-stats-modal__last-kill",children:["Last auto-kill: ",Ae]}),N&&t.jsx("p",{className:"system-stats-modal__kill-result system-stats-modal__kill-result--error",children:N})]})]})]}),c&&a&&t.jsxs("div",{className:"system-stats-modal__footer-error",children:["Latest refresh failed: ",c]})]})})}const pD=5e3;function fD(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 N;o?N=await Hm({limit:a,projectId:n,type:s}):N=(await Dm({limit:a,type:s,projectId:n})).map(E=>({...E,projectId:n??"",projectName:""})),c(N),p(N.length===a),N.length>0&&(x.current=N[N.length-1].timestamp)}catch(N){h(N instanceof Error?N.message:"Failed to load activity log")}finally{u(!1)}},[a,n,s,o]),b=i.useCallback(async()=>{if(x.current)try{u(!0);let N;o?N=await Hm({limit:a,projectId:n,type:s,since:x.current}):N=(await Dm({limit:a,type:s,since:x.current,projectId:n})).map(E=>({...E,projectId:n??"",projectName:""})),c(k=>[...k,...N]),p(N.length===a),N.length>0&&(x.current=N[N.length-1].timestamp)}catch(N){h(N instanceof Error?N.message:"Failed to load more entries")}finally{u(!1)}},[a,n,s,o]),v=i.useCallback(()=>{c([]),p(!1),x.current=void 0},[]);return i.useEffect(()=>{w()},[w]),i.useEffect(()=>{if(r)return g.current=setInterval(()=>{w()},pD),()=>{g.current&&(clearInterval(g.current),g.current=null)}},[r,w]),{entries:l,loading:d,error:m,refresh:w,clear:v,hasMore:f,loadMore:b}}const Rd={"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"},gD={"task:created":t.jsx(Cn,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(Eo,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(fs,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(an,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(Wn,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(_o,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(co,{size:14,className:"activity-icon settings"})};function bD(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 xD({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:v,error:N,refresh:k,hasMore:E}=fD({projectId:x,type:g,limit:100,autoRefresh:e,useCentralFeed:w}),y=b.map(R=>({id:R.id,timestamp:R.timestamp,type:R.type,taskId:R.taskId,taskTitle:R.taskTitle,details:R.details,metadata:R.metadata,projectId:R.projectId,projectName:R.projectName})),j=async()=>{try{await xS(),k(),p(!1)}catch{p(!1)}},P=R=>{a&&a(R)},F=R=>{h(R),l?.(R==="all"?void 0:R)};i.useEffect(()=>{if(!e)return;const R=L=>{L.key==="Escape"&&(f?p(!1):n())};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[e,n,f]);const _=d!=="all"||m!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:R=>{R.target===R.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(ys,{size:14}),t.jsxs("select",{value:m,onChange:R=>F(R.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map(R=>t.jsx("option",{value:R.id,children:R.name},R.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(Al,{size:14}),t.jsxs("select",{value:d,onChange:R=>u(R.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(Rd).map(([R,L])=>t.jsx("option",{value:R,children:L},R))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>k(),title:"Refresh","data-testid":"activity-refresh",children:v?t.jsx(Nt,{size:14,className:"spin"}):t.jsx(fs,{size:14})}),y.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:t.jsx(Sn,{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(R=>R.id===m)?.name||m]}),d!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",Rd[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:[N&&t.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[t.jsx(Ts,{size:16}),t.jsx("span",{children:N})]}),y.length===0&&!v&&!N&&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:y.map(R=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:gD[R.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:Rd[R.type]}),t.jsx("span",{className:"activity-log-entry-time",children:bD(R.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[R.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>P(R.taskId),"data-testid":"activity-task-link",children:R.taskId}),R.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:R.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:R.details})]}),R.metadata&&Object.keys(R.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof R.metadata.from=="string"&&typeof R.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[R.metadata.from," → ",R.metadata.to]}),typeof R.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${R.metadata.merged?"success":"error"}`,children:R.metadata.merged?"Merged":"Not merged"})]})]})]},R.id))}),E&&!v&&t.jsx("button",{className:"activity-log-load-more",onClick:k,"data-testid":"activity-load-more",children:"Load More"}),v&&y.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(Nt,{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:j,children:"Clear Log"})]})]})})]})}):null}const Yr=[{id:"status",label:"Status",icon:Bg},{id:"changes",label:"Changes",icon:Ud},{id:"commits",label:"Commits",icon:Mo},{id:"branches",label:"Branches",icon:Ps},{id:"worktrees",label:"Worktrees",icon:yw},{id:"stashes",label:"Stashes",icon:So},{id:"remotes",label:"Remotes",icon:Og}];function zf({status:e}){switch(e){case"added":case"untracked":return t.jsx(Zy,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(Dg,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(Yy,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(oa,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(tw,{size:14,className:"gm-file-icon"})}}function Ff({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 vD(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 kr(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 yD({isOpen:e,onClose:n,tasks:s,addToast:a,projectId:r}){const o=ci(),l=Zs();ji(e);const{keyboardOverlap:c,viewportHeight:d,viewportOffsetTop:u,keyboardOpen:m}=Yi({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,v]=i.useState(null),N=i.useRef(null);Ti(N,e,"fusion:git-modal-size");const k=Gi(f),E=vD(a),[y,j]=i.useState(null),[P,F]=i.useState([]),[_,R]=i.useState(new Set),[L,U]=i.useState(""),[C,$]=i.useState(!1),[V,Y]=i.useState(null),[ne,q]=i.useState(!1),[A,I]=i.useState(null),[D,S]=i.useState(null),G=i.useRef(0),[he,Se]=i.useState([]),[Ue,ce]=i.useState(null),[Ae,X]=i.useState(null),[Z,ee]=i.useState(!1),[le,K]=i.useState(20),[O,pe]=i.useState(""),[ve,B]=i.useState([]),[we,ze]=i.useState(""),[re,He]=i.useState(""),[Pe,tt]=i.useState(""),[qe,de]=i.useState(null),[De,Te]=i.useState([]),[ct,Ve]=i.useState(!1),[me,oe]=i.useState(null),[Me,Xe]=i.useState(null),[rt,ht]=i.useState(!1),[yt,Re]=i.useState([]),[Ge,at]=i.useState([]),[ie,Ke]=i.useState(""),[je,Fe]=i.useState(null),[Be,St]=i.useState(null),[ye,kt]=i.useState(null),[It,Ie]=i.useState(!1),[be,ot]=i.useState(null),gt=i.useRef(0),[xt,jt]=i.useState(null),[Bt,Jt]=i.useState(null),Vt=i.useCallback(async()=>{if(e){w(!0),v(null);try{switch(p){case"status":{const te=await fi(r);j(te);break}case"changes":{const[te,Oe]=await Promise.all([fi(r),Za(r)]);j(te),F(Oe),R(new Set),S(null),Y(null),I(null);break}case"commits":{const te=await wN(le,r);Se(te);break}case"branches":{const[te,Oe]=await Promise.all([Lr(r),fi(r)]);B(te),j(Oe);break}case"worktrees":{const te=await SN(r);Re(te);break}case"stashes":{const te=await Wo(r);at(te),St(null),kt(null),ot(null),gt.current+=1;break}case"remotes":{const te=await fi(r);j(te);break}}}catch(te){v(Ce(te)||"Failed to fetch git data"),a(Ce(te)||"Failed to fetch git data","error")}finally{w(!1)}}},[p,e,le,a,r]);i.useEffect(()=>{e&&Vt()},[Vt,e]),i.useEffect(()=>{if(!e)return;const te=Oe=>{if(Oe.key==="Escape"){f();return}if((Oe.key==="ArrowUp"||Oe.key==="ArrowDown")&&Oe.altKey){Oe.preventDefault();const mt=Yr.findIndex(Pt=>Pt.id===p);Oe.key==="ArrowUp"&&mt>0?g(Yr[mt-1].id):Oe.key==="ArrowDown"&&mt<Yr.length-1&&g(Yr[mt+1].id)}};return document.addEventListener("keydown",te),()=>document.removeEventListener("keydown",te)},[e,f,p]);const pn=i.useCallback(async te=>{try{await Am(te,r),a(`Staged ${te.length} file(s)`,"success");const Oe=await Za(r);F(Oe),R(new Set),S(null),Y(null),I(null)}catch(Oe){a(Ce(Oe)||"Failed to stage files","error")}},[a,r]),Xt=i.useCallback(async te=>{try{await DN(te,r),a(`Unstaged ${te.length} file(s)`,"success");const Oe=await Za(r);F(Oe),R(new Set),S(null),Y(null),I(null)}catch(Oe){a(Ce(Oe)||"Failed to unstage files","error")}},[a,r]),mn=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 LN(te,r),a(`Discarded changes to ${te.length} file(s)`,"success");const[mt,Pt]=await Promise.all([Za(r),fi(r)]);F(mt),j(Pt),R(new Set),S(null),Y(null),I(null)}catch(mt){a(Ce(mt)||"Failed to discard changes","error")}},[a,r,o]),Ht=i.useCallback(async te=>{if(te.preventDefault(),!!L.trim()){$(!0);try{const Oe=await Rm(L.trim(),r);a(`Committed: ${Oe.hash}`,"success"),U("");const[mt,Pt]=await Promise.all([Za(r),fi(r)]);F(mt),j(Pt),S(null),Y(null),I(null)}catch(Oe){a(Ce(Oe)||"Failed to commit","error")}finally{$(!1)}}},[L,a,r]),Zt=i.useCallback(async()=>{if(L.trim()){$(!0);try{const te=P.filter(sn=>!sn.staged).map(sn=>sn.file);te.length>0&&await Am(te,r);const Oe=await Rm(L.trim(),r);a(`Committed: ${Oe.hash}`,"success"),U("");const[mt,Pt]=await Promise.all([Za(r),fi(r)]);F(mt),j(Pt),S(null),Y(null),I(null)}catch(te){a(Ce(te)||"Failed to commit","error")}finally{$(!1)}}},[L,P,a,r]),tn=i.useCallback(async(te,Oe)=>{S({file:te,staged:Oe}),q(!0),I(null);const mt=G.current+1;G.current=mt;try{const Pt=await $N(te,Oe,r);if(G.current!==mt)return;Y(Pt)}catch(Pt){if(G.current!==mt)return;const sn=Ce(Pt)||"Failed to load file diff";Y(null),I(sn),a(sn,"error")}finally{G.current===mt&&q(!1)}},[a,r]),dn=i.useCallback(te=>{R(Oe=>{const mt=new Set(Oe);return mt.has(te)?mt.delete(te):mt.add(te),mt})},[]),qt=i.useCallback(async te=>{if(Ue===te){ce(null),X(null);return}ce(te),ee(!0);try{const Oe=await Tl(te,r);X(Oe)}catch(Oe){a(Ce(Oe)||"Failed to load diff","error"),X(null)}finally{ee(!1)}},[Ue,a,r]),ke=i.useCallback(()=>{K(te=>Math.min(te+20,100))},[]),$e=i.useMemo(()=>{if(!O.trim())return he;const te=O.toLowerCase();return he.filter(Oe=>Oe.message.toLowerCase().includes(te)||Oe.author.toLowerCase().includes(te)||Oe.shortHash.toLowerCase().includes(te))},[he,O]),Ye=i.useCallback(async te=>{if(te.preventDefault(),!!we.trim()){w(!0);try{await CN(we.trim(),re.trim()||void 0,r),a(`Created branch ${we}`,"success"),ze(""),He("");const Oe=await Lr(r);B(Oe)}catch(Oe){a(Ce(Oe)||"Failed to create branch","error")}finally{w(!1)}}},[we,re,a,r]),ut=i.useCallback(async te=>{w(!0);try{await EN(te,r),a(`Switched to ${te}`,"success");const[Oe,mt]=await Promise.all([fi(r),Lr(r)]);j(Oe),B(mt)}catch(Oe){a(Ce(Oe)||"Failed to checkout branch","error")}finally{w(!1)}},[a,r]),We=i.useCallback(async te=>{if(await o.confirm({title:"Delete Branch",message:`Delete branch "${te}"?`,danger:!0})){w(!0);try{await Mm(te,void 0,r),a(`Deleted branch ${te}`,"success");const mt=await Lr(r);B(mt)}catch(mt){if(Ce(mt).includes("not fully merged")){if(await o.confirm({title:"Force Delete Branch",message:"Branch has unmerged commits. Force delete?",danger:!0}))try{await Mm(te,!0,r),a(`Force deleted branch ${te}`,"success");const sn=await Lr(r);B(sn)}catch(sn){a(Ce(sn)||"Failed to delete branch","error")}}else a(Ce(mt)||"Failed to delete branch","error")}finally{w(!1)}}},[a,r,o]),$t=i.useMemo(()=>{if(!Pe.trim())return ve;const te=Pe.toLowerCase();return ve.filter(Oe=>Oe.name.toLowerCase().includes(te))},[ve,Pe]),At=i.useCallback(async te=>{if(qe===te){de(null),Te([]),oe(null),Xe(null);return}de(te),Te([]),oe(null),Xe(null),Ve(!0);try{const Oe=await NN(te,10,r);Te(Oe)}catch{Te([])}finally{Ve(!1)}},[qe,r]),wt=i.useCallback(async te=>{if(me===te){oe(null),Xe(null);return}oe(te),Xe(null),ht(!0);try{const Oe=await Tl(te,r);Xe(Oe)}catch{Xe(null)}finally{ht(!1)}},[me,r]),zt=i.useCallback(()=>{de(null),Te([]),oe(null),Xe(null)},[]),Lt=i.useCallback(()=>{gt.current+=1,St(null),kt(null),ot(null),Ie(!1)},[]),Ot=i.useCallback(async te=>{te.preventDefault(),Fe("create"),Lt();try{await RN(ie.trim()||void 0,r),a("Changes stashed","success"),Ke("");const Oe=await Wo(r);at(Oe)}catch(Oe){a(Ce(Oe)||"Failed to stash changes","error")}finally{Fe(null)}},[ie,a,r,Lt]),nn=i.useCallback(async(te,Oe=!1)=>{Fe(`apply-${te}`),Lt();try{await PN(te,Oe,r),a(Oe?"Stash popped":"Stash applied","success");const mt=await Wo(r);at(mt)}catch(mt){a(Ce(mt)||"Failed to apply stash","error")}finally{Fe(null)}},[a,r,Lt]),Yt=i.useCallback(async te=>{if(await o.confirm({title:"Drop Stash",message:`Drop stash@{${te}}? This cannot be undone.`,danger:!0})){Fe(`drop-${te}`),Lt();try{await IN(te,r),a("Stash dropped","success");const mt=await Wo(r);at(mt)}catch(mt){a(Ce(mt)||"Failed to drop stash","error")}finally{Fe(null)}}},[a,r,o,Lt]),rn=i.useCallback(async te=>{if(Be===te){Lt();return}const Oe=gt.current+1;gt.current=Oe,St(te),kt(null),ot(null),Ie(!0);try{const mt=await TN(te,r);if(gt.current!==Oe)return;kt(mt)}catch(mt){if(gt.current!==Oe)return;kt(null),ot(Ce(mt)||"Failed to load stash diff")}finally{gt.current===Oe&&Ie(!1)}},[Be,r,Lt]),_e=i.useCallback(async()=>{jt("fetch");try{const te=await _N(void 0,r);Jt(te),a(te.message||"Fetch completed",te.fetched?"success":"info");const Oe=await fi(r);j(Oe)}catch(te){a(Ce(te)||"Fetch failed","error")}finally{jt(null)}},[a,r]),it=i.useCallback(async te=>{jt("pull");try{const Oe=await MN(te,r);if(Jt(Oe),Oe.conflict)a("Merge conflict detected. Resolve manually.","error");else{const Pt=te?.rebase?"Pull --rebase completed":"Pull completed";a(Oe.message||Pt,"success")}const mt=await fi(r);j(mt)}catch(Oe){a(Ce(Oe)||"Pull failed","error")}finally{jt(null)}},[a,r]),bt=i.useCallback(async()=>{jt("push");try{const te=await AN(r);Jt(te),a(te.message||"Push completed","success");const Oe=await fi(r);j(Oe)}catch(te){a(Ce(te)||"Push failed","error")}finally{jt(null)}},[a,r]),Rt=i.useMemo(()=>P.filter(te=>te.staged),[P]),se=i.useMemo(()=>P.filter(te=>!te.staged),[P]);return e?t.jsx("div",{className:"modal-overlay open git-manager-modal-overlay",...k,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal gm-modal",ref:N,style:h,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h3",{children:[t.jsx(Hd,{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:Vt,disabled:x,title:"Refresh",children:t.jsx(fs,{size:14,className:x?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:f,"aria-label":"Close",children:t.jsx(an,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:Yr.map(te=>{const Oe=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(Oe,{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(Nt,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),b&&!x&&t.jsxs("div",{className:"gm-error",children:[t.jsx(Ts,{size:18}),t.jsx("span",{children:b}),t.jsx("button",{className:"btn btn-sm",onClick:Vt,children:"Retry"})]}),p==="status"&&!x&&y&&t.jsx(wD,{status:y,copyToClipboard:E}),p==="changes"&&!x&&t.jsx(kD,{status:y,stagedFiles:Rt,unstagedFiles:se,selectedFiles:_,toggleFileSelection:dn,onStageFiles:pn,onUnstageFiles:Xt,onDiscardChanges:mn,onSelectDiffFile:tn,selectedDiffTarget:D,changeDiff:V,loadingChangeDiff:ne,changeDiffError:A,commitMessage:L,setCommitMessage:U,onCommit:Ht,onStageAllAndCommit:Zt,committing:C}),p==="commits"&&!x&&t.jsx(jD,{commits:$e,commitSearch:O,setCommitSearch:pe,selectedCommit:Ue,commitDiff:Ae,loadingDiff:Z,onCommitClick:qt,onLoadMore:ke,canLoadMore:he.length>=le&&le<100,copyToClipboard:E}),p==="branches"&&!x&&t.jsx(ND,{branches:$t,branchSearch:Pe,setBranchSearch:tt,newBranchName:we,setNewBranchName:ze,branchBase:re,setBranchBase:He,onCreateBranch:Ye,onCheckoutBranch:ut,onDeleteBranch:We,loading:x,allBranches:ve,selectedBranch:qe,branchCommits:De,loadingBranchCommits:ct,expandedBranchCommit:me,branchCommitDiff:Me,loadingBranchCommitDiff:rt,onSelectBranch:At,onBranchCommitClick:wt,onCloseBranchDetails:zt}),p==="worktrees"&&!x&&t.jsx(SD,{worktrees:yt}),p==="stashes"&&!x&&t.jsx(CD,{stashes:Ge,stashMessage:ie,setStashMessage:Ke,onCreateStash:Ot,onApplyStash:nn,onDropStash:Yt,onToggleStashDiff:rn,stashLoading:je,expandedStashIndex:Be,stashDiff:ye,loadingStashDiff:It,stashDiffError:be}),p==="remotes"&&!x&&t.jsx(ED,{status:y,remoteLoading:xt,lastRemoteResult:Bt,onFetch:_e,onPull:it,onPush:bt,addToast:a,projectId:r,copyToClipboard:E})]})]})]})}):null}function wD({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(Ps,{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(ra,{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(Ts,{size:12}),"Modified"]}):t.jsxs(t.Fragment,{children:[t.jsx(Wn,{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(Ra,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx(Co,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(Wn,{size:12}),"Up to date"]})]})]})]})]})}function kD({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 v=s.filter(k=>a.has(`unstaged:${k.file}`)),N=n.filter(k=>a.has(`staged:${k.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(Ps,{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:[v.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(v.map(k=>k.file)),title:"Stage selected",children:[t.jsx(Cn,{size:12})," Stage (",v.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(v.map(k=>k.file)),title:"Discard selected",children:t.jsx(_o,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(k=>k.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(k=>{const E=u?.file===k.file&&u.staged===!1;return t.jsxs("div",{className:`gm-file-item${E?" active":""}`,onClick:()=>d(k.file,!1),role:"button",tabIndex:0,onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),d(k.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:y=>y.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`unstaged:${k.file}`),onChange:()=>r(`unstaged:${k.file}`)})}),t.jsx(zf,{status:k.status}),t.jsx("span",{className:"gm-file-name",title:k.file,children:t.jsx("bdo",{dir:"ltr",children:k.file})}),t.jsx(Ff,{status:k.status}),t.jsx("button",{className:"gm-icon-btn",onClick:y=>{y.stopPropagation(),o([k.file])},title:"Stage file",children:t.jsx(Cn,{size:12})})]},`unstaged:${k.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:[N.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(N.map(k=>k.file)),title:"Unstage selected",children:["Unstage (",N.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(k=>k.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(k=>{const E=u?.file===k.file&&u.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${E?" active":""}`,onClick:()=>d(k.file,!0),role:"button",tabIndex:0,onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),d(k.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:y=>y.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`staged:${k.file}`),onChange:()=>r(`staged:${k.file}`)})}),t.jsx(zf,{status:k.status}),t.jsx("span",{className:"gm-file-name",title:k.file,children:t.jsx("bdo",{dir:"ltr",children:k.file})}),t.jsx(Ff,{status:k.status}),t.jsx("button",{className:"gm-icon-btn",onClick:y=>{y.stopPropagation(),l([k.file])},title:"Unstage file",children:t.jsx(an,{size:12})})]},`staged:${k.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(Ud,{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(Nt,{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(Ud,{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:k=>g(k.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(Nt,{size:14,className:"spin"}):t.jsx(Aa,{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 jD({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(Hi,{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:kr(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(ra,{size:12})})}),a===m.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(Nt,{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 ND({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:v,onBranchCommitClick:N,onCloseBranchDetails:k}){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(Hi,{size:14}),t.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:E=>s(E.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:c,children:[t.jsx("input",{type:"text",placeholder:"New branch name",value:a,onChange:E=>r(E.target.value),disabled:m}),t.jsxs("select",{value:o,onChange:E=>l(E.target.value),disabled:m,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:"Base: HEAD"}),h.map(E=>t.jsx("option",{value:E.name,children:E.name},E.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:m||!a.trim(),children:[t.jsx(Cn,{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(E=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${E.isCurrent?" current":""}${f===E.name?" selected":""}`,onClick:()=>v(E.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[E.isCurrent&&t.jsx(bs,{size:14,className:"gm-current-icon"}),E.name]}),E.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",E.remote]}),E.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:kr(E.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!E.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:y=>{y.stopPropagation(),d(E.name)},disabled:m,title:"Checkout",children:t.jsx(Ps,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:y=>{y.stopPropagation(),u(E.name)},disabled:m,title:"Delete",children:t.jsx(Sn,{size:14})})]})})]}),f===E.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(Mo,{size:14}),"Commits on ",E.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:k,title:"Close","data-testid":"close-branch-details",children:t.jsx(an,{size:14})})]}),g?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(Nt,{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(y=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>N(y.hash),"data-testid":`branch-commit-${y.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:y.shortHash}),t.jsx("span",{className:"gm-commit-message",title:y.message,children:y.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:y.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:kr(y.date)}),y.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),x===y.hash&&t.jsx("div",{className:"gm-commit-diff",children:b?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(Nt,{size:16,className:"spin"}),"Loading diff..."]}):w?t.jsxs(t.Fragment,{children:[(y.body||y.message)&&t.jsx("div",{className:"gm-commit-message-full",children:y.body||y.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"})})]},y.hash))})]})]},E.name))})]})}function SD({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:Tu(n.path)||n.path})]}),t.jsxs("div",{className:"gm-worktree-detail",children:[n.branch&&t.jsxs("span",{className:"gm-worktree-branch",children:[t.jsx(Ps,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function CD({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(Nt,{size:14,className:"spin"}):t.jsx(So,{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(Ps,{size:12}),f.branch]}),t.jsx("span",{children:kr(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(Nt,{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(Nt,{size:14,className:"spin"}):t.jsx(Sn,{size:14})})]})]}),d===f.index&&t.jsx("div",{className:"gm-stash-diff",children:m?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(Nt,{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 ED({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:a,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:d}){const u=oe=>{try{return new URL(oe).hostname}catch{return oe.replace(/^git@/,"").split(":")[0]||oe}},[m,h]=i.useState([]),[f,p]=i.useState(!1),[g,x]=i.useState(null),[w,b]=i.useState(""),[v,N]=i.useState(""),[k,E]=i.useState(null),[y,j]=i.useState(""),[P,F]=i.useState(""),[_,R]=i.useState(!1),[L,U]=i.useState(!1),C=i.useRef(null),[$,V]=i.useState([]),[Y,ne]=i.useState(!1),[q,A]=i.useState(null),[I,D]=i.useState([]),[S,G]=i.useState(!1),[he,Se]=i.useState(null),Ue=i.useRef(0),ce=m.find(oe=>oe.name===q);i.useEffect(()=>{(n!==null||f)&&U(!1)},[n,f]),i.useEffect(()=>{if(!L)return;const oe=Xe=>{C.current?.contains(Xe.target)||U(!1)},Me=Xe=>{Xe.key==="Escape"&&U(!1)};return document.addEventListener("mousedown",oe),document.addEventListener("keydown",Me),()=>{document.removeEventListener("mousedown",oe),document.removeEventListener("keydown",Me)}},[L]);const[Ae,X]=i.useState(null),[Z,ee]=i.useState(null),[le,K]=i.useState(!1),[O,pe]=i.useState(null),[ve,B]=i.useState(null),[we,ze]=i.useState(!1);i.useEffect(()=>{re()},[]),i.useEffect(()=>{e&&e.ahead>0?He():e&&e.ahead===0&&V([])},[e?.ahead]),i.useEffect(()=>{m.length>0&&!q&&A(m[0].name)},[m]),i.useEffect(()=>{q?Pe(q):(D([]),Se(null))},[q]),i.useEffect(()=>{!q||!s||Pe(q)},[q,s]),i.useEffect(()=>{q&&!m.find(oe=>oe.name===q)&&A(m.length>0?m[0].name:null)},[m,q]);const re=async()=>{p(!0);try{const oe=await mN(c);h(oe)}catch(oe){l(Ce(oe)||"Failed to load remotes","error")}finally{p(!1)}},He=async()=>{ne(!0);try{const oe=await kN(c);V(oe)}catch{V([])}finally{ne(!1)}},Pe=async oe=>{const Me=Ue.current+1;Ue.current=Me,G(!0),Se(null);try{const Xe=await jN(oe,void 0,10,c);if(Ue.current!==Me)return;D(Xe)}catch(Xe){if(Ue.current!==Me)return;Se(Ce(Xe)||"Failed to load remote commits"),D([])}finally{Ue.current===Me&&G(!1)}},tt=ci(),qe=async oe=>{if(oe.preventDefault(),!(!w.trim()||!v.trim())){x("add");try{await hN(w.trim(),v.trim(),c),l(`Remote '${w}' added successfully`,"success"),b(""),N(""),R(!1),await re()}catch(Me){l(Ce(Me)||"Failed to add remote","error")}finally{x(null)}}},de=async oe=>{if(await tt.confirm({title:"Remove Remote",message:`Are you sure you want to remove remote '${oe}'?`,danger:!0})){x(`remove-${oe}`);try{await pN(oe,c),l(`Remote '${oe}' removed`,"success"),await re()}catch(Xe){l(Ce(Xe)||"Failed to remove remote","error")}finally{x(null)}}},De=async oe=>{if(P.trim()){x(`rename-${oe}`);try{await fN(oe,P.trim(),c),l(`Remote renamed to '${P.trim()}'`,"success"),E(null),F(""),await re()}catch(Me){l(Ce(Me)||"Failed to rename remote","error")}finally{x(null)}}},Te=async oe=>{if(y.trim()){x(`url-${oe}`);try{await gN(oe,y.trim(),c),l("Remote URL updated","success"),E(null),j(""),await re()}catch(Me){l(Ce(Me)||"Failed to update remote URL","error")}finally{x(null)}}},ct=i.useCallback(async(oe,Me)=>{if(Me==="ahead"){if(Ae===oe){X(null),ee(null);return}X(oe),ee(null),K(!0);try{const Xe=await Tl(oe);ee(Xe)}catch{ee(null)}finally{K(!1)}}else{if(O===oe){pe(null),B(null);return}pe(oe),B(null),ze(!0);try{const Xe=await Tl(oe);B(Xe)}catch{B(null)}finally{ze(!1)}}},[Ae,O]),Ve=oe=>{E(`url-${oe.name}`),j(oe.pushUrl||oe.fetchUrl)},me=oe=>{E(`name-${oe.name}`),F(oe.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:()=>R(!_),disabled:g!==null,title:_?"Cancel":"Add Remote",children:_?t.jsx(an,{size:14}):t.jsx(Cn,{size:14})})]}),_&&t.jsxs("form",{className:"gm-remote-form",onSubmit:qe,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:w,onChange:oe=>b(oe.target.value),disabled:g==="add",className:"input gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:v,onChange:oe=>N(oe.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()||!v.trim()||g==="add",children:[g==="add"?t.jsx(Nt,{size:12,className:"spin"}):t.jsx(Cn,{size:12}),"Add"]})]}),f?t.jsxs("div",{className:"gm-loading",children:[t.jsx(Nt,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(oe=>t.jsxs("div",{className:`gm-remote-selector-item${q===oe.name?" selected":""}`,onClick:()=>A(oe.name),role:"button",tabIndex:0,onKeyDown:Me=>{(Me.key==="Enter"||Me.key===" ")&&(Me.preventDefault(),A(oe.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:oe.name}),oe.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",title:oe.fetchUrl,children:u(oe.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm gm-remote-remove-btn",onClick:Me=>{Me.stopPropagation(),de(oe.name)},disabled:g!==null,title:"Remove remote",children:t.jsx(Sn,{size:14})})]},oe.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[q&&ce?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:q}),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(Ra,{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(Co,{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(Nt,{size:14,className:"spin"}):t.jsx(fs,{size:14}),"Fetch"]}),t.jsxs("div",{className:"gm-pull-split",ref:C,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(Nt,{size:14,className:"spin"}):t.jsx(Js,{size:14}),"Pull"]}),t.jsx("button",{className:"btn btn-primary btn-icon gm-pull-split-toggle",onClick:()=>U(oe=>!oe),disabled:n!==null||f,"aria-label":"Pull options","aria-haspopup":"menu","aria-expanded":L,children:t.jsx(un,{size:14})}),L?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(Nt,{size:14,className:"spin"}):t.jsx(Ra,{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:"}),k===`url-${q}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:y,onChange:oe=>j(oe.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Te(q),disabled:g===`url-${q}`,children:g===`url-${q}`?t.jsx(Nt,{size:12,className:"spin"}):t.jsx(bs,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{E(null),j("")},title:"Cancel",children:t.jsx(an,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:ce.fetchUrl,children:t.jsx("bdo",{dir:"ltr",children:ce.fetchUrl})}),t.jsxs("div",{className:"gm-remote-inline-actions",children:[t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(ce.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(ra,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>Ve(ce),disabled:g!==null,title:"Edit remote URL",children:t.jsx(Os,{size:14})})]})]})]}),ce.pushUrl&&ce.pushUrl!==ce.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:ce.pushUrl,children:t.jsx("bdo",{dir:"ltr",children:ce.pushUrl})}),t.jsx("div",{className:"gm-remote-inline-actions",children:t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(ce.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(ra,{size:14})})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:k===`name-${q}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:P,onChange:oe=>F(oe.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>De(q),disabled:g===`rename-${q}`,children:g===`rename-${q}`?t.jsx(Nt,{size:12,className:"spin"}):t.jsx(bs,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{E(null),F("")},title:"Cancel",children:t.jsx(an,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>me(ce),disabled:g!==null,title:"Edit remote name",children:t.jsx(Os,{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(Ra,{size:14}),"Commits to Push (",e.ahead,")"]})}),Y?t.jsxs("div",{className:"gm-loading",children:[t.jsx(Nt,{size:14,className:"spin"}),"Loading..."]}):$.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:$.map(oe=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>ct(oe.hash,"ahead"),role:"button",tabIndex:0,onKeyDown:Me=>{(Me.key==="Enter"||Me.key===" ")&&(Me.preventDefault(),ct(oe.hash,"ahead"))},title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:oe.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:oe.message,children:oe.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:oe.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:kr(oe.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:Ae===oe.hash?t.jsx(un,{size:14}):t.jsx(zn,{size:14})})]}),Ae===oe.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:le?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(Nt,{size:16,className:"spin"}),"Loading diff..."]}):Z?t.jsxs(t.Fragment,{children:[(oe.body||oe.message)&&t.jsx("div",{className:"gm-commit-message-full",children:oe.body||oe.message}),Z.stat&&t.jsx("pre",{className:"gm-diff-stat",children:Z.stat}),t.jsx("pre",{className:"gm-diff-patch",children:Z.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},oe.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(Bg,{size:14}),"Recent commits on ",q]})}),S?t.jsxs("div",{className:"gm-loading",children:[t.jsx(Nt,{size:14,className:"spin"}),"Loading commits..."]}):he?t.jsxs("div",{className:"gm-error",children:[t.jsx(Ts,{size:14}),he]}):I.length===0?t.jsxs("div",{className:"gm-empty",children:["No commits found on ",q,". Try fetching first."]}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:I.map(oe=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>ct(oe.hash,"remote"),role:"button",tabIndex:0,onKeyDown:Me=>{(Me.key==="Enter"||Me.key===" ")&&(Me.preventDefault(),ct(oe.hash,"remote"))},title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:oe.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:oe.message,children:oe.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:oe.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:kr(oe.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:O===oe.hash?t.jsx(un,{size:14}):t.jsx(zn,{size:14})})]}),O===oe.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:we?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(Nt,{size:16,className:"spin"}),"Loading diff..."]}):ve?t.jsxs(t.Fragment,{children:[(oe.body||oe.message)&&t.jsx("div",{className:"gm-commit-message-full",children:oe.body||oe.message}),ve.stat&&t.jsx("pre",{className:"gm-diff-stat",children:ve.stat}),t.jsx("pre",{className:"gm-diff-patch",children:ve.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},oe.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 ir={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function _D(e,n){return e&&n?`${e}/${n}`:""}function MD(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 Bf(e){switch(e){case"file-text":return oa;case"check-circle":return Wn;case"shield":return Ck;case"zap":return is;case"eye":return Er;case"globe":return tc;case"layout-grid":return la;case"puzzle":return dk;default:return Wn}}function Uf(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 AD({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),[v,N]=i.useState(!1),[k,E]=i.useState(!1),[y,j]=i.useState(ir),[P,F]=i.useState(!1),[_,R]=i.useState(!1),[L,U]=i.useState(null),[C,$]=i.useState(null),[V,Y]=i.useState({}),[ne,q]=i.useState([]),A=i.useRef(null);Ti(A,e,"fusion:workflow-steps-modal-size");const I=i.useCallback(async()=>{try{h(!0);const O=await $o(a);o(O)}catch(O){s(Ce(O)||"Failed to load workflow steps","error")}finally{h(!1)}},[s,a]),D=i.useCallback(async()=>{try{const O=await vo(a);Y(O||{})}catch{}},[a]),S=i.useCallback(async()=>{try{const O=await Fs();q(O.models||[])}catch{}},[]),G=i.useCallback(async()=>{try{p(!0);const[O,pe]=await Promise.all([kS(),jS()]);c(O.templates);const ve=Object.fromEntries(pe.templates.map(({pluginId:B,template:we})=>[we.id,B]));u(ve)}catch(O){s(Ce(O)||"Failed to load templates","error")}finally{p(!1)}},[s]);i.useEffect(()=>{e&&(I(),G(),D(),S())},[e,I,G,D,S]);const he=i.useCallback(()=>{E(!0),N(!1),b(null),j(ir)},[]),Se=i.useCallback(()=>{E(!1),N(!0),b(null),j(ir)},[]),Ue=i.useCallback(O=>{b(O.id),N(!1),j({name:O.name,description:O.description,mode:O.mode||"prompt",phase:O.phase||"pre-merge",prompt:O.prompt,scriptName:O.scriptName||"",enabled:O.enabled,defaultOn:O.defaultOn||!1,modelProvider:O.modelProvider||"",modelId:O.modelId||""})},[]),ce=i.useCallback(()=>{b(null),N(!1),E(!1),j(ir)},[]),Ae=i.useCallback(async()=>{if(!y.name.trim()||!y.description.trim()){s("Name and description are required","error");return}F(!0);try{const O=y.mode==="prompt"&&y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:y.mode==="prompt"?{modelProvider:void 0,modelId:void 0}:{};if(v){const pe={name:y.name.trim(),description:y.description.trim(),mode:y.mode,phase:y.phase,prompt:y.mode==="prompt"&&y.prompt.trim()||void 0,scriptName:y.mode==="script"?y.scriptName.trim():void 0,enabled:y.enabled,defaultOn:y.defaultOn||void 0,...O};await Lm(pe,a),s("Workflow step created","success")}else w&&(await vS(w,{name:y.name.trim(),description:y.description.trim(),mode:y.mode,phase:y.phase,prompt:y.mode==="prompt"?y.prompt:"",scriptName:y.mode==="script"?y.scriptName.trim():void 0,enabled:y.enabled,defaultOn:y.defaultOn,...O},a),s("Workflow step updated","success"));N(!1),b(null),j(ir),await I()}catch(O){s(Ce(O)||"Failed to save workflow step","error")}finally{F(!1)}},[y,v,w,s,I]),X=i.useCallback(async O=>{try{await yS(O,a),s("Workflow step deleted","success"),U(null),w===O&&(b(null),j(ir)),await I()}catch(pe){s(Ce(pe)||"Failed to delete workflow step","error")}},[w,s,I]),Z=i.useCallback(async()=>{if(!(!w&&!v)&&y.mode==="prompt"){if(v){if(!y.name.trim()||!y.description.trim()){s("Name and description are required before refining","error");return}F(!0);try{const O=y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:{},pe={name:y.name.trim(),description:y.description.trim(),mode:"prompt",prompt:y.prompt.trim()||void 0,enabled:y.enabled,defaultOn:y.defaultOn||void 0,...O},ve=await Lm(pe,a);N(!1),b(ve.id),R(!0);const B=await Om(ve.id,a);j(we=>({...we,prompt:B.prompt})),s("Prompt refined with AI","success"),await I()}catch(O){s(Ce(O)||"Failed to refine prompt","error")}finally{F(!1),R(!1)}return}if(w){R(!0);try{const O=await Om(w,a);j(pe=>({...pe,prompt:O.prompt})),s("Prompt refined with AI","success"),await I()}catch(O){s(Ce(O)||"Failed to refine prompt","error")}finally{R(!1)}}}},[w,v,y,s,I]),ee=i.useCallback(async O=>{$(O.id);try{await NS(O.id,a),s(`Added ${O.name} workflow step`,"success"),await I(),x("my-steps"),E(!1)}catch(pe){const ve=Ce(pe);ve?.includes("already exists")?s(`A workflow step named '${O.name}' already exists`,"error"):s(ve||"Failed to add workflow step from template","error")}finally{$(null)}},[s,I]),le=Gi(n);if(!e)return null;const K=v||w!==null;return t.jsx("div",{className:"modal-overlay open",...le,"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:[!K&&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(py,{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(la,{size:14}),"Templates (",l.length,")"]})]}),g==="my-steps"&&!K&&!k&&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(O=>t.jsx("div",{className:"wfm-step-card","data-testid":`workflow-step-${O.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:O.name}),t.jsx("span",{className:`wfm-badge ${O.enabled?"wfm-badge-enabled":"wfm-badge-disabled"}`,children:O.enabled?"Enabled":"Disabled"}),t.jsx("span",{className:`wfm-badge ${(O.mode||"prompt")==="script"?"wfm-badge-script":"wfm-badge-prompt"}`,children:(O.mode||"prompt")==="script"?"Script":"AI Prompt"}),t.jsx("span",{className:`wfm-badge ${(O.phase||"pre-merge")==="post-merge"?"wfm-badge-post-merge":"wfm-badge-pre-merge"}`,children:(O.phase||"pre-merge")==="post-merge"?"Post-merge":"Pre-merge"}),O.defaultOn&&t.jsx("span",{className:"wfm-badge wfm-badge-default-on",children:"Default on"})]}),t.jsx("div",{className:"wfm-step-card-desc",children:O.description})]}),t.jsxs("div",{className:"wfm-step-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>Ue(O),title:"Edit","aria-label":`Edit ${O.name}`,children:t.jsx(Os,{size:14})}),L===O.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>X(O.id),title:"Confirm delete","aria-label":`Confirm delete ${O.name}`,children:t.jsx(bs,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>U(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(an,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>U(O.id),title:"Delete","aria-label":`Delete ${O.name}`,children:t.jsx(Sn,{size:14})})]})]})},O.id))})]}),g==="templates"&&!K&&!k&&t.jsx(t.Fragment,{children:f?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(Nt,{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(O=>{const pe=Bf(O.icon),ve=Uf(O.category),B=C===O.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`template-${O.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:O.name}),t.jsx("span",{className:ve,children:O.category}),d[O.id]&&t.jsx("span",{className:"wfm-badge-category wfm-badge-category-plugin",children:d[O.id]})]}),t.jsx("div",{className:"wfm-template-desc",children:O.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>ee(O),disabled:B,"data-testid":`add-template-${O.id}`,children:B?t.jsxs(t.Fragment,{children:[t.jsx(Nt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Cn,{size:12}),"Add"]})})]})]})},O.id)})})}),k&&!K&&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:Se,"data-testid":"create-custom-step",children:[t.jsx(Cn,{size:14}),"Custom workflow step"]}),f?t.jsxs("div",{className:"wfm-loading","data-testid":"create-chooser-template-loading",children:[t.jsx(Nt,{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(O=>{const pe=Bf(O.icon),ve=Uf(O.category),B=C===O.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`chooser-template-${O.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:O.name}),t.jsx("span",{className:ve,children:O.category}),d[O.id]&&t.jsx("span",{className:"wfm-badge-category wfm-badge-category-plugin",children:d[O.id]})]}),t.jsx("div",{className:"wfm-template-desc",children:O.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>ee(O),disabled:B,"data-testid":`chooser-add-template-${O.id}`,children:B?t.jsxs(t.Fragment,{children:[t.jsx(Nt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Cn,{size:12}),"Add template"]})})]})]})},O.id)})})]}),K&&t.jsxs("div",{className:"wfm-form","data-testid":"workflow-step-form",children:[t.jsx("h3",{className:"wfm-form-title",children:v?"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:y.name,onChange:O=>j(pe=>({...pe,name:O.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:y.description,onChange:O=>j(pe=>({...pe,description:O.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 ${y.mode==="prompt"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>j(O=>({...O,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(qi,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${y.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>j(O=>({...O,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(Vi,{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 ${y.phase==="pre-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>j(O=>({...O,phase:"pre-merge"})),"data-testid":"phase-pre-merge",children:"Pre-merge"}),t.jsx("button",{className:`btn ${y.phase==="post-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>j(O=>({...O,phase:"post-merge"})),"data-testid":"phase-post-merge",children:"Post-merge"})]}),t.jsx("div",{className:"wfm-field-hint",children:y.phase==="pre-merge"?"Runs before merge — can block merge on failure":"Runs after merge success — failures are logged but do not block"})]}),y.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:Z,disabled:!y.description.trim()||_,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[_?t.jsx(Nt,{size:12,className:"spin"}):t.jsx(xs,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:y.prompt,onChange:O=>j(pe=>({...pe,prompt:O.target.value})),placeholder:"Leave empty to use AI refinement",rows:6,className:"wfm-prompt-textarea","data-testid":"workflow-step-prompt"})]}),y.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"}),y.modelProvider&&y.modelId&&t.jsxs("button",{type:"button",className:"btn-icon wfm-model-clear-btn",onClick:()=>j(O=>({...O,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(an,{size:12}),t.jsx("span",{children:"Use default"})]})]}),t.jsx("span",{className:"wfm-model-hint",children:y.modelProvider&&y.modelId?`Using ${y.modelProvider}/${y.modelId}`:"Using global default model"}),t.jsx("div",{"data-testid":"workflow-step-model-select",children:t.jsx(Ns,{models:ne,value:_D(y.modelProvider,y.modelId),onChange:O=>{const pe=MD(O);j(ve=>({...ve,modelProvider:pe.provider,modelId:pe.modelId}))},placeholder:"Select a model override…",label:"Model override for this workflow step"})})]}),y.mode==="script"&&t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Script"}),Object.keys(V).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:y.scriptName,onChange:O=>j(pe=>({...pe,scriptName:O.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(V).map(([O,pe])=>t.jsxs("option",{value:O,children:[O," (",pe,")"]},O))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:y.enabled,onChange:O=>j(pe=>({...pe,enabled:O.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:y.defaultOn,onChange:O=>j(pe=>({...pe,defaultOn:O.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:ce,disabled:P,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:Ae,disabled:P||!y.name.trim()||!y.description.trim()||y.mode==="script"&&!y.scriptName.trim(),"data-testid":"save-workflow-step",children:P?"Saving...":v?"Create":"Save"})]})]})]})]})}),!K&&!k&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:he,"data-testid":"add-workflow-step",children:[t.jsx(Cn,{size:14}),"Add Workflow Step"]})})]})})}const RD=36e5,PD=3e5,Pd=[{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 ID(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 TD(e){return typeof e!="number"||!Number.isFinite(e)?RD:Math.max(PD,Math.round(e))}function R5(e){if(Pd.some(s=>s.value===e))return[...Pd];const n={value:e,label:`${ID(e)} (custom)`};return[...Pd,n].sort((s,a)=>s.value-a.value)}const $D=4,DD=5*6e4;function LD(e){const n=TD(e?.heartbeatIntervalMs);return Math.max(n*$D,DD)}function Hf(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 OD(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 zD(e){const{state:n,lastHeartbeatAt:s,lastError:a,pauseReason:r,runtimeConfig:o}=e,l=OD(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(xi,{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(xi,{size:14}),color:"var(--state-paused-text)",stateDerived:!1};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(Vn,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const d=new Date(s).getTime(),u=Date.now()-d,m=LD(o);if(u>m){const h=`No heartbeat for ${Hf(u)} (threshold: ${Hf(m)})`;return{label:"Unresponsive",icon:t.jsx(Ys,{size:14}),color:"var(--state-error-text)",stateDerived:!1,reason:h}}return{label:"Healthy",icon:t.jsx(kw,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}function Gl({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(Vn,{size:Math.max(14,Math.round(n*.55)),"aria-hidden":"true"})})}const FD="https://github.com/Runfusion/Fusion/issues/new";function BD(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`${FD}?${r.toString()}`}function UD({open:e,onClose:n,errorText:s,issueContext:a}){const[r,o]=i.useState(!1),l=i.useMemo(()=>BD(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(Ts,{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(bs,{size:14}):t.jsx(ra,{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($g,{size:14}),"Report on GitHub"]})]})]})}):null}function HD({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(Ts,{size:14}),t.jsx("span",{className:"agent-error-indicator__label",children:s})]}),t.jsx(UD,{open:a,onClose:()=>r(!1),errorText:e,issueContext:n})]})}const yl=[{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 qD({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 D=Fn("fn-agent-view",a);return D==="board"||D==="list"?D:"list"});i.useEffect(()=>{const D=Fn("fn-agent-view",a);if(D==="board"||D==="list"){b(D);return}b("list")},[a]),i.useEffect(()=>{ds("fn-agent-view",w,a)},[a,w]);const[v,N]=i.useState(null),k=i.useRef(null),[E,y]=i.useState(new Set),[j,P]=i.useState(new Map),{confirm:F}=ci(),_=i.useMemo(()=>j.size===0?r:r.map(D=>{const S=j.get(D.id);return S?{...D,state:S}:D}),[r,j]),R=i.useMemo(()=>g!=="all"?_:[..._].sort((D,S)=>{const G=D.state==="paused"?1:0,he=S.state==="paused"?1:0;return G!==he?G-he:(S.updatedAt??"").localeCompare(D.updatedAt??"")}),[_,g]),L=i.useCallback(async()=>{c(!0);try{const S=await Mr(g!=="all"?{state:g}:void 0,a);o(S)}catch(D){s(`Failed to load agents: ${Ce(D)}`,"error")}finally{c(!1)}},[g,s,a]);i.useEffect(()=>{e&&L()},[e,L]),i.useEffect(()=>{if(!e)return;const D=setInterval(()=>{L()},3e4);return()=>{clearInterval(D)}},[e,L]);const U=async()=>{if(m.trim())try{await IS({name:m.trim(),role:f},a),s(`Agent "${m}" created`,"success"),h(""),u(!1),L()}catch(D){s(`Failed to create agent: ${Ce(D)}`,"error")}},C=async(D,S)=>{if(!E.has(D)){y(G=>new Set(G).add(D)),P(G=>{const he=new Map(G);return he.set(D,S),he});try{await $S(D,S,a),s(`Agent state updated to ${S}`,"success"),await L(),P(G=>{const he=new Map(G);return he.delete(D),he})}catch(G){P(he=>{const Se=new Map(he);return Se.delete(D),Se}),s(`Failed to update state: ${Ce(G)}`,"error")}finally{y(G=>{const he=new Set(G);return he.delete(D),he})}}},$=async(D,S)=>{if(await F({title:"Delete Agent",message:`Delete agent "${S}"? This cannot be undone.`,danger:!0}))try{await DS(D,a),s(`Agent "${S}" deleted`,"success"),L()}catch(he){s(`Failed to delete agent: ${Ce(he)}`,"error")}},V=async(D,S)=>{const G=r.find(he=>he.id===D);if(G){if(G.role===S){N(null);return}try{await TS(D,{role:S},a),s(`Agent role updated to ${yl.find(he=>he.value===S)?.label??S}`,"success"),N(null),L()}catch(he){s(`Failed to update role: ${Ce(he)}`,"error")}}},Y=(D,S)=>{D.key==="Escape"&&N(null)},ne=D=>yl.find(S=>S.value===D)?.label??D,q=D=>zD(D),A=D=>D.color==="var(--state-active-text)"?"active":D.color==="var(--state-paused-text)"?"paused":D.color==="var(--state-error-text)"?"error":"muted",I=(D,S)=>D.state==="error"?{title:void 0,label:"Error"}:{title:S.reason??S.label,label:S.stateDerived?null:S.label};return e?t.jsx("div",{className:"modal-overlay open",onClick:D=>D.target===D.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(Vn,{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(la,{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(qd,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void L(),title:"Refresh",disabled:l,children:t.jsx(fs,{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(Al,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:g,onChange:D=>x(D.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(Cn,{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:D=>h(D.target.value),onKeyDown:D=>D.key==="Enter"&&U(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:f,onChange:D=>p(D.target.value),children:yl.map(D=>t.jsxs("option",{value:D.value,children:[D.icon," ",D.label]},D.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:R.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(Vn,{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"?R.map(D=>{const S=q(D),G=I(D,S),he=A(S);return t.jsxs("div",{className:"agent-board-card","data-state":D.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:t.jsx(Gl,{agent:D,size:20})}),t.jsx("span",{className:"agent-board-badge","data-state":D.state,children:D.state}),t.jsx("span",{className:"agent-board-health","data-health":he,title:G.title,children:S.icon})]}),t.jsx("div",{className:"agent-board-name",title:D.name,children:D.name}),t.jsx("div",{className:"agent-board-id",children:D.id}),t.jsxs("div",{className:"agent-board-actions",children:[D.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void C(D.id,"active"),disabled:E.has(D.id),title:"Activate",children:t.jsx(ss,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(D.id,D.name),title:"Delete",children:t.jsx(Sn,{size:14})})]}),D.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void C(D.id,"paused"),disabled:E.has(D.id),title:"Pause",children:t.jsx(xi,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void C(D.id,"paused"),disabled:E.has(D.id),title:"Stop",children:t.jsx(Mi,{size:14})})]}),D.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void C(D.id,"active"),disabled:E.has(D.id),title:"Resume",children:t.jsx(ss,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(D.id,D.name),title:"Delete",children:t.jsx(Sn,{size:14})})]}),D.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void C(D.id,"paused"),disabled:E.has(D.id),title:"Pause",children:t.jsx(xi,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void C(D.id,"paused"),disabled:E.has(D.id),title:"Stop",children:t.jsx(Mi,{size:14})})]}),D.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void C(D.id,"active"),disabled:E.has(D.id),title:"Retry",children:t.jsx(ss,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void C(D.id,"paused"),disabled:E.has(D.id),title:"Stop",children:t.jsx(Mi,{size:14})})]})]})]},D.id)}):R.map(D=>{const S=q(D),G=I(D,S),he=A(S);return t.jsxs("div",{className:"agent-card","data-state":D.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[v===D.id?t.jsx("select",{ref:k,className:"select agent-role-select",value:D.role,onChange:Se=>void V(D.id,Se.target.value),onKeyDown:Se=>Y(Se,D.id),onBlur:()=>N(null),autoFocus:!0,children:yl.map(Se=>t.jsxs("option",{value:Se.value,children:[Se.icon," ",Se.label]},Se.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>N(D.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:Se=>{(Se.key==="Enter"||Se.key===" ")&&N(D.id)},children:t.jsx(Gl,{agent:D,size:20})}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:D.name}),t.jsx("span",{className:"agent-id text-secondary",children:D.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":D.state,children:D.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":he,title:G.title,children:[S.icon,G.label?` ${G.label}`:""]}),t.jsx("span",{className:"badge text-secondary",children:ne(D.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[D.state==="error"&&D.lastError?t.jsx(HD,{errorText:D.lastError,issueContext:{surface:"AgentListModal list",agentId:D.id,agentName:D.name,agentState:D.state,taskId:D.taskId}}):null,D.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:D.taskId})]}),D.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date(D.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[D.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void C(D.id,"active"),disabled:E.has(D.id),title:"Activate",children:[t.jsx(ss,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(D.id,D.name),title:"Delete",children:[t.jsx(Sn,{size:14})," Delete"]})]}),D.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void C(D.id,"paused"),disabled:E.has(D.id),title:"Pause",children:[t.jsx(xi,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void C(D.id,"paused"),disabled:E.has(D.id),title:"Stop",children:[t.jsx(Mi,{size:14})," Stop"]})]}),D.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void C(D.id,"active"),disabled:E.has(D.id),title:"Resume",children:[t.jsx(ss,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(D.id,D.name),title:"Delete",children:[t.jsx(Sn,{size:14})," Delete"]})]}),D.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void C(D.id,"paused"),disabled:E.has(D.id),title:"Pause",children:[t.jsx(xi,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void C(D.id,"paused"),disabled:E.has(D.id),title:"Stop",children:[t.jsx(Mi,{size:14})," Stop"]})]}),D.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void C(D.id,"active"),disabled:E.has(D.id),title:"Retry",children:[t.jsx(ss,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void C(D.id,"paused"),disabled:E.has(D.id),title:"Stop",children:[t.jsx(Mi,{size:14})," Stop"]})]})]})]},D.id)})})]})]})}):null}function VD({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 Uj();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 v=await Gj(b);u.current&&d({kind:v.enabled?"enabled":"disabled",restartRequired:v.restartRequired}),n?.(v.enabled),await m()}catch(v){u.current&&d({kind:"error",message:v instanceof Error?v.message:String(v)})}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(Nt,{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(Tn,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(WD,{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(qf,{status:a,authenticated:e}),c&&t.jsx(Vf,{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(Tn,{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(qf,{status:a,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:w}),c&&t.jsx(Vf,{action:c})]})}function WD({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 qf({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(Nt,{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 Vf({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 KD({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 Wj();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 Yj(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(Nt,{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(Tn,{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(Tn,{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 GD({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 Kj();return c.current&&r(x),x},[]);i.useEffect(()=>{d()},[d]);const u=i.useCallback(async x=>{l(x?"enabling":"disabling");try{const w=await Qj(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(Nt,{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(Tn,{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(Tn,{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 JD(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 Id({instructions:e,"data-testid":n}){const[s,a]=i.useState(!1),r=JD(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(bs,{size:12}):t.jsx(ra,{size:12})})]})]},u))}):e})}function YD({value:e,onChange:n,onSubmit:s,prompt:a,placeholder:r,helpText:o,disabled:l=!1,submitLabel:c="Submit code","data-testid":d}){return t.jsxs("div",{className:"oauth-manual-code","data-testid":d,children:[t.jsx("p",{className:"oauth-manual-code__prompt",children:a}),t.jsx("textarea",{className:"form-input oauth-manual-code__input",value:e,onChange:u=>n(u.target.value),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 QD=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"]),XD=/^[a-z][a-z0-9-]*$/,Wf=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function Kf(){return{id:"",name:"",reasoning:!1}}function ZD({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:[Kf()]),[v,N]=i.useState(null),k=w.length>1,E=i.useMemo(()=>v??r??null,[v,r]);function y(_,R){b(L=>L.map((U,C)=>C===_?{...U,...R}:U))}function j(_){b(R=>R.length<=1?R:R.filter((L,U)=>U!==_))}function P(){if(!l.trim())return"Provider ID is required.";if(!XD.test(l.trim()))return"Provider ID must be kebab-case.";if(!o&&QD.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 Wf.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 R=P();N(R),!R&&await n({id:l.trim(),name:d.trim()||void 0,baseUrl:m.trim(),api:f,apiKey:g.trim()||void 0,models:w.map(L=>({id:L.id.trim(),name:L.name?.trim()||void 0,reasoning:!!L.reasoning,contextWindow:L.contextWindow,maxTokens:L.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:Wf.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((_,R)=>t.jsxs("div",{className:"custom-provider-form__model-row",children:[t.jsx("input",{className:"input","aria-label":`Model ID ${R+1}`,placeholder:"Model ID",value:_.id,onChange:L=>y(R,{id:L.target.value}),disabled:a}),t.jsx("input",{className:"input","aria-label":`Model name ${R+1}`,placeholder:"Display name",value:_.name??"",onChange:L=>y(R,{name:L.target.value}),disabled:a}),t.jsxs("label",{className:"checkbox-label custom-provider-form__toggle",children:[t.jsx("input",{type:"checkbox",checked:!!_.reasoning,onChange:L=>y(R,{reasoning:L.target.checked}),disabled:a}),"Reasoning"]}),t.jsx("input",{className:"input","aria-label":`Context window ${R+1}`,placeholder:"Context window",type:"number",value:_.contextWindow??"",onChange:L=>y(R,{contextWindow:L.target.value?Number(L.target.value):void 0}),disabled:a}),t.jsx("input",{className:"input","aria-label":`Max tokens ${R+1}`,placeholder:"Max tokens",type:"number",value:_.maxTokens??"",onChange:L=>y(R,{maxTokens:L.target.value?Number(L.target.value):void 0}),disabled:a}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>j(R),disabled:a||!k,"aria-label":`Remove model ${R+1}`,children:"×"})]},`${R}-model`))}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>b(_=>[..._,Kf()]),disabled:a,children:"+ Add model"})]}),E?t.jsx("div",{className:"form-error",children:E}):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 eL=new Set(["google-antigravity","antigravity","google-gemini-cli"]);function tL(e){return!eL.has(e)}function Gf(e){return e.filter(n=>tL(n.id))}const gv={host:"web",activeProfileId:null,profiles:[]},bv=i.createContext({shellApi:null,state:gv,ready:!0,openConnectionManagerSignal:0});function nL({children:e}){const n=i.useMemo(()=>typeof window<"u"?window.fusionShell??null:null,[]),[s,a]=i.useState(gv),[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(bv.Provider,{value:{shellApi:n,state:s,ready:r,openConnectionManagerSignal:l},children:e})}function sL(){return i.useContext(bv)}const iL={host:"web",activeProfileId:null,profiles:[]};function aL(e){if(!e)return iL;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 cm(e){return new Error(`${e} is only available in native shell mode`)}async function rL(e,n){if(!e)throw cm("Saving connection profiles");return e.saveProfile(n)}async function oL(e,n){if(!e)throw cm("Deleting connection profiles");await e.deleteProfile(n)}async function lL(e,n){if(!e)throw cm("Switching connection profiles");return e.setActiveProfile(n)}function xv(){const e=sL(),n=i.useMemo(()=>aL(e.state),[e.state]),s=i.useCallback(o=>rL(e.shellApi,o),[e.shellApi]),a=i.useCallback(o=>oL(e.shellApi,o),[e.shellApi]),r=i.useCallback(o=>lL(e.shellApi,o),[e.shellApi]);return{...e,state:n,saveProfile:s,removeProfile:a,setActiveProfile:r}}const za="fusion_model_onboarding_state",jr=[],Nr=[],Jl=!1,Yl=!1,Sr={},cL=void 0,na=["ai-setup","github","project-setup","first-task"],dL={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function Xs(){if(typeof window>"u")return null;try{const e=localStorage.getItem(za);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?uL(n):null}catch{return null}}function uL(e){const n=e.postOnboardingDismissedAt??cL;return{...e,completedSteps:e.completedSteps??jr,skippedSteps:e.skippedSteps??Nr,dismissed:e.dismissed??Jl,completed:e.completed??Yl,stepData:e.stepData??Sr,...n?{postOnboardingDismissedAt:n}:{}}}function wl(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:jr,skippedSteps:Nr,dismissed:Jl,completed:Yl,stepData:Sr};try{localStorage.setItem(za,JSON.stringify(s))}catch{}return}try{const s=Xs(),a=new Date().toISOString(),r=n.completed??Yl;let o=n.dismissed??Jl;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??jr,c=n.skippedSteps??s?.skippedSteps??Nr,d={...s?.stepData??Sr};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(za,JSON.stringify(u))}catch{}}}function mL(e){if(!(typeof window>"u"))try{const n=Xs(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:jr,skippedSteps:[e],dismissed:Jl,completed:Yl,stepData:Sr};localStorage.setItem(za,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(za,JSON.stringify(r))}catch{}}function Jf(){if(!(typeof window>"u"))try{const e=Xs(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:jr,skippedSteps:Nr,dismissed:!1,completed:!0,stepData:Sr};localStorage.setItem(za,JSON.stringify(s))}catch{}}function Cr(){const e=Xs();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function hL(){if(!(typeof window>"u"))try{const e=Xs(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:jr,skippedSteps:Nr,dismissed:!1,completed:!1,stepData:Sr,postOnboardingDismissedAt:n};localStorage.setItem(za,JSON.stringify(s))}catch{}}function vv(){const e=Xs();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function pL(){const e=Xs();return!e||Cr()?!1:e.currentStep!=="complete"}function fL(){const e=Xs();if(!e||Cr()||e.currentStep==="complete")return null;const n=e.currentStep,s=dL[n]??xL(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function gL(){const e=Xs();return e?e.skippedSteps:Nr}function bL(e){const n=Xs();return!n||!n.stepData?null:n.stepData[e]??null}function xL(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const yv="fusion_onboarding_events",Yf="fusion_onboarding_session_id",vL=200,yL=50;function ii(e,n={}){if(!(typeof window>"u"))try{const s=kL(),a=SL(n.step),r={type:e,timestamp:new Date().toISOString(),...a?{step:a}:{},metadata:n,sessionId:wL()},o=NL([...s,r]);jL(o)}catch{}}function wL(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(Yf);if(e)return e;const n=Qf();return sessionStorage.setItem(Yf,n),n}catch{return Qf()}}function Qf(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function kL(){try{const e=localStorage.getItem(yv);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(CL):[]}catch{return[]}}function jL(e){try{localStorage.setItem(yv,JSON.stringify(e))}catch{}}function NL(e){const n=[...e];for(;n.length>vL;)n.splice(0,yL);return n}function SL(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function CL(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 EL=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}))??[]}),_L={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"}}},wv={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:"..."}},ML={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},Xf={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 xu(e){if(Xf[e])return Xf[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 Td=["anthropic","openai","google","gemini","ollama"],AL=["anthropic","claude-cli","droid-cli","cursor-cli","llama-cpp","openai-codex","gemini","minimax","kimi","zai"],RL={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"},PL={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function vu(e){return RL[e]??e}function Zf(e){const n=vu(e),s=AL.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function eg(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=Zf(e.id),a=Zf(n.id);if(s!==a)return s-a;const r=vu(e.id),o=vu(n.id);if(r!==o)return r.localeCompare(o);const l=PL[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 IL(e,n){const s=n.trim();if(!s)return"API key is required";const a=wv[e]??ML;return a.pattern.test(s)?null:`${xu(e)} keys should follow this format: ${a.hint} (e.g. ${a.example})`}const kv={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"},TL={description:"AI provider — connect to start using AI models",apiKeyInfo:kv};function yu(e){return _L[e]??TL}function $L(e){return yu(e.id).apiKeyInfo??kv}function DL({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 LL({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=wv[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(ai,{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(ai,{summary:"Advanced setup details",children:g})]})}const OL=150;function zL({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:a,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const d=Xs(),u=d?.currentStep,m=u==="complete"?"ai-setup":na.includes(u)?u:"ai-setup",h=d?.completedSteps??[],f=d?.skippedSteps??gL(),[p,g]=i.useState(!0),[x,w]=i.useState(m),[b,v]=i.useState(h),[N,k]=i.useState(f),[E,y]=i.useState(!1),[j,P]=i.useState(""),[F,_]=i.useState(!1),[R,L]=i.useState(null),[U,C]=i.useState(null),[$,V]=i.useState([]),[Y,ne]=i.useState(void 0),[q,A]=i.useState(!0),[I,D]=i.useState(null),[S,G]=i.useState({}),[he,Se]=i.useState({}),[Ue,ce]=i.useState({}),[Ae,X]=i.useState(null),[Z,ee]=i.useState([]),[le,K]=i.useState(""),[O,pe]=i.useState(!1),[ve,B]=i.useState({}),[we,ze]=i.useState({}),[re,He]=i.useState({}),[Pe,tt]=i.useState([]),[qe,de]=i.useState(!1),[De,Te]=i.useState(!1),[ct,Ve]=i.useState(),[me,oe]=i.useState("Remote Server"),[Me,Xe]=i.useState(""),[rt,ht]=i.useState(""),[yt,Re]=i.useState(!1),[Ge,at]=i.useState(null),ie=i.useRef({}),Ke=i.useRef(null),je=i.useRef(null),Fe=i.useRef(null),[Be,St]=i.useState({}),[ye,kt]=i.useState(()=>Xs()?.stepData?.github?.skipped===!0),It=i.useRef(0),Ie=i.useRef(l),{shellApi:be,state:ot}=xv(),gt=i.useRef(!1),xt=d?.currentStep,jt=!!d&&d.currentStep!=="complete";Ti(je,p,"fusion:model-onboarding-modal-size"),i.useEffect(()=>{const M=Ke.current;M&&(M.scrollTop=0)},[x]);const[Bt,Jt]=i.useState(()=>Xs()?.stepData?.["ai-setup"]?.skippedProviders??{}),Vt=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],pn=Vt.findIndex(M=>M.key===x),Xt=x==="complete"?Vt.length:pn;i.useEffect(()=>{x!=="complete"&&wl(x,{completedSteps:b,skippedSteps:N})},[x,b,N]),i.useEffect(()=>{gt.current||(gt.current=!0,ii("onboarding:wizard-opened",{source:jt?"resume":"initial",resumedFromStep:xt}))},[jt,xt]),i.useEffect(()=>{const M=Ie.current!=null,ue=l!=null;!M&&ue&&y(!0),ue||y(!1),Ie.current=l},[l]);const mn=i.useRef(m);i.useEffect(()=>{if(mn.current==="ai-setup"&&x!=="ai-setup"&&!$.some(ue=>ue.id!=="github"&&ue.authenticated)){const ue={};for(const Ee of $)Ee.id!=="github"&&!Ee.authenticated&&!Bt[Ee.id]&&(ue[Ee.id]=!0);if(Object.keys(ue).length>0){const Ee={...Bt,...ue};Jt(Ee),wl(x,{stepData:{"ai-setup":{skippedProviders:Ee}}})}}mn.current=x},[x,$,Bt]);const Ht=i.useCallback(async()=>{try{const{providers:M,ghCli:ue}=await xo(),Ee=Gf(M);V(Ee),ne(ue),G(z=>{const ge={};for(const[xe,dt]of Object.entries(z)){const Tt=Ee.find(Wt=>Wt.id===xe);Tt&&!Tt.authenticated&&Tt.loginInProgress&&(ge[xe]=dt)}return Object.keys(ge).length===Object.keys(z).length?z:ge}),St(z=>{let ge=!1;const xe={...z};for(const[dt,Tt]of Object.entries(z)){if(Tt!=="pending")continue;Ee.find(bn=>bn.id===dt)?.loginInProgress||(delete xe[dt],ge=!0)}return ge?xe:z}),Jt(z=>{const ge={...z};for(const xe of Ee)xe.authenticated&&ge[xe.id]&&delete ge[xe.id];return Object.keys(ge).length===Object.keys(z).length?z:ge})}catch{}},[]),Zt=i.useCallback(async()=>{try{const M=await Xj();tt((M.providers??[]).map(EL))}catch{}},[]),tn=i.useCallback(async M=>{Te(!0),Ve(void 0);try{await eN(M),await Zt(),await Fs().then(ue=>ee(ue.models??[])),de(!1)}catch(ue){Ve(Ce(ue)||"Failed to create custom provider")}finally{Te(!1)}},[Zt]),dn=i.useRef(!1);i.useEffect(()=>{x==="ai-setup"&&Zt(),dn.current&&Ht(),dn.current=x!=="ai-setup"},[x,Ht,Zt]),i.useEffect(()=>{if(!$.some(Ee=>Ee.loginInProgress))return;const ue=setInterval(()=>{Ht()},2e3);return()=>clearInterval(ue)},[$,Ht]);const qt=$.find(M=>M.id==="github"),ke=!!qt,$e=qt?.authenticated??!1,Ye=qt?.loginInProgress??!1,ut=Y?.authenticated??!1,We=$e||ut,$t=!$e&&ut,At=i.useCallback(M=>{if(M.authenticated)return"connected";const ue=Be?.[M.id];return ue==="timeout"||ue==="failed"?"retry":Bt[M.id]?"skipped":"not-connected"},[Be,Bt]);function wt({status:M}){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:Ee,className:z}=ue[M];return t.jsx("span",{"data-testid":"provider-status-badge",className:z,"data-status":M,children:Ee})}const zt=i.useCallback(()=>{if(We)return"connected";const M=Be.github;return M==="pending"?"pending":M==="failed"||M==="timeout"?"failed":ye?"skipped":"not-connected"},[We,Be,ye]);function Lt({status:M}){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:Ee,className:z}=ue[M];return t.jsx("span",{"data-testid":"github-status-badge",className:z,"data-status":M,children:Ee})}const Ot=i.useCallback(async()=>{try{const M=await Fs();ee(M.models)}catch{}},[]),nn=i.useCallback(async()=>{try{const M=await Ki();if(M.defaultProvider&&M.defaultModelId){const ue=`${M.defaultProvider}/${M.defaultModelId}`;K(ue)}}catch{}},[]);i.useEffect(()=>{Promise.all([Ht(),Ot(),nn()]).finally(()=>A(!1))},[Ht,Ot,nn]),i.useEffect(()=>{const M=bL("ai-setup");if(M?.loginOutcomes){const ue=M.loginOutcomes,Ee={};for(const[z,ge]of Object.entries(ue))ge!=="pending"&&(Ee[z]=ge);Object.keys(Ee).length>0&&St(Ee)}},[]);const Yt=i.useCallback((M,ue)=>{wl(x,{completedSteps:b,stepData:{"ai-setup":{loginOutcomes:{[M]:ue}}}})},[x,b]);i.useEffect(()=>{const M=Object.entries(Be).filter(([ue,Ee])=>Ee!=="pending");for(const[ue,Ee]of M)Yt(ue,Ee)},[Be,Yt]),i.useEffect(()=>()=>{Fe.current&&clearInterval(Fe.current),Object.values(ie.current).forEach(clearTimeout),ie.current={}},[]);const rn=i.useCallback(M=>{kt(M),wl(x,{completedSteps:b,stepData:{github:{skipped:M}}})},[x,b]),_e=i.useCallback(M=>M==="complete"?-1:na.indexOf(M),[]),it=i.useCallback(()=>{v(ue=>[...new Set([...ue,x])]),k(ue=>ue.filter(Ee=>Ee!==x)),ii("onboarding:step-completed",{step:x}),x==="github"&&!$e&&rn(!1);const M=_e(x);M>=0&&M<na.length-1&&w(na[M+1])},[x,$e,rn,_e]),bt=i.useCallback(()=>{k(ue=>[...new Set([...ue,x])]),mL(x),ii("onboarding:step-skipped",{step:x}),x==="github"&&!$e&&rn(!0);const M=_e(x);M>=0&&M<na.length-1&&w(na[M+1])},[x,$e,rn,_e]),Rt=i.useCallback(()=>{const M=x;v(Ee=>Ee.filter(z=>z!==M)),k(Ee=>Ee.filter(z=>z!==M)),M==="github"&&!$e&&rn(!1);const ue=_e(x);ue>0&&w(na[ue-1])},[x,$e,rn,_e]),se=i.useCallback(()=>{bt()},[bt]),te=i.useCallback(async M=>{St(Ee=>{const z=Ee[M];if(z&&z!=="pending"){const{[M]:ge,...xe}=Ee;return xe}return Ee});const ue=()=>{G(Ee=>{if(!(M in Ee))return Ee;const z={...Ee};return delete z[M],z}),Se(Ee=>{if(!(M in Ee))return Ee;const z={...Ee};return delete z[M],z}),ce(Ee=>{if(!(M in Ee))return Ee;const z={...Ee};return delete z[M],z})};ue(),St(Ee=>({...Ee,[M]:"pending"})),D(M),It.current=0;try{const{url:Ee,instructions:z,manualCode:ge}=await tN(M);z?.trim()&&G(xe=>({...xe,[M]:z})),ge&&Se(xe=>({...xe,[M]:ge})),window.open(Ii(Ee),"_blank"),Fe.current=setInterval(async()=>{if(It.current++,It.current>=OL){Fe.current&&(clearInterval(Fe.current),Fe.current=null),D(null),V(xe=>xe.map(dt=>dt.id===M?{...dt,loginInProgress:!1}:dt)),St(xe=>({...xe,[M]:"timeout"})),ue(),n("Login timed out. Please try again.","warning");return}try{const{providers:xe,ghCli:dt}=await xo(),Tt=Gf(xe);V(Tt),ne(dt);const Wt=Tt.find(bn=>bn.id===M);if(Wt?.authenticated){Fe.current&&(clearInterval(Fe.current),Fe.current=null),D(null),St(bn=>({...bn,[M]:"success"})),ue(),M==="github"&&rn(!1),n("Login successful","success");return}Wt?.loginInProgress||(Fe.current&&(clearInterval(Fe.current),Fe.current=null),D(null),St(bn=>({...bn,[M]:"failed"})),ue(),n("Login did not complete. Please try again.","error"))}catch{}},2e3)}catch(Ee){Ee instanceof Error&&Ee.message.includes("already in progress")||Ee&&typeof Ee=="object"&&"status"in Ee&&Ee.status===409?(n("Login already in progress. Cancel it to retry.","warning"),St(ge=>({...ge,[M]:"pending"})),Ht()):(n(Ee instanceof Error?Ee.message:"Login failed","error"),St(ge=>({...ge,[M]:"failed"}))),D(null),ue()}},[n,Ht,rn]),Oe=i.useCallback(async M=>{const ue=Ue[M]?.trim();if(!ue){n("Paste the full redirect URL or authorization code first.","warning");return}X(M);try{(await nN(M,ue)).submitted?(ce(z=>{if(!(M in z))return z;const ge={...z};return delete ge[M],ge}),n("Authorization code received. Finishing login…","success")):n("That authorization code was already submitted. Waiting for login…","warning")}catch(Ee){n(Ce(Ee)||"Failed to submit authorization code","error")}finally{X(null)}},[n,Ue]),mt=i.useCallback(async M=>{Fe.current&&(clearInterval(Fe.current),Fe.current=null),D(M),It.current=0,V(ue=>ue.map(Ee=>Ee.id===M?{...Ee,loginInProgress:!1}:Ee)),St(ue=>({...ue,[M]:"cancelled"}));try{await iN(M),await Ht().catch(()=>{}),n("Login cancelled","success")}catch(ue){n(Ce(ue)||"Failed to cancel login","error")}finally{D(null),G(ue=>{if(!(M in ue))return ue;const Ee={...ue};return delete Ee[M],Ee}),Se(ue=>{if(!(M in ue))return ue;const Ee={...ue};return delete Ee[M],Ee}),ce(ue=>{if(!(M in ue))return ue;const Ee={...ue};return delete Ee[M],Ee}),X(ue=>ue===M?null:ue)}},[n,Ht]),Pt=i.useCallback((M,ue)=>{B(z=>({...z,[M]:ue}));const Ee=ie.current[M];Ee&&(clearTimeout(Ee),delete ie.current[M]),ze(z=>{if(!z[M])return z;const ge={...z};return delete ge[M],ge}),He(z=>{if(!z[M])return z;const ge={...z};return delete ge[M],ge})},[]),sn=i.useCallback(()=>{const M=Ke.current;if(!M)return;const ue=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof M.scrollTo=="function"){M.scrollTo({top:0,behavior:ue?"auto":"smooth"});return}}catch{}M.scrollTop=0},[]),In=i.useCallback(async(M,ue)=>{const Ee=(ue??ve[M]??"").trim(),z=IL(M,Ee);if(z){ze(xe=>({...xe,[M]:z}));return}const ge=ie.current[M];ge&&(clearTimeout(ge),delete ie.current[M]),D(M),ze(xe=>{const dt={...xe};return delete dt[M],dt}),He(xe=>{if(!xe[M])return xe;const dt={...xe};return delete dt[M],dt});try{await aN(M,Ee),await Ht(),sn(),B(xe=>{const dt={...xe};return delete dt[M],dt}),ze(xe=>{if(!xe[M])return xe;const dt={...xe};return delete dt[M],dt}),He(xe=>({...xe,[M]:"✓ Key saved"})),ie.current[M]=setTimeout(()=>{He(xe=>{if(!xe[M])return xe;const dt={...xe};return delete dt[M],dt}),delete ie.current[M]},3e3),n("API key saved","success")}catch(xe){const dt=xe instanceof TypeError&&xe.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":xe instanceof Error?xe.message:"Failed to save API key";ze(Tt=>({...Tt,[M]:dt})),He(Tt=>{if(!Tt[M])return Tt;const Wt={...Tt};return delete Wt[M],Wt}),n(dt,"error")}finally{D(null)}},[ve,n,Ht,sn]),fe=i.useCallback(async M=>{D(M);try{await rN(M),await Ht(),n("API key removed","success")}catch(ue){n(ue instanceof Error?ue.message:"Failed to clear API key","error")}finally{D(null)}},[n,Ht]),ft=i.useCallback(async M=>{D(M);try{await sN(M),await Ht(),n("Logged out","success")}catch(ue){n(ue instanceof Error?ue.message:"Logout failed","error")}finally{D(null)}},[n,Ht]),lt=i.useCallback(M=>{K(M)},[]),vt=i.useCallback(async()=>{try{const M={modelOnboardingComplete:!0};if(le){const ue=le.indexOf("/"),Ee=ue!==-1?le.slice(0,ue):void 0,z=ue!==-1?le.slice(ue+1):le,ge=Z.find(xe=>xe.id===z);ge?(M.defaultProvider=ge.provider,M.defaultModelId=ge.id):Ee&&z&&(M.defaultProvider=Ee,M.defaultModelId=z)}await Pn(M),Jf()}catch{}},[le,Z,Pn,Jf]),et=i.useCallback(async()=>{const M=[...new Set([...b,"first-task"])];pe(!0);try{await vt(),ii("onboarding:completed",{completedSteps:M,skippedSteps:N}),v(M),k(ue=>ue.filter(Ee=>Ee!=="first-task")),w("complete")}finally{pe(!1)}},[vt,b,N]),_t=i.useCallback(async()=>{if(!s)return;const M=j.trim();if(!M){L("Please enter a task description.");return}L(null),_(!0);let ue=!1;try{const Ee=await Wg({description:M,source:{sourceType:"dashboard_ui"}},s);C(Ee),y(!0),ii("onboarding:first-task-created",{taskId:Ee?.id}),n("Task created","success"),ue=!0}catch(Ee){const z=Ee instanceof Error?Ee.message:"Something went wrong creating your task. Please try again.";L(z),n(z,"error")}finally{_(!1)}ue&&vt()},[s,j,n,vt]),Gt=i.useCallback(async()=>{pe(!0);try{await vt()}finally{pe(!1)}ii("onboarding:open-new-task",{}),r?.()},[vt,r]),ae=i.useCallback(async()=>{if(We){pe(!0);try{await vt()}finally{pe(!1)}g(!1),e(),ii("onboarding:open-github-import",{}),o?.()}},[vt,We,e,o]),pt=i.useCallback(async()=>{ii("onboarding:dismissed",{currentStep:x,completedSteps:b,skippedSteps:N}),pe(!0);try{await Pn({modelOnboardingComplete:!0})}catch{}g(!1),e()},[x,b,N,e]),gn=i.useCallback(()=>{ii("onboarding:finished",{}),g(!1),e()},[e]),us=i.useCallback(()=>{const M=l??U;M&&(vt(),c?.(M),e())},[l,U,vt,c,e]),Kn=i.useCallback(()=>{vt(),e()},[vt,e]),_n=zt(),$n=$.filter(M=>M.id!=="github"),hn=ot.host!=="web"&&!ot.activeProfileId,Ut=[...$n].sort(eg),Dn=Ut.some(M=>!M.type||M.type==="oauth"),as=Ut.some(M=>M.type==="api_key"),Rn=$n.filter(M=>M.authenticated),ms=Rn.length>0,Xn=!!s,vs=x==="github"&&!ms,Gn=i.useCallback(async()=>{if(be){at(null),Re(!0);try{const M=await be.saveProfile({name:me,serverUrl:Me,authToken:rt.trim()?rt:null});try{await be.setActiveProfile(M.id)}catch(ue){at(Ce(ue)||"Saved profile but failed to activate it");return}Xe(""),ht(""),n("Remote server profile saved","success")}catch(M){at(Ce(M)||"Failed to save shell connection")}finally{Re(!1)}}},[be,me,Me,rt,n]);if(!p)return null;const hs=(()=>{if(!le)return"";const M=le.indexOf("/"),ue=M===-1?void 0:le.slice(0,M),Ee=M===-1?le:le.slice(M+1),z=Z.find(ge=>ge.id===Ee&&(!ue||ge.provider===ue));return z?.name?z.name:ue?`${xu(ue)} ${Ee}`:le})(),Ln=[];if(Xn?Ln.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):Ln.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),ms){const M=xu(Rn[0]?.id??"");Ln.push({label:"AI Provider",status:"connected",detail:`${M} connected — AI agents can work on tasks`})}else $n.length>0&&$n.some(M=>Bt[M.id])?Ln.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):Ln.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});We?Ln.push({label:"GitHub",status:"connected",detail:$t?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!ke||ye?Ln.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):Ln.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),hs&&Ln.push({label:"Default Model",status:"connected",detail:hs});const En=l??U,ps=En?.description?.split(`
692
- `)[0]?.trim()||En?.title||"",Nn=new Set(Td),As=Ut.filter(M=>Nn.has(M.id)).sort((M,ue)=>{const Ee=Td.indexOf(M.id),z=Td.indexOf(ue.id);return Ee!==z?Ee-z:eg(M,ue)}),Cs=Ut.filter(M=>M.authenticated&&!Nn.has(M.id)),Es=Ut.filter(M=>!M.authenticated&&!Nn.has(M.id)),Q=M=>{const ue=Be[M.id]==="timeout"||Be[M.id]==="failed"||Be[M.id]==="cancelled",Ee=M.loginInProgress&&!ue;if(M.id==="llama-cpp"&&M.type==="cli")return t.jsx(GD,{authenticated:M.authenticated,onToggled:()=>{Ht()}},M.id);if(M.id==="claude-cli"&&M.type==="cli")return t.jsx(VD,{authenticated:M.authenticated,onToggled:()=>{Ht()}},M.id);if(M.id==="cursor-cli"&&M.type==="cli")return t.jsx(KD,{authenticated:M.authenticated,onToggled:()=>{Ht()}},M.id);if(M.type==="api_key"){const z=yu(M.id),ge=$L(M);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${M.id}`,className:`onboarding-provider-card${M.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${M.id}`,"aria-hidden":"true",children:t.jsx(Tn,{provider:M.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(zg,{size:14,className:"onboarding-provider-key-icon"}),M.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:z.description}),t.jsx(wt,{status:At(M)}),M.authenticated&&M.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",M.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(LL,{provider:M,apiKeyInfo:ge,inputValue:ve[M.id]??"",isSaving:I===M.id,error:we[M.id],success:re[M.id],isConnected:M.authenticated,onInputChange:Pt,onSave:In,onClear:fe})})]},M.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${M.id}`,className:`onboarding-provider-card${M.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${M.id}`,"aria-hidden":"true",children:t.jsx(Tn,{provider:M.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:M.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:yu(M.id).description}),t.jsx(wt,{status:At(M)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:I===M.id?M.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 mt(M.id),children:"Cancel"})]}):Ee?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 mt(M.id),children:"Cancel"})]}):M.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>ft(M.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>te(M.id),children:"Login"})}),(I===M.id||Ee)&&S[M.id]&&t.jsx(Id,{instructions:S[M.id],"data-testid":`onboarding-login-instructions-${M.id}`}),(I===M.id||Ee)&&he[M.id]&&t.jsx(YD,{value:Ue[M.id]??"",onChange:z=>ce(ge=>({...ge,[M.id]:z})),onSubmit:()=>void Oe(M.id),prompt:he[M.id].prompt,placeholder:he[M.id].placeholder,helpText:he[M.id].helpText,disabled:Ae===M.id,submitLabel:Ae===M.id?"Submitting…":"Submit code","data-testid":`onboarding-manual-code-${M.id}`}),Be[M.id]==="timeout"&&I!==M.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),Be[M.id]==="failed"&&I!==M.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},M.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:je,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(is,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(Js,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(xm,{size:24})," Set Up Your Project"]}),x==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(xm,{size:24})," Create Your First Task"]}),x==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(Wn,{size:24})," All Set!"]})]}),x!=="complete"&&t.jsx("button",{className:"modal-close",onClick:pt,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(an,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:Vt.map((M,ue)=>{const Ee=Xt>ue,z=b.includes(M.key)&&Ee,ge=N.includes(M.key)&&!b.includes(M.key)&&Ee,xe=z||ge;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[ue>0&&t.jsx("div",{className:`model-onboarding-step-connector ${ue<=Xt?"done":""}`}),xe?t.jsxs("button",{className:`model-onboarding-step-indicator ${x===M.key?"active":""} ${z?"done":""} ${ge?"skipped":""}`,onClick:()=>w(M.key),"aria-label":`Go back to ${M.label}`,title:`Review ${M.label}`,children:[t.jsx("span",{className:"step-number",children:z?t.jsx(Wn,{size:14}):ge?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):ue+1}),t.jsx("span",{className:"step-label",children:M.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${x===M.key?"active":""} ${z?"done":""} ${ge?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:z?t.jsx(Wn,{size:14}):ge?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):ue+1}),t.jsx("span",{className:"step-label",children:M.label})]})]},M.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:Ke,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."}),hn&&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:M=>oe(M.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:Me,onChange:M=>Xe(M.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:rt,onChange:M=>ht(M.target.value)}),Ge&&t.jsx("small",{className:"field-error",children:Ge}),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 Gn(),disabled:!Me.trim()||yt,children:yt?"Saving…":"Save remote server"})]})]}),!q&&$.length>0&&(()=>{const M=$.filter(xe=>xe.id!=="github"&&xe.authenticated).length,ue=$.filter(xe=>xe.id!=="github").length,Ee=Object.keys(Bt).filter(xe=>!$.find(dt=>dt.id===xe)?.authenticated).length;if(ue===0)return null;let z="onboarding-provider-summary",ge="";return M>0?(z+=" onboarding-provider-summary--connected",ge=`✓ ${M} of ${ue} provider${ue!==1?"s":""} connected`):Ee>0?(z+=" onboarding-provider-summary--skipped",ge=`${Ee} provider${Ee!==1?"s":""} skipped`):(z+=" onboarding-provider-summary--none",ge="No providers connected yet"),t.jsx("div",{className:z,"data-testid":"provider-summary",children:ge})})(),t.jsx(ia,{slotId:"onboarding-recommendation-card",projectId:s}),t.jsx(ai,{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."})}),$.length>0&&!$.some(M=>M.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),q?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(Nt,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):$.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(ia,{slotId:"onboarding-provider-card",projectId:s,renderPlaceholder:!1,actions:{refreshAuthProviders:()=>{Ht()}}}),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"}),As.length>0?t.jsx("div",{className:"model-onboarding-providers",children:As.map(M=>Q(M))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),Cs.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:Cs.map(M=>Q(M))})]}),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(ai,{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."})}),Z.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(Ns,{models:Z,value:le,onChange:lt,placeholder:"Select a default model…",label:"Default model"})}),le&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",Z.find(M=>M.id===le)?.name??le]})})]}),t.jsx(ai,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsxs("div",{"data-testid":"onboarding-advanced-provider-settings",children:[Es.length>0?t.jsx("div",{className:"model-onboarding-providers",children:Es.map(M=>Q(M))}):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(M=>t.jsxs("div",{className:"onboarding-custom-provider-item",children:[t.jsx(Tn,{provider:M.id,size:"sm"}),t.jsx("span",{children:M.name||M.id})]},M.id))}):null,qe?t.jsx(ZD,{onSave:tn,onCancel:()=>{de(!1),Ve(void 0)},saving:De,error:ct}):t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>de(!0),children:"Add custom provider"})]})}),Dn&&t.jsx(ai,{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."})}),as&&t.jsx(ai,{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(ia,{slotId:"onboarding-setup-help",projectId:s})]})]}),x==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[We?t.jsx("p",{className:"model-onboarding-description",children:$t?"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."}),!We&&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(ai,{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."})}),ke?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(Js,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(Lt,{status:_n})})]}),$e&&(I==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>ft("github"),children:"Disconnect"}))]}),(_n==="not-connected"||_n==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[I==="github"||Ye?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 mt("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>te("github"),children:[t.jsx(Js,{size:16}),"Connect"]}),(I==="github"||Ye)&&S.github&&t.jsx(Id,{instructions:S.github,"data-testid":"onboarding-login-instructions-github"})]}),_n==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:$t?"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."}),_n==="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"})]})]}),_n==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),_n==="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"})})]}),_n==="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(Tn,{provider:"github",size:"lg"})}),$t?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:$t?"Continue with gh CLI auth →":"Continue without GitHub →"}),$t&&(I==="github"||Ye?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(Nt,{size:14,className:"onboarding-spinner"}),"Waiting for OAuth login…"]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>te("github"),children:[t.jsx(Tn,{provider:"github",size:"sm"}),"Connect OAuth (optional)"]}))]}),$t&&(I==="github"||Ye)&&S.github&&t.jsx(Id,{instructions:S.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."}),Xn?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(ai,{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."}),E&&En?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(Wn,{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:En.id}),ps&&t.jsx("p",{className:"onboarding-task-created__description",children:ps}),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:us,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:Kn,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[Xn?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:j,onChange:M=>{P(M.target.value),L(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:_t,disabled:F,"data-testid":"onboarding-first-task-submit",children:F?t.jsxs(t.Fragment,{children:[t.jsx(Nt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),R&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:R}),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(DL,{items:Ln}),Xn&&t.jsxs(t.Fragment,{children:[t.jsx(ai,{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:Gt,disabled:O,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Cn,{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${We?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:ae,disabled:O||!We,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Js,{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"}),!We&&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(Wn,{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:pt,disabled:O,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:bt,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:Rt,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:bt,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:Rt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:it,disabled:!Xn,children:"Next →"})]}),x==="first-task"&&!E&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Rt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:et,disabled:O,children:O?t.jsxs(t.Fragment,{children:[t.jsx(Nt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),x==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:gn,children:[t.jsx(Wn,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function jv({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 FL=i.lazy(()=>kn(()=>import("./SetupWizardModal-D1q548_L.js"),__vite__mapDeps([13,1,14,15,16,17,5,6,18])).then(e=>({default:e.SetupWizardModal}))),BL=i.lazy(()=>kn(()=>import("./SettingsModal-BLsac7CJ.js"),__vite__mapDeps([19,1,20,21,22,2,5,6,23])).then(e=>({default:e.SettingsModal})));function UL(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{kn(()=>import("./SettingsModal-BLsac7CJ.js"),__vite__mapDeps([19,1,20,21,22,2,5,6,23]))},{timeout:1500})}function HL({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 j=n.find(P=>P.id===c.detailTask?.id);return j?"prompt"in c.detailTask?{...c.detailTask,...j,prompt:c.detailTask.prompt,log:c.detailTask.log}:j:c.detailTask})():null,v=p??c.closeSettings,N=i.useCallback(()=>{c.openNewTask()},[c]),k=i.useCallback(()=>{c.openGitHubImport()},[c]),E=i.useCallback(j=>{w(null),c.closeModelOnboarding(),c.openDetailTask(j)},[c]),y=i.useCallback(async j=>{const P=await u.handleModalCreate(j);return c.modelOnboardingOpen&&w(P),P},[u.handleModalCreate,c.modelOnboardingOpen]);return i.useEffect(()=>{!c.modelOnboardingOpen&&x&&w(null)},[c.modelOnboardingOpen,x]),i.useEffect(()=>{UL()},[]),t.jsxs(t.Fragment,{children:[b&&t.jsx(Sa,{children:t.jsx(dT,{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(Sa,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(BL,{onClose:v,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(y4,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:u.handleGitHubImport,tasks:n,projectId:e}),t.jsx(Sa,{children:t.jsx(N4,{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(Sa,{children:t.jsx(T4,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:u.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(n$,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(i$,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(C$,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),c.todosOpen&&t.jsx(_$,{isOpen:!0,onClose:c.closeTodos,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan}),t.jsx(L$,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e,anchorRect:c.usageAnchorRect}),t.jsx(hD,{isOpen:c.systemStatsOpen,onClose:c.closeSystemStats,projectId:e}),c.schedulesOpen&&t.jsx(sD,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(Sa,{children:t.jsx(oD,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:y,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(xD,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:a,onOpenTaskDetail:j=>{const P=n.find(F=>F.id===j);P&&c.openDetailTask(P)}}),t.jsx(Sa,{children:t.jsx(yD,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(Sa,{children:t.jsx(AD,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(qD,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(i.Suspense,{fallback:null,children:t.jsx(FL,{onProjectRegistered:d.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(zL,{onComplete:d.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:d.handleAddProject,onOpenNewTask:N,onOpenGitHubImport:k,firstCreatedTask:x,onViewTask:E}),t.jsx(jv,{toasts:o,onRemove:l})]})}function qL({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 wu=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function VL(e,n){if(n==="ready")return"done";const s=wu.findIndex(r=>r.id===n),a=wu.findIndex(r=>r.id===e);return a<s?"done":a===s?"active":"pending"}function WL({stage:e}){const[n]=i.useState(()=>Wk());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:wu.map(s=>{const a=VL(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(Nt,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:s.label})]},s.id)})})]})})}const KL=5e3;function GL(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function JL(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++,zl(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 YL(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 QS(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()},KL),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[f]);const p=JL(e,s,a),g=GL(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:g,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:d,refresh:f}}const QL={planning:Pi,subtask:Ia,mission_interview:js,milestone_interview:js,slice_interview:js},XL={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function ZL({sessions:e,generating:n,needsInput:s,onOpenSession:a,onDismissSession:r}){const{confirm:o}=ci(),[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}=Ir(),g=i.useMemo(()=>Ua(),[]);if(i.useEffect(()=>{if(!l)return;const b=v=>{m.current&&!m.current.contains(v.target)&&c(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[l]),i.useEffect(()=>{const b=new Set,v=new Map;for(const N of e){const k=p.get(N.id),E=[N.status,N.updatedAt,k?.tabId??N.lockedByTab??"",k?.stale?"stale":"fresh"].join("|"),y=h.current.get(N.id);y&&y!==E&&b.add(N.id),v.set(N.id,E)}if(h.current=v,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(Nt,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(Fd,{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 v=QL[b.type],N=b.status==="generating",k=b.status==="awaiting_input",E=b.status==="error",y=p.get(b.id),j=y?.tabId??b.lockedByTab??null,P=!!(j&&j!==g&&!y?.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()=>{P&&!await o({title:"Open Active Session",message:"This session is active in another tab. Open anyway?"})||(a(b),c(!1))},children:[E?t.jsx(Ts,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):t.jsx(v,{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:[E?"Failed":XL[b.type],N&&" — generating...",k&&!P&&" — needs input",k&&P&&" — active in another tab"]})]}),N&&t.jsx(Nt,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),k&&!P&&t.jsx(Fd,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),k&&P&&t.jsx(ac,{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(an,{size:12})})]},b.id)})})]})]})}function eO(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 tO(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:ss};case"paused":return{label:"Paused",color:"var(--triage)",icon:xi};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:is}}}function nO({tasks:e,projectId:n,taskStuckTimeoutMs:s,backgroundSessions:a,backgroundGenerating:r,backgroundNeedsInput:o,onOpenBackgroundSession:l,onDismissBackgroundSession:c,lastFetchTimeMs:d,currentProjectPath:u,onOpenProjectDirectory:m,keyboardOpen:h}){if(h)return null;const{stats:f,loading:p,error:g}=YL(e,n,s,d),[x,w]=i.useState(!1),b=i.useMemo(()=>tO(f.executorState),[f.executorState]),v=i.useMemo(()=>eO(f.lastActivityAt),[f.lastActivityAt]),N=b.icon;return g?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(Ro,{size:14}),g]})}):p&&f.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 ${f.executorState==="running"?"executor-status-bar--running":""}`,role:"status","aria-label":"Executor status",children:[a&&a.length>0&&l&&c&&t.jsxs(t.Fragment,{children:[t.jsx(ZL,{sessions:a,generating:r??0,needsInput:o??0,onOpenSession:l,onDismissSession:c}),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:f.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 ${f.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:f.runningTaskCount}),t.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),t.jsx("span",{className:"executor-status-bar__max",children:f.maxConcurrent})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),f.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:f.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 ${f.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 ${f.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:f.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:f.inReviewCount})]}),u&&m&&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${x?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>w(k=>!k),"aria-label":x?"Hide project directory":"Show project directory","aria-expanded":x,"data-testid":"executor-project-path-toggle",title:x?"Hide project directory":"Show project directory",children:t.jsx(ys,{size:12,"aria-hidden":"true"})}),x&&t.jsx("button",{className:"executor-status-bar__project-path",onClick:m,title:u,"data-testid":"executor-project-path-link",children:u})]})]}),t.jsx("div",{className:"executor-status-bar__spacer"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[t.jsx(Wi,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:v})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx(N,{size:12,style:{color:b.color},"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__state",style:{color:b.color},children:b.label})]})]})}const sO={planning:Pi,subtask:Ia,mission_interview:js,milestone_interview:js,slice_interview:js},iO={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},Nv="fusion:session-banner-dismissed";function lo(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function aO(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(Nv);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:lo(r);s.set(a,o)}return s}catch{return new Map}}function rO(e){if(!(typeof window>"u"))try{const n={};for(const[s,a]of e)n[s]=a;window.localStorage.setItem(Nv,JSON.stringify(n))}catch{}}const Ui=aO();function oO({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:a}){const[r,o]=i.useState(0),l=()=>{rO(Ui),o(g=>g+1)};i.useEffect(()=>{if(Ui.size===0)return;const g=new Map(e.map(w=>[w.id,w]));let x=!1;for(const[w,b]of Ui){const v=g.get(w);if(!v)continue;if(!(v.status==="awaiting_input"||v.status==="error")){Ui.delete(w),x=!0;continue}lo(v.updatedAt)>b&&(Ui.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=Ui.get(g.id);return x===void 0?!0:lo(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=>{Ui.set(g.id,Math.max(lo(g.updatedAt),Date.now())),l()},f=g=>{Ui.delete(g.id),l(),n(g)},p=()=>{const g=Date.now();for(const x of c)Ui.set(x.id,Math.max(lo(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(Ts,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(an,{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=sO[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(Ts,{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":iO[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(an,{size:14,"aria-hidden":"true"})})]})]},g.id)})})]})}const Sv="fusion:cli-binary-banner-dismissed";function lO(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Sv)==="1"}catch{return!1}}function cO(){if(!(typeof window>"u"))try{window.localStorage.setItem(Sv,"1")}catch{}}function dO({onOpenSettings:e}){const[n,s]=i.useState(null),[a,r]=i.useState(()=>lO()),[o,l]=i.useState(!1),[c,d]=i.useState(null);i.useEffect(()=>{if(a)return;let v=!1;return Hj().then(N=>{v||s(N)}).catch(()=>{}),()=>{v=!0}},[a]);const u=i.useCallback(async()=>{l(!0),d(null);try{const v=await qj();s({binary:v.binary,expectedVersion:v.expectedVersion,state:v.state,install:v.install}),v.installResult.success||d(v.installResult.permissionsHint||v.installResult.stderr||`Install failed (exit ${v.installResult.exitCode??"n/a"})`)}catch(v){d(v instanceof Error?v.message:String(v))}finally{l(!1)}},[]),m=i.useCallback(()=>{cO(),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(an,{size:16})})]})}function uO({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:"npm i -g @runfusion/fusion"})," to update. "," ",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(an,{size:16,"aria-hidden":"true"})})]})}function mO({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(Ro,{"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(Ma,{"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(an,{"aria-hidden":"true"})})]})]})})}function hO({onResume:e}){const n=fL();if(!n)return null;const s=n.completedSteps.length,a=na.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(xs,{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:()=>{ii("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(ss,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function pO({onOpenSettings:e,onOpenModelOnboarding:n}){const s=Cr(),a=vv(),[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[N,k]=await Promise.all([xo(),Ki()]);if(b)return;const E=N.providers??[],y=E.find(R=>R.id==="github"),P=!E.some(R=>R.id!=="github"&&R.authenticated),F=!k.defaultProvider&&!k.defaultModelId,_=y?!y.authenticated:!1;h({needsAiProvider:P,needsDefaultModel:F,needsGitHub:_})}catch{b||c(!0)}finally{b||o(!1)}})(),()=>{b=!0}},[s,a]);const f=i.useCallback(()=>{hL(),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:is}),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:zg}),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:Js}),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(Pi,{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 v=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(v,{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(ia,{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(an,{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 Qr(e){return e>99?"99+":String(e)}function gO({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:v,onOpenTodos:N,todosOpen:k=!1,onOpenGitHubImport:E,onOpenPlanning:y,onResumePlanning:j,activePlanningSessionCount:P=0,onOpenUsage:F,onRunScript:_,projectId:R,onViewAllProjects:L,showSkillsTab:U,experimentalFeatures:C,onOpenNodes:$,pluginDashboardViews:V=[],shellConnectionControl:Y}){const ne=Zs(),[q,A]=i.useState(!1),[I,D]=i.useState(!1),[S,G]=i.useState({}),[he,Se]=i.useState(!1),Ue=i.useMemo(()=>Object.entries(S).sort(([re],[He])=>re.localeCompare(He)),[S]);i.useEffect(()=>{if(!I)return;let re=!1;return Se(!0),vo(R).then(He=>{re||G(He)}).catch(()=>{re||G({})}).finally(()=>{re||Se(!1)}),()=>{re=!0}},[I,R]);const ce=i.useCallback(()=>A(!1),[]),Ae=i.useCallback(re=>{ce(),re?.()},[ce]);if(i.useEffect(()=>{if(!q)return;const re=He=>{He.key==="Escape"&&A(!1)};return document.addEventListener("keydown",re),()=>document.removeEventListener("keydown",re)},[q]),ne!=="mobile"||a||r)return null;const X=P>0&&j?j:y,Z=!!U,ee=!!C?.todoView,le=Z,K=Z&&!le,ve=V.filter(re=>re.view.placement==="primary").sort((re,He)=>(re.view.order??Number.MAX_SAFE_INTEGER)-(He.view.order??Number.MAX_SAFE_INTEGER)).slice(0,1),B=new Set(ve.map(re=>`${re.pluginId}:${re.view.viewId}`)),we=V.filter(re=>!B.has(`${re.pluginId}:${re.view.viewId}`)).sort((re,He)=>(re.view.order??Number.MAX_SAFE_INTEGER)-(He.view.order??Number.MAX_SAFE_INTEGER)),ze=e==="documents"||!!C?.evalsView&&e==="evals"||e==="research"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||k&&ee||e==="skills"&&!le||e==="graph"||e==="stash-recovery"||ur(e)&&!ve.some(re=>uo(re.pluginId,re.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(la,{}),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(Vn,{}),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(js,{}),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(qi,{}),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(Ta,{}),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:Qr(u)})]}),le&&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(is,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),ve.map(re=>{const He=uo(re.pluginId,re.view.viewId),Pe=Dl(re.view.icon);return t.jsxs("button",{type:"button",className:`mobile-nav-tab${e===He||e==="graph"&&re.pluginId==="fusion-plugin-dependency-graph"&&re.view.viewId==="graph"?" mobile-nav-tab--active":""}`,"data-testid":`mobile-nav-tab-plugin-${re.pluginId}-${re.view.viewId}`,role:"tab","aria-selected":e===He||e==="graph"&&re.pluginId==="fusion-plugin-dependency-graph"&&re.view.viewId==="graph",onClick:()=>n(re.pluginId==="fusion-plugin-dependency-graph"&&re.view.viewId==="graph"?"graph":He),children:[t.jsx(Pe,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:re.view.label})]},`${re.pluginId}:${re.view.viewId}`)}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${ze?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>A(re=>!re),children:[t.jsx(Bd,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),q&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:ce}),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"}),Y?t.jsx("div",{className:"mobile-more-shell-connection","data-testid":"mobile-more-shell-connection",children:Y}):null,t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-mailbox",onClick:()=>Ae(d),children:[t.jsx(Ta,{}),t.jsx("span",{children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:Qr(u)}),m>0&&t.jsx("span",{className:"mobile-more-item-badge",children:Qr(m)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>Ae(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:()=>Ae(c),children:[t.jsx(fr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>Ae(p),children:[t.jsx(Ps,{}),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:()=>Ae(b),children:[t.jsx(Vi,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>D(re=>!re),"aria-expanded":I,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(zn,{size:14,className:`mobile-more-chevron${I?" mobile-more-chevron--open":""}`})})]}),I&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:he?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(Nt,{className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):Ue.length>0?t.jsxs(t.Fragment,{children:[Ue.map(([re,He])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${re}`,onClick:()=>{_&&_(re,He),ce(),D(!1)},children:[t.jsx(ss,{}),t.jsx("span",{children:re})]},re)),w&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{ce(),D(!1),w()},children:[t.jsx(bi,{}),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:()=>{ce(),D(!1),w()},children:[t.jsx(bi,{}),t.jsx("span",{children:"No scripts — add one…"})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>Ae(v),children:[t.jsx(ys,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>Ae(X),children:[t.jsx(Pi,{}),t.jsx("span",{children:"Planning"}),P>0&&t.jsx("span",{className:"mobile-more-item-badge",children:Qr(P)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>Ae(g),children:[t.jsx(Pl,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>Ae(x),children:[t.jsx(Wi,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>Ae(E),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:()=>Ae(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:()=>Ae(L),children:[t.jsx(nc,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>Ae(()=>n("documents")),children:[t.jsx(oa,{}),t.jsx("span",{children:"Documents"})]}),C?.evalsView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-evals",onClick:()=>Ae(()=>n("evals")),children:[t.jsx(js,{}),t.jsx("span",{children:"Evals"})]}),K&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>Ae(()=>n("skills")),children:[t.jsx(is,{}),t.jsx("span",{children:"Skills"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-stash-recovery",onClick:()=>Ae(()=>n("stash-recovery")),children:[t.jsx(Pa,{}),t.jsx("span",{children:"Stash Recovery"}),f>0?t.jsx("span",{className:"mobile-more-item-badge",children:Qr(f)}):null]}),C?.researchView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-research",onClick:()=>Ae(()=>n("research")),children:[t.jsx(Hi,{}),t.jsx("span",{children:"Research"})]}),C?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>Ae(()=>n("insights")),children:[t.jsx(xs,{}),t.jsx("span",{children:"Insights"})]}),C?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>Ae(()=>n("memory")),children:[t.jsx(go,{}),t.jsx("span",{children:"Memory"})]}),C?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{Ae(()=>n("dev-server"))},children:[t.jsx(fr,{}),t.jsx("span",{children:"Dev Server"})]}),C?.nodesView&&$&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-nodes",onClick:()=>Ae($),children:[t.jsx(nk,{}),t.jsx("span",{children:"Nodes"})]}),ee&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>Ae(()=>N?.()),children:[t.jsx(Cu,{}),t.jsx("span",{children:"Todos"})]}),we.map(re=>{const He=uo(re.pluginId,re.view.viewId),Pe=Dl(re.view.icon);return t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":`mobile-more-item-plugin-${re.pluginId}-${re.view.viewId}`,onClick:()=>Ae(()=>n(re.pluginId==="fusion-plugin-dependency-graph"&&re.view.viewId==="graph"?"graph":He)),children:[t.jsx(Pe,{}),t.jsx("span",{children:re.view.label})]},`${re.pluginId}:${re.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:()=>Ae(o),children:[t.jsx(co,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function tg(e){return e.trim().toLowerCase().replace(/[\s-]+/g,"_").replace(/_+/g,"_")}function Cv(e,n){const s=n.trim();if(!s)return!0;const a=tg(s);return tg(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=>Cv(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(Gl,{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(Gl,{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 ng(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)},v=()=>{w=null,r(f)},N=()=>{x!==null&&(cancelAnimationFrame(x),x=null),w!==null&&(cancelAnimationFrame(w),w=null)};return l.current=N,{handlers:{onThinking:E=>{f+=E,w===null&&(w=requestAnimationFrame(v))},onText:E=>{h+=E,x===null&&(x=requestAnimationFrame(b))},onToolStart:E=>{p=[...p,{toolName:E.toolName,args:E.args,isError:!1,status:"running"}],o(p)},onToolEnd:E=>{const y=[...p];for(let j=y.length-1;j>=0;j--){const P=y[j];if(P?.toolName===E.toolName&&P.status==="running"){y[j]={...P,status:"completed",isError:E.isError,result:E.result},p=y,o(y);return}}p=[...y,{toolName:E.toolName,isError:E.isError,result:E.result,status:"completed"}],o(p)},onFallback:E=>{g=E,m?.(E,n),c?.(`Primary model unavailable. Switched to fallback ${E.fallbackModel}.`,"warning")},onDone:E=>{N(),d({messageId:E.messageId,message:E.message,accumulated:{text:h,thinking:f,toolCalls:p,fallbackInfo:g}})},onError:E=>{N(),u(E,s)}},cancelFlushes:N}}const xO=["load failed","failed to fetch","networkerror when attempting to fetch resource.","connection aborted","connection closed unexpectedly","network error"];function vO(e){const n=e.trim().toLowerCase();return n?xO.some(s=>n.includes(s)):!1}function yO(){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 dr="__fn_agent__";function Ev(e,n){const s=typeof e=="string"?e.trim():"",a=typeof n=="string"?n.trim():"";return!s||!a?{}:{modelProvider:s,modelId:a}}function kl(e,n,s){const a=typeof e=="string"?e.trim():"",r=Ev(n,s),o=a||(r.modelProvider&&r.modelId?dr:"");return o?{agentId:o,...r}:null}function jl(e,n,s){const a=Ev(n,s),r=a.modelProvider??"",o=a.modelId??"";return`${e}::${r}/${o}`}function sg(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 wO(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 kO(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 ar(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:wO(e.metadata),fallbackInfo:kO(e.metadata),createdAt:e.createdAt}}function jO(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(""),[v,N]=i.useState([]),[k,E]=i.useState(""),y=i.useRef(null),j=i.useRef(!1),P=i.useRef(null),F=i.useRef(""),_=i.useRef(f);_.current=f;const R=i.useRef(null),L=i.useRef(""),U=i.useRef(null),C=i.useRef(s);C.current=s;const $=i.useRef(0),V=3,Y=i.useRef(!1);i.useEffect(()=>{F.current=k},[k]);const ne=i.useCallback(async()=>{c(!0);try{const K=await Km(e);o(K.sessions)}catch(K){console.error("[useQuickChat] Failed to refresh sessions:",K)}finally{c(!1)}},[e]),q=i.useCallback(async K=>{const O={agentId:K.agentId};return K.modelProvider&&K.modelId&&(O.modelProvider=K.modelProvider,O.modelId=K.modelId),(await x0(O,e)).session},[e]),A=i.useCallback(K=>{if(y.current||!K)return!0;j.current=!1,p(!0);const{handlers:O}=ng({sessionId:K,tempUserMessageId:"",setStreamingText:x,setStreamingThinking:b,setStreamingToolCalls:N,cancelStreamingFlushesRef:P,addToast:n,onFallbackSession:(pe,ve)=>{const B=sg(pe.fallbackModel);o(we=>we.map(ze=>ze.id===ve?{...ze,...B}:ze)),a(we=>we&&we.id===ve?{...we,...B}:we)},onDone:()=>{x(""),b(""),N([]),p(!1),_.current=!1,y.current=null,Or(K,{limit:50},e).then(pe=>{u(pe.messages.map(ar))}).catch(()=>{})},onError:pe=>{x(""),b(""),N([]),p(!1),_.current=!1,y.current=null;const ve=typeof pe=="string"&&pe.trim()?pe:"Failed to get response";n?.(ve,"error"),Or(K,{limit:50},e).then(B=>{u(B.messages.map(ar))}).catch(()=>{})}});return y.current=k0(K,O,e),!0},[n,e]),I=i.useCallback(async(K,O,pe)=>{const ve=kl(K,O,pe);if(!ve)return;const B=jl(ve.agentId,ve.modelProvider,ve.modelId);c(!0);try{const{session:we}=await b0({agentId:ve.agentId,modelProvider:ve.modelProvider,modelId:ve.modelId},e);if(we)a(we),L.current=B,we.isGenerating&&(x(""),A(we.id));else{const ze=await q(ve);a(ze),L.current=B}$.current=0}catch(we){console.error("[useQuickChat] Failed to initialize session:",we),$.current+=1,$.current<=V&&n?.("Failed to initialize chat","error")}finally{c(!1)}},[A,e,n,q]),D=i.useCallback(async()=>{if(s){h(!0);try{const K=await Or(s.id,{limit:50},e);u(K.messages.map(ar))}catch(K){console.error("[useQuickChat] Failed to load messages:",K)}finally{h(!1)}}},[s,e]);i.useEffect(()=>{s?D():u([])},[s,D]),i.useEffect(()=>{if(!s?.isGenerating||(y.current||A(s.id),!_.current||y.current||!s))return;const K=setInterval(async()=>{if(!_.current||y.current||!s){clearInterval(K);return}try{if(!(await v0(s.id,e)).session.isGenerating){clearInterval(K);const pe=await Or(s.id,{limit:50},e);u(pe.messages.map(ar)),x(""),b(""),N([]),p(!1)}}catch{}},3e3);return()=>clearInterval(K)},[s,A,e]);const S=i.useCallback(async()=>{if(s){h(!0);try{const K=await Or(s.id,{limit:50},e);u(K.messages.map(ar))}catch(K){console.error("[useQuickChat] Failed to reload messages:",K)}finally{h(!1)}}},[s,e]),G=i.useCallback(()=>{P.current?.(),P.current=null,F.current="",E(""),x(""),b(""),N([]),p(!1)},[]),he=i.useCallback(async(K,O,pe)=>{const ve=kl(K,O,pe);if(!ve)return;const B=jl(ve.agentId,ve.modelProvider,ve.modelId);U.current=ve;const we=B===L.current&&C.current;if(we||(y.current&&(y.current.close(),y.current=null),G()),we){await S();return}a(null),u([]),L.current=B,await I(ve.agentId,ve.modelProvider,ve.modelId)},[I,S,G]),Se=i.useCallback(async K=>{const O=kl(K.agentId,K.modelProvider??void 0,K.modelId??void 0);O&&(U.current=O,L.current=jl(O.agentId,O.modelProvider,O.modelId),y.current&&(y.current.close(),y.current=null),G(),a(K),K.isGenerating&&(x(""),A(K.id)))},[A,G]),Ue=i.useCallback(async(K,O)=>{await he(dr,K,O)},[he]),ce=i.useCallback(async(K,O,pe)=>{const B=kl(K??"",O,pe)??U.current;if(!B)return;U.current=B;const we=jl(B.agentId,B.modelProvider,B.modelId);Y.current=!0,$.current=0,y.current&&(y.current.close(),y.current=null),G(),u([]),a(null),c(!0);try{const ze=await q(B);a(ze),L.current=we;const re=await Km(e);o(re.sessions)}catch(ze){console.error("[useQuickChat] Failed to start a fresh session:",ze),n?.("Failed to start a new chat","error")}finally{Y.current=!1,c(!1)}},[n,q,e,G]),Ae=i.useCallback(()=>{s&&(j.current=!0,P.current?.(),P.current=null,y.current?.close(),y.current=null,y0(s.id,e).catch(()=>{}),p(!1),x(""),b(""),N([]))},[s,e]),X=i.useCallback(()=>{F.current="",E("")},[]),Z=i.useRef(()=>Promise.resolve()),ee=yO(),le=i.useCallback((K,O)=>{if(!s||!K.trim()&&(!O||O.length===0))return Promise.resolve();if(_.current)return O&&O.length>0?Promise.reject(new Error("Cannot send attachments while a response is streaming")):(F.current=K,E(K),n?.("Still waiting for previous response — message queued","warning"),Promise.resolve());const pe=new Promise((ve,B)=>{R.current={resolve:ve,reject:B},j.current=!1,y.current&&(y.current.close(),y.current=null);const we=`temp-${Date.now()}`,ze={id:we,sessionId:s.id,role:"user",content:K,createdAt:new Date().toISOString()};u(He=>[...He,ze]),x(""),b(""),N([]),p(!0);const{handlers:re}=ng({sessionId:s.id,tempUserMessageId:we,setStreamingText:x,setStreamingThinking:b,setStreamingToolCalls:N,cancelStreamingFlushesRef:P,addToast:n,onFallbackSession:(He,Pe)=>{const tt=sg(He.fallbackModel);o(qe=>qe.map(de=>de.id===Pe?{...de,...tt}:de)),a(qe=>qe&&qe.id===Pe?{...qe,...tt}:qe)},onDone:({messageId:He,message:Pe,accumulated:tt})=>{const qe=Pe?ar(Pe):{id:He||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:tt.text,thinkingOutput:tt.thinking||void 0,toolCalls:tt.toolCalls.length>0?tt.toolCalls:void 0,fallbackInfo:tt.fallbackInfo,createdAt:new Date().toISOString()};u(De=>[...De,qe]),x(""),b(""),N([]),p(!1),_.current=!1,y.current=null,R.current?.resolve(),R.current=null;const de=F.current.trim();de&&(F.current="",E(""),Z.current(de))},onError:He=>{x(""),b(""),N([]),p(!1),_.current=!1,y.current=null,console.error("[useQuickChat] Stream error:",He);const Pe=typeof He=="string"&&He.trim()?He:"Failed to get response";if(typeof He=="string"&&vO(He)&&(ee.isHiddenNow()||ee.wasRecentlyHidden(5e3))?(console.info("[useQuickChat] Suppressed tab-suspension stream error:",He),R.current?.resolve()):(n?.(Pe,"error"),R.current?.reject(new Error(Pe))),R.current=null,!j.current){const qe=F.current.trim();qe&&(F.current="",E(""),Z.current(qe))}S()}});y.current=w0(s.id,K,re,O,e)});return pe.catch(()=>{}),pe},[s,e,n,S,ee]);return Z.current=le,i.useEffect(()=>()=>{y.current&&(y.current.close(),y.current=null)},[]),i.useMemo(()=>({activeSession:s,sessions:r,sessionsLoading:l,messages:d,messagesLoading:m,isStreaming:f,streamingText:g,streamingThinking:w,streamingToolCalls:v,pendingMessage:k,sendMessage:le,stopStreaming:Ae,clearPendingMessage:X,switchSession:he,selectSession:Se,startModelChat:Ue,startFreshSession:ce,refreshSessions:ne,loadMessages:D,reloadMessages:S,skipNextSessionInitRef:Y}),[s,r,l,d,m,f,g,w,v,k,le,Ae,X,he,Se,Ue,ce,ne,D,S])}function NO(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 Mr({...x,...p,includeEphemeral:p?.includeEphemeral??w},e),v=Array.from(new Map(b.map(N=>[N.id,N])).values());a(v)}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 LS(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 li(`/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||!fC(p));return{agents:s,activeAgents:f,stats:r,isLoading:l,loadAgents:d,loadStats:u,refreshAgents:m}}function SO({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=Y0(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(Lg,{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 CO=200;function EO(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((y,j)=>{if(j<0||j>y.length){r(!1);return}const P=F=>/[a-zA-Z0-9/_.-]/.test(F);for(let F=j-1;F>=0;F--){if(y[F]==="#")if(F===0){const _=y.slice(F+1,j);d(F),l(_),g(0),r(!0);return}else{const _=y[F-1];if(/[\s,.;:!?'"()[\]{}]/.test(_)){const R=y.slice(F+1,j);d(F),l(R),g(0),r(!0);return}r(!1);return}if(!P(y[F])){r(!1);return}}r(!1)},[]),v=i.useCallback(()=>{r(!1),l(""),d(-1),m([]),g(0),f(!1)},[]),N=i.useCallback(async y=>{if(!y.trim()){m([]),f(!1);return}w.current?.abort(),w.current=new AbortController;try{f(!0);const j=await UN(y,s,n);m(j.files),g(0)}catch(j){j.name!=="AbortError"&&m([])}finally{f(!1)}},[s,n]);i.useEffect(()=>{if(a)return x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{N(o)},CO),()=>{x.current&&clearTimeout(x.current)}},[o,a,N]);const k=i.useCallback((y,j)=>{if(!a||c<0)return j;const P=j.slice(0,c),F=j.slice(c+1),_=F.match(/[\s]|$/),R=_?_.index:F.length,L=F.slice(R);return`${P}#${y.path}${L}`},[a,c]),E=i.useCallback((y,j)=>{if(!a||u.length===0)return!1;switch(y.key){case"ArrowDown":return y.preventDefault(),g(P=>Math.min(P+1,u.length-1)),!0;case"ArrowUp":return y.preventDefault(),g(P=>Math.max(P-1,0)),!0;case"Enter":case"Tab":return u[p]?(y.preventDefault(),!0):!1;case"Escape":return y.preventDefault(),v(),!0;default:return!1}},[a,u,p,v]);return{mentionActive:a,files:u,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:g,detectMention:b,selectFile:k,dismissMention:v,handleKeyDown:E}}function _O(e){return`${e.name?.trim()||e.id} (${e.role})`}function Xr(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 MO(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 _l(e,n){return e.length<=n?e:`${e.slice(0,n)}…`}function AO(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}=${_l(r,50)}`}).join(", ")}function RO(e){if(e===void 0)return null;if(typeof e=="string")return _l(e,200);try{return _l(JSON.stringify(e),200)}catch{return _l(String(e),200)}}function _v(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=AO(f.args),b=RO(f.result),v=g?w:b?`result: ${b}`:w?`args: ${w}`:null,N=n?null:v,k=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}),N&&t.jsx("span",{className:"chat-tool-call-preview",title:N,children:N}),t.jsx("span",{className:"chat-tool-call-status-text",children:k})]}),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(ym,{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(ym,{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 Mv={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 ig(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 PO(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 Nl={width:320,height:400},IO=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"]),TO=[".png",".jpg",".jpeg",".gif",".webp",".txt",".json",".yaml",".yml",".log",".csv",".xml",".md"];function $O(e){return e.type.startsWith("image/")}function DO(e){if(IO.has(e.type))return!0;const n=e.name.toLowerCase();return TO.some(s=>n.endsWith(s))}const rr={width:280,height:260},Rs=768,or=8;function LO(e,n){const s=i.useCallback(()=>{if(typeof window>"u")return 0;const k=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return k&&parseFloat(k)||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 k=`fusion-quick-chat-position-${e||"default"}`;try{const E=localStorage.getItem(k);if(E){const y=JSON.parse(E);if(typeof y.x=="number"&&typeof y.y=="number"&&!isNaN(y.x)&&!isNaN(y.y))return y}}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(k=>{if(typeof window>"u")return k;const E=48,y=window.innerWidth<=768?4:8,j=window.innerWidth<=768?44:0,P=window.innerWidth>768?s():0,F=window.innerWidth-E-y,_=window.innerHeight-E-y-j-P;return{x:Math.max(y,Math.min(F,k.x)),y:Math.max(y,Math.min(_,k.y))}},[s]),g=i.useCallback(k=>{if(typeof window>"u")return;const E=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(E,JSON.stringify(k))}catch{}},[e]),x=i.useCallback(()=>{if(!d.current)return;const k=h.current,E=m.current;k&&E!==null&&typeof k.releasePointerCapture=="function"&&k.releasePointerCapture(E),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",v)},[g]),w=i.useCallback(k=>{if(!d.current||m.current!==null&&k.pointerId!==m.current)return;const E=k.clientX-d.current.pointerX,y=k.clientY-d.current.pointerY;if((Math.abs(E)>=5||Math.abs(y)>=5)&&(f.current=!0),!f.current)return;const j=d.current.x-E,P=d.current.y-y,F=p({x:j,y:P});u.current=F,o(F)},[p]),b=i.useCallback(k=>{m.current!==null&&k.pointerId!==m.current||x()},[x]),v=i.useCallback(k=>{m.current!==null&&k.pointerId!==m.current||x()},[x]),N=i.useCallback(k=>{if(k.button!==0&&k.pointerType==="mouse")return;const E=k.currentTarget;k.preventDefault(),typeof E.setPointerCapture=="function"&&E.setPointerCapture(k.pointerId);const y=u.current;d.current={x:y.x,y:y.y,pointerX:k.clientX,pointerY:k.clientY},m.current=k.pointerId,h.current=E,f.current=!1,c(!0),document.body.style.userSelect="none",document.addEventListener("pointermove",w,{passive:!0}),document.addEventListener("pointerup",b),document.addEventListener("pointercancel",v)},[v,w,b]);return i.useEffect(()=>()=>{document.removeEventListener("pointermove",w),document.removeEventListener("pointerup",b),document.removeEventListener("pointercancel",v),document.body.style.userSelect=""},[v,w,b]),{position:r,isDragging:l,handlePointerDown:N}}function OO(e,n,s){const a=`fusion:quick-chat-size-${e||"default"}`,r=i.useCallback(()=>typeof window<"u"&&window.innerWidth>Rs,[]),o=i.useCallback((f,p,g)=>{if(typeof window>"u")return f;const x=Math.max(rr.width,window.innerWidth-p-or),w=Math.max(rr.height,window.innerHeight-g-or);return{width:Math.max(rr.width,Math.min(x,f.width)),height:Math.max(rr.height,Math.min(w,f.height))}},[]),l=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=Rs)return Nl;try{const f=localStorage.getItem(a);if(!f)return Nl;const p=JSON.parse(f);return typeof p.width!="number"||typeof p.height!="number"?Nl:{width:p.width,height:p.height}}catch{return Nl}},[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=v=>{const N=v.clientX-x.pointerX,k=v.clientY-x.pointerY;let E=x.width,y=x.height,j=x.anchorRight,P=x.anchorBottom;if(p.includes("w")&&(E=x.width-N),p.includes("e")){const C=N;E=x.width+C,j=x.anchorRight-C}if(p.includes("n")&&(y=x.height-k),p.includes("s")){const C=k;y=x.height+C,P=x.anchorBottom-C}const F=n+j,_=s+P,R=o({width:E,height:y},F,_),L=Math.max(or-n,Math.min(window.innerWidth-n-rr.width-or,j)),U=Math.max(or-s,Math.min(window.innerHeight-s-rr.height-or,P));d(R),m({right:L,bottom:U})},b=v=>{typeof g.releasePointerCapture=="function"&&g.releasePointerCapture(v.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 ag=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(),v=a.get(b);if(v){const N=!!(r&&!r.memberIds.has(v.id)),k=N?`Not a member of ${r?.roomName}`:void 0;h.push(t.jsxs("span",{className:`chat-mention-chip${N?" chat-mention-chip--non-member":""}`,title:k,"aria-label":k,children:["@",v.name.replace(/\s+/g,"_")]},`${v.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(wi,{remarkPlugins:[ki],components:Mv,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(Su,{size:14}):t.jsx(Er,{size:14})})]}),_v(n.toolCalls,!0)]})});function zO({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}=NO(e),[h,f]=i.useState(!1),p=a!==void 0,g=p?a:h,x=p?z=>{r?.(typeof z=="function"?z(g):z)}:f;Yi({enabled:g});const w=Zs(),[b,v]=i.useState("agent"),[N,k]=i.useState(""),[E,y]=i.useState(!1),[j,P]=i.useState("model"),[F,_]=i.useState(""),[R,L]=i.useState(""),[U,C]=i.useState([]),[$,V]=i.useState(!1),[Y,ne]=i.useState(""),[q,A]=i.useState(""),[I,D]=i.useState(""),[S,G]=i.useState([]),[he,Se]=i.useState(!1),[Ue,ce]=i.useState(!1),[Ae,X]=i.useState(""),[Z,ee]=i.useState(0),[le,K]=i.useState(""),[O,pe]=i.useState(!1),[ve,B]=i.useState(0),[we,ze]=i.useState(-1),[re,He]=i.useState(()=>new Set),[Pe,tt]=i.useState(!1),[qe,de]=i.useState([]),[De,Te]=i.useState(!1),[ct,Ve]=i.useState(!1),[,me]=i.useState(!1),[oe,Me]=i.useState({top:0,left:0}),Xe=EO({projectId:e}),rt=i.useCallback(z=>{if(!z||!Xe.mentionActive)return;const ge=z.getBoundingClientRect();Me({top:ge.top-260,left:ge.left+8})},[Xe.mentionActive]),ht=i.useRef(!1),yt=i.useRef(!1),Re=i.useRef(""),Ge=i.useRef(0),at=i.useRef(null),ie=i.useRef(null),Ke=i.useRef(0),{position:je,isDragging:Fe,handlePointerDown:Be}=LO(e,ht),St=je.y+60,{panelSize:ye,anchorOffset:kt,handleResizeStart:It}=OO(e,je.x,St),Ie=typeof window<"u"&&window.innerWidth>Rs,{activeSession:be,messages:ot,isStreaming:gt,streamingText:xt,streamingThinking:jt,streamingToolCalls:Bt,sessions:Jt,sessionsLoading:Vt,messagesLoading:pn,sendMessage:Xt,stopStreaming:mn,pendingMessage:Ht,clearPendingMessage:Zt,switchSession:tn,selectSession:dn,startModelChat:qt,startFreshSession:ke,refreshSessions:$e,skipNextSessionInitRef:Ye}=jO(e,n),ut=i.useRef(null),We=i.useRef(null),$t=i.useRef(null),At=i.useRef(null),wt=i.useRef(null),zt=i.useRef([]),Lt=i.useRef(!1),Ot=i.useRef(!1),nn=i.useRef(!1),Yt=i.useRef(null),rn=i.useRef(!1),_e=i.useRef(!1),it=i.useRef({isOpen:!1,sessionId:null});i.useEffect(()=>{if(!g||typeof window>"u"||typeof document>"u"||window.innerWidth>Rs)return;const z=window.scrollY,ge=document.documentElement,xe=document.body,dt={htmlOverflow:ge.style.overflow,bodyOverflow:xe.style.overflow};return window.scrollTo(0,0),ge.style.overflow="hidden",xe.style.overflow="hidden",()=>{ge.style.overflow=dt.htmlOverflow,xe.style.overflow=dt.bodyOverflow,window.scrollTo(0,z)}},[g]),i.useLayoutEffect(()=>{if(!g||typeof window>"u"||!window.visualViewport)return;const z=ut.current;if(!z)return;const ge=window.visualViewport,xe=()=>{rn.current||(z.style.setProperty("--vv-height",`${ge.height}px`),z.style.setProperty("--vv-offset-top",`${ge.offsetTop||0}px`))};return xe(),ge.addEventListener("resize",xe),ge.addEventListener("scroll",xe),()=>{ge.removeEventListener("resize",xe),ge.removeEventListener("scroll",xe)}},[g]);const bt=Y||q,Rt=i.useMemo(()=>Xr(bt),[bt]),se=i.useMemo(()=>b==="model"&&be?.modelProvider&&be?.modelId?`${be.modelProvider}/${be.modelId}`:bt,[be?.modelId,be?.modelProvider,b,bt]),te=i.useMemo(()=>Xr(se),[se]),Oe=i.useMemo(()=>U.find(z=>`${z.provider}/${z.id}`===se)??null,[se,U]),mt=i.useMemo(()=>MO(Oe,te),[Oe,te]),Pt=i.useMemo(()=>b==="model"?Rt?`${dr}::${Rt.modelProvider}/${Rt.modelId}`:"":N?`${N}::`:"",[b,N,Rt]),In=!(b==="agent"?!!N:!!Rt)||!be;i.useEffect(()=>{if(m.length===0){k(""),v("model");return}m.some(ge=>ge.id===N)||k(m[0]?.id??"")},[m,N]),i.useEffect(()=>{!g||yt.current||(yt.current=!0,V(!0),Fs().then(z=>{const ge=z.models??[];if(C(ge),Y||ge.length===0)return;const xe=z.defaultProvider,dt=z.defaultModelId;if(xe&&dt){const Wt=`${xe}/${dt}`;if(ge.some(Mn=>`${Mn.provider}/${Mn.id}`===Wt)){A(Wt),ne(Wt),v("model");return}}A("");const Tt=ge[0];Tt&&ne(`${Tt.provider}/${Tt.id}`)}).catch(z=>{console.error("[QuickChatFAB] Failed to load models:",z),C([]),A("")}).finally(()=>{V(!1)}))},[g,m.length,Y]),i.useEffect(()=>{!g||!e||(Se(!0),g0(e).then(z=>{G(z)}).catch(()=>{G([])}).finally(()=>{Se(!1)}))},[g,e]),i.useEffect(()=>{g&&$e()},[g,$e]),i.useEffect(()=>{if(!g){Re.current="";return}if(!Pt){Re.current="";return}if(Ye.current){Re.current=Pt;return}const z=Pt===Re.current&&!be&&!Vt;if(!(Pt===Re.current&&!z)){if(Re.current=Pt,b==="model"&&Rt){qt(Rt.modelProvider,Rt.modelId);return}b==="agent"&&N&&tn(N)}},[g,b,Rt,N,Pt,be,Vt,qt,tn,Ye]),i.useEffect(()=>{g||(pe(!1),K(""),ze(-1),ce(!1),X(""),ee(0),zt.current.forEach(z=>{z.previewUrl&&URL.revokeObjectURL(z.previewUrl)}),de([]))},[g]),i.useEffect(()=>{zt.current=qe},[qe]),i.useEffect(()=>{if(!g){Lt.current=!1;return}typeof window>"u"||(Lt.current=window.innerWidth<=Rs)},[g]),i.useEffect(()=>{if(!g||In||!Lt.current)return;const z=At.current;if(!z)return;const ge=document.activeElement,xe=ge?ut.current?.contains(ge):!1,dt=ge===document.body,Tt=ge===Yt.current;if(!xe&&!dt&&!Tt){Lt.current=!1;return}if(Tt){z.focus({preventScroll:!0}),Lt.current=!1;return}const Wt=requestAnimationFrame(()=>{z.focus(),Lt.current=!1});return()=>cancelAnimationFrame(Wt)},[g,In]),i.useEffect(()=>()=>{zt.current.forEach(z=>{z.previewUrl&&URL.revokeObjectURL(z.previewUrl)})},[]);const fe=i.useCallback(()=>{y(!0),P("model"),_(m[0]?.id??""),L(Y||q||"")},[m,q,Y]),ft=i.useMemo(()=>m.find(z=>z.id===N)??null,[m,N]),lt=i.useMemo(()=>{const z=Ae.trim().toLowerCase();return(z?S.filter(xe=>xe.name.toLowerCase().includes(z)):S).slice(0,10)},[S,Ae]),vt=i.useMemo(()=>{const z=m.filter(dt=>Cv(dt.name,le));if(!u)return z;const ge=z.filter(dt=>u.memberIds.has(dt.id));if(le.trim().length===0)return ge;const xe=z.filter(dt=>!u.memberIds.has(dt.id));return[...ge,...xe]},[m,le,u]),et=i.useMemo(()=>{const z=new Map;for(const ge of m)z.set(ge.name.toLowerCase(),ge);return z},[m]);i.useEffect(()=>{ee(0)},[lt]),i.useEffect(()=>{B(0)},[le,O]),i.useEffect(()=>()=>{at.current!==null&&(window.clearTimeout(at.current),at.current=null),ie.current!==null&&(window.clearTimeout(ie.current),ie.current=null)},[]),i.useEffect(()=>{if(!g)return;const z=xe=>{const dt=xe.target;ut.current?.contains(dt)||We.current?.contains(dt)||dt.closest(".model-combobox-dropdown--portal")||x(!1)},ge=xe=>{xe.key==="Escape"&&x(!1)};return document.addEventListener("mousedown",z),document.addEventListener("keydown",ge),()=>{document.removeEventListener("mousedown",z),document.removeEventListener("keydown",ge)}},[g,x]);const _t=i.useCallback(()=>{const z=$t.current;if(!z)return;const xe=z.scrollTop+z.clientHeight>=z.scrollHeight-50;Ve(!xe),_e.current=!xe},[]),Gt=i.useCallback(z=>{if(!z.isConnected)return;let ge=0,xe=0,dt=-1;const Tt=6,Wt=()=>{if(z.isConnected){if(z.scrollTop=z.scrollHeight,z.scrollHeight===dt?xe+=1:(xe=0,dt=z.scrollHeight),ge+=1,ge>=Tt||xe>=2){Ve(!1),_e.current=!1;return}window.requestAnimationFrame(Wt)}};Wt()},[]),ae=i.useCallback(()=>{const z=$t.current;z&&Gt(z)},[Gt]);i.useLayoutEffect(()=>{const z=be?.id??null,ge=it.current;if(it.current={isOpen:g,sessionId:z},!g||!z)return;const xe=!ge.isOpen&&g,dt=ge.isOpen&&ge.sessionId!==z;if(!xe&&!dt)return;const Tt=$t.current;Tt&&Gt(Tt)},[g,be?.id,Gt]),i.useEffect(()=>{g&&(_e.current||ae())},[ot,xt,jt,gt,g,ae]);const pt=i.useMemo(()=>{const z=new Map(m.map(xe=>[xe.id,xe.name?.trim()||xe.id])),ge=new Map(U.map(xe=>[`${xe.provider}/${xe.id}`,xe.name?.trim()||""]));return Jt.map((xe,dt)=>{const Tt=xe.title?.trim()||`Session ${dt+1}`;let Wt=null;if(xe.agentId&&xe.agentId!==dr)Wt=z.get(xe.agentId)||xe.agentId;else if(xe.modelProvider&&xe.modelId){const bn=`${xe.modelProvider}/${xe.modelId}`,Mn=ge.get(bn);Wt=Mn?`${Mn} [${bn}]`:bn}return{id:xe.id,label:Wt?`${Tt} — ${Wt}`:Tt}})},[m,U,Jt]),gn=i.useMemo(()=>b==="agent"?ft?`Message ${ft.name||ft.id}`:"Select an agent to start chatting":mt?`Message ${mt}`:"Select a model to start chatting",[b,ft,mt]),us=i.useCallback(z=>{const ge=Jt.find(xe=>xe.id===z);ge&&(ge.modelProvider&&ge.modelId?(v("model"),ne(`${ge.modelProvider}/${ge.modelId}`)):(v("agent"),k(ge.agentId)),dn(ge))},[dn,Jt]),Kn=i.useCallback(async()=>{if(!Vt){if(j==="agent"){if(!F)return;v("agent"),k(F),await ke(F)}else{const z=Xr(R||Y||q);if(!z)return;v("model"),ne(`${z.modelProvider}/${z.modelId}`),await ke(dr,z.modelProvider,z.modelId)}await $e(),y(!1),P("model")}},[q,F,j,R,$e,Y,Vt,ke]),_n=Ht.length>50?`${Ht.slice(0,50)}…`:Ht,$n=i.useCallback(z=>{if(!z||z.length===0)return;const ge=[];for(let xe=0;xe<z.length;xe+=1){const dt=z[xe];DO(dt)&&ge.push({file:dt,previewUrl:$O(dt)?URL.createObjectURL(dt):""})}ge.length>0&&de(xe=>[...xe,...ge])},[]),hn=i.useCallback(z=>{de(ge=>{const xe=ge[z];return xe?.previewUrl&&URL.revokeObjectURL(xe.previewUrl),ge.filter((dt,Tt)=>Tt!==z)})},[]),Ut=i.useCallback(z=>{$n(z.clipboardData?.files)},[$n]),Dn=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth>Rs)return;const z=At.current;!z||z.disabled||z.focus({preventScroll:!0})},[]),as=i.useCallback(()=>{typeof window>"u"||window.innerWidth>Rs||(nn.current=!0)},[]),Rn=i.useCallback(async()=>{const z=I.trim(),ge=zt.current;if(!(!z&&ge.length===0)&&!In){if(D(""),pe(!1),K(""),ze(-1),z==="/help"){tt(!0),Dn(),nn.current=!1;return}if(z==="/clear"){mn(),Zt(),ge.forEach(xe=>{xe.previewUrl&&URL.revokeObjectURL(xe.previewUrl)}),de(xe=>xe.filter(dt=>!ge.includes(dt)));try{if(b==="model"){const xe=Xr(bt);if(!xe)return;await ke(dr,xe.modelProvider,xe.modelId)}else N&&await ke(N)}catch{n("Failed to clear conversation","error")}finally{Dn(),nn.current=!1}return}try{tt(!1),await Xt(z,ge.map(xe=>xe.file)),ge.forEach(xe=>{xe.previewUrl&&URL.revokeObjectURL(xe.previewUrl)}),de(xe=>xe.filter(dt=>!ge.includes(dt)))}catch{}finally{Dn(),nn.current=!1}}},[n,b,Zt,Dn,In,I,bt,N,Xt,ke,mn]),ms=i.useCallback(z=>{z.preventDefault(),Ke.current+=1,Te(!0)},[]),Xn=i.useCallback(z=>{z.preventDefault(),z.dataTransfer.dropEffect="copy",Te(!0)},[]),vs=i.useCallback(z=>{z.preventDefault(),Ke.current=Math.max(0,Ke.current-1),Ke.current===0&&Te(!1)},[]),Gn=i.useCallback(z=>{z.preventDefault(),Ke.current=0,Te(!1),$n(z.dataTransfer?.files)},[$n]),hs=i.useCallback((z,ge)=>{const xe=PO(z,ge);if(xe){pe(!0),K(xe.filter),ze(xe.start);return}pe(!1),K(""),ze(-1)},[]),Ln=i.useCallback(z=>{D(ge=>{const xe=ig(ge);if(!xe)return ge;const dt=`/skill:${z.name} `,Tt=ge.slice(0,xe.start)+dt+ge.slice(xe.end);return window.requestAnimationFrame(()=>{At.current&&At.current.focus()}),Tt}),ce(!1),X(""),ee(0)},[]),En=i.useCallback(z=>{const ge=At.current;if(!ge||we<0)return;const xe=ge.selectionStart??Ge.current,dt=ge.selectionEnd??xe,Tt=Math.max(xe,dt),Wt=Math.min(we,Tt),Mn=`${`@${z.name.replace(/\s+/g,"_")}`} `,Zn=I.slice(0,Wt)+Mn+I.slice(Tt),On=Wt+Mn.length;D(Zn),pe(!1),K(""),B(0),ze(-1),window.requestAnimationFrame(()=>{At.current&&(At.current.focus(),At.current.setSelectionRange(On,On))})},[we,I]),ps=i.useCallback(z=>{const ge=z.target.value,xe=z.target.selectionStart??ge.length;Ge.current=xe,D(ge),Pe&&ge.trim().length>0&&tt(!1),hs(ge,xe);const dt=ig(ge);dt?(ce(!0),X(dt.filter)):(ce(!1),X("")),Xe.detectMention(ge,xe),me(Xe.mentionActive),Xe.mentionActive&&rt(z.target)},[Pe,hs,Xe,rt]),Nn=i.useCallback(()=>{if(nn.current){window.requestAnimationFrame(()=>{Dn()});return}typeof window<"u"&&window.innerWidth<=Rs&&ut.current&&(rn.current=!0,ut.current.style.removeProperty("--vv-height"),ut.current.style.removeProperty("--vv-offset-top"),window.setTimeout(()=>{rn.current=!1},450)),at.current!==null&&window.clearTimeout(at.current),at.current=window.setTimeout(()=>{pe(!1),K(""),ze(-1),me(!1),Xe.dismissMention(),at.current=null},120),ie.current!==null&&window.clearTimeout(ie.current),ie.current=window.setTimeout(()=>{ce(!1),ie.current=null},120)},[Xe,Dn]),As=i.useCallback(()=>{rn.current=!1,at.current!==null&&(window.clearTimeout(at.current),at.current=null),ie.current!==null&&(window.clearTimeout(ie.current),ie.current=null)},[]),Cs=i.useCallback(z=>{const ge=z.currentTarget,xe=ge.selectionStart??ge.value.length;Ge.current=xe,hs(ge.value,xe),Xe.detectMention(ge.value,xe),me(Xe.mentionActive),Xe.mentionActive&&rt(ge)},[hs,Xe,rt]),Es=i.useCallback(z=>{z.key!=="Escape"&&Cs(z)},[Cs]),Q=i.useCallback(z=>{He(ge=>{const xe=new Set(ge);return xe.has(z)?xe.delete(z):xe.add(z),xe})},[]),M=i.useCallback((z,ge=!1)=>ge?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:z}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(wi,{remarkPlugins:[ki],components:Mv,children:z})}),[]),ue=i.useCallback(z=>{if(Ge.current=z.currentTarget.selectionStart??Ge.current,Xe.mentionActive&&Xe.files.length>0){if(Xe.handleKeyDown(z,I),z.key==="Enter"||z.key==="Tab"){const ge=Xe.files[Xe.selectedIndex];if(ge){const xe=Xe.selectFile(ge,I);D(xe),Xe.dismissMention(),me(!1)}}return}if(O&&z.key==="ArrowDown"){z.preventDefault(),vt.length>0&&B(ge=>(ge+1)%vt.length);return}if(O&&z.key==="ArrowUp"){z.preventDefault(),vt.length>0&&B(ge=>ge===0?vt.length-1:ge-1);return}if(O&&z.key==="Enter"){z.preventDefault();const ge=vt[ve]??vt[0];ge&&En(ge);return}if(O&&z.key==="Escape"){z.preventDefault(),z.stopPropagation(),pe(!1),K(""),ze(-1);return}if(Ue&&lt.length>0&&z.key==="ArrowDown"){z.preventDefault(),ee(ge=>(ge+1)%lt.length);return}if(Ue&&lt.length>0&&z.key==="ArrowUp"){z.preventDefault(),ee(ge=>ge===0?lt.length-1:ge-1);return}if(Ue&&(z.key==="Enter"||z.key==="Tab")){z.preventDefault();const ge=lt[Z]??lt[0];ge&&Ln(ge);return}if(Ue&&z.key==="Escape"){z.preventDefault(),ce(!1),X("");return}z.key!=="Enter"||z.shiftKey||(z.preventDefault(),Rn())},[O,vt,ve,En,Rn,Xe,I,Ue,lt,Z,Ln]),Ee=i.useCallback(()=>{if(ht.current){ht.current=!1;return}if(g){x(!1);return}typeof window<"u"&&window.innerWidth<=Rs&&Yt.current?.focus({preventScroll:!0}),x(!0)},[g,x]);return t.jsxs(t.Fragment,{children:[t.jsx("input",{ref:Yt,type:"text",className:"quick-chat-stealth-input","aria-hidden":"true",tabIndex:-1}),s&&t.jsx("button",{ref:We,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":Fe?"true":"false",style:{right:je.x,bottom:je.y},onPointerDown:Be,onClick:Ee,children:t.jsx(qi,{size:24})}),g&&t.jsxs("div",{className:"quick-chat-panel",ref:ut,"data-testid":"quick-chat-panel",style:{...Ie?{right:je.x+kt.right,bottom:St+kt.bottom,width:ye.width,height:ye.height}:{}},children:[Ie&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:It,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:It,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:It,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:It,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:It,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:It,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:It,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:It,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"}),b==="model"&&mt&&(()=>{const z=Oe?.provider??te?.modelProvider??"";return w==="mobile"&&mt.length>12&&z?t.jsx("span",{className:"quick-chat-model-tag quick-chat-model-tag--icon","data-testid":"quick-chat-model-tag",title:mt,"aria-label":mt,children:t.jsx(Tn,{provider:z,size:"sm"})}):t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:mt,children:mt})})()]}),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:fe,disabled:Vt,children:t.jsx(Cn,{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(an,{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:be?.id??"",onChange:z=>us(z.target.value),"data-testid":"quick-chat-session-dropdown",children:[t.jsx("option",{value:"",disabled:!0,children:Vt?"Loading sessions…":"Select a session"}),pt.map(z=>t.jsx("option",{value:z.id,children:z.label},z.id))]})]}),E&&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${j==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-model",onClick:()=>P("model"),children:"Model"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${j==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-agent",onClick:()=>P("agent"),children:"Agent"})]}),j==="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:F,onChange:z=>_(z.target.value),"data-testid":"quick-chat-new-agent-select",children:m.map(z=>t.jsx("option",{value:z.id,children:_O(z)},z.id))})]}):t.jsx("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-new-model-select",children:t.jsx(Ns,{id:"quick-chat-new-model-select",models:U,value:R,onChange:L,label:"Select model override",placeholder:$?"Loading models…":"Select a model",disabled:$||U.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:()=>{y(!1),P("model")},children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary","data-testid":"quick-chat-new-session-submit",onClick:()=>void Kn(),disabled:Vt||(j==="agent"?!F:!Xr(R||Y||q)),children:"Create"})]})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:$t,"data-testid":"quick-chat-messages",onScroll:_t,children:Vt?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):gt?t.jsxs(t.Fragment,{children:[ot.map(z=>t.jsx(ag,{message:z,forcePlain:z.role!=="user"&&re.has(z.id),mentionAgentsByName:et,roomContext:u,onToggleRender:Q},z.id)),Pe&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:M("Available commands:\n- `/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:[xt?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:M(xt,re.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${re.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":re.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>Q("__streaming__"),children:re.has("__streaming__")?t.jsx(Su,{size:14}):t.jsx(Er,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:jt?"Thinking…":"Connecting…"}),_v(Bt,!0),jt&&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:jt})]})]})]}):pn?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):ot.length===0&&!xt&&!jt&&!gt&&!Pe?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[ot.map(z=>t.jsx(ag,{message:z,forcePlain:z.role!=="user"&&re.has(z.id),mentionAgentsByName:et,roomContext:u,onToggleRender:Q},z.id)),Pe&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:M("Available commands:\n- `/clear` — Clear conversation and start fresh\n- `/skill:{name}` — Use a specific skill\n- `/help` — Show this help")})]})}),ct&&t.jsxs("button",{type:"button",className:"btn btn-sm quick-chat-jump-to-latest","data-testid":"quick-chat-jump-to-latest",onClick:ae,children:[t.jsx(un,{size:14}),"Latest"]}),qe.length>0&&t.jsx("div",{className:"quick-chat-attachment-previews","data-testid":"quick-chat-attachment-previews",children:qe.map((z,ge)=>t.jsxs("div",{className:"quick-chat-attachment-preview","data-testid":`quick-chat-attachment-preview-${ge}`,children:[z.previewUrl?t.jsx("img",{src:z.previewUrl,alt:z.file.name}):t.jsx("span",{className:"quick-chat-attachment-preview-name",children:z.file.name}),t.jsx("button",{type:"button",className:"quick-chat-attachment-remove","data-testid":`quick-chat-attachment-remove-${ge}`,"aria-label":`Remove ${z.file.name}`,onClick:()=>hn(ge),children:"×"})]},`${z.file.name}-${ge}`))}),t.jsx("div",{className:"quick-chat-panel-input",children:t.jsxs("div",{className:`quick-chat-input-wrapper${De?" quick-chat-input-wrapper--dragover":""}`,onDragEnter:ms,onDragOver:Xn,onDragLeave:vs,onDrop:Gn,children:[t.jsx("input",{ref:wt,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:z=>{$n(z.target.files),z.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:()=>wt.current?.click(),children:t.jsx(Fg,{size:16})}),t.jsx("input",{ref:At,type:"text",value:I,onChange:ps,onKeyDown:ue,onKeyUp:Es,onClick:Cs,onBlur:Nn,onFocus:As,onPaste:Ut,onTouchStart:z=>{typeof window>"u"||window.innerWidth>Rs||document.activeElement!==z.currentTarget&&(z.preventDefault(),z.currentTarget.focus({preventScroll:!0}))},placeholder:gn,disabled:In,"data-testid":"quick-chat-input"}),gt?t.jsx("button",{type:"button",className:"chat-input-stop quick-chat-send-btn",onPointerDown:z=>{typeof window>"u"||window.innerWidth>Rs||(z.preventDefault(),z.pointerType&&z.pointerType!=="mouse"&&(Ot.current=!0,mn()))},onTouchStart:z=>{typeof window>"u"||window.innerWidth>Rs||(z.preventDefault(),Ot.current=!0,mn())},onMouseDown:z=>{typeof window>"u"||window.innerWidth>Rs||z.preventDefault()},onClick:()=>{if(Ot.current){Ot.current=!1;return}mn()},"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(Mi,{size:14})}):t.jsx("button",{type:"button",className:"quick-chat-send-btn",onPointerDown:z=>{typeof window>"u"||window.innerWidth>Rs||(z.preventDefault(),z.pointerType&&z.pointerType!=="mouse"&&(Ot.current=!0,as(),Dn(),Rn()))},onTouchStart:z=>{typeof window>"u"||window.innerWidth>Rs||(z.preventDefault(),Ot.current=!0,as(),Dn(),Rn())},onMouseDown:z=>{typeof window>"u"||window.innerWidth>Rs||z.preventDefault()},onClick:()=>{if(Ot.current){Ot.current=!1;return}Rn()},disabled:In||I.trim().length===0&&qe.length===0,"data-testid":"quick-chat-send",children:t.jsx(Aa,{size:16})})]}),t.jsx(bO,{agents:m,filter:le,highlightedIndex:ve,visible:O,onSelect:En,position:"above",roomMemberIds:u?.memberIds,roomName:u?.roomName}),t.jsx(SO,{visible:Xe.mentionActive&&!O,position:oe,files:Xe.files,selectedIndex:Xe.selectedIndex,onSelect:z=>{const ge=Xe.selectFile(z,I);D(ge),Xe.dismissMention(),me(!1),At.current?.focus()},loading:Xe.loading}),Ue&&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…"}):lt.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:Ae?"No skills found":"No skills available"}):lt.map((z,ge)=>t.jsxs("button",{type:"button",role:"option","aria-selected":ge===Z,className:`chat-skill-menu-item${ge===Z?" chat-skill-menu-item--highlighted":""}`,onMouseDown:xe=>xe.preventDefault(),onMouseEnter:()=>ee(ge),onClick:()=>Ln(z),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:z.name}),t.jsx("span",{className:"chat-skill-menu-item-description",title:z.relativePath,children:z.relativePath})]},z.id))}),Ht&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${_n}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:Zt,children:"×"})]})]})})]})]})}function Zr(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function rg(e){return e.status==="generating"||e.status==="awaiting_input"}function eo(e){return e==="complete"||e==="error"}function FO(e){const[n,s]=i.useState([]),a=i.useRef(new Map),r=i.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:d}=Ir(),u=i.useCallback(()=>{Ru(e).then(p=>{const g=p.filter(w=>{const b=Zr(w.updatedAt),v=r.current.get(w.id);return v===void 0?!0:b<=v?!1:(r.current.delete(w.id),!0)}),x=new Map;for(const w of g)x.set(w.id,Zr(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,v=a.current.get(w.sessionId)??0;if(b<v)continue;const N=r.current.get(w.sessionId);if(N!==void 0&&b<=N)continue;if(N!==void 0&&b>N&&!eo(w.status)&&r.current.delete(w.sessionId),eo(w.status)){x.delete(w.sessionId)&&(g=!0),a.current.set(w.sessionId,b);continue}const k=x.get(w.sessionId),E=w.type??k?.type,y=w.title??k?.title;if(!k&&(!E||!y))continue;const j={id:w.sessionId,type:E??"planning",status:w.status,title:y??"AI Session",projectId:w.projectId??k?.projectId??e??null,lockedByTab:w.owningTabId??k?.lockedByTab??null,updatedAt:w.updatedAt??k?.updatedAt??new Date(b).toISOString()},P=x.get(w.sessionId);(!P||P.status!==j.status||P.title!==j.title||P.type!==j.type||P.projectId!==j.projectId||P.lockedByTab!==j.lockedByTab||P.updatedAt!==j.updatedAt)&&(x.set(w.sessionId,j),a.current.set(w.sessionId,b),g=!0)}return g?[...x.values()].sort((w,b)=>Zr(b.updatedAt)-Zr(w.updatedAt)):p})},[e,o]),i.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",g=w=>{try{const b=JSON.parse(w.data),v=Zr(b.updatedAt)||Date.now();s(N=>{const k=a.current.get(b.id)??0;if(v<k)return N;const E=r.current.get(b.id);if(E!==void 0&&v<=E)return N;if(E!==void 0&&v>E&&!eo(b.status)&&r.current.delete(b.id),a.current.set(b.id,v),eo(b.status))return N.filter(j=>j.id!==b.id);const y=N.findIndex(j=>j.id===b.id);if(y>=0){const j=[...N];return j[y]=b,j}return rg(b)?[b,...N]:N}),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:v}),eo(b.status)&&c({sessionId:b.id,status:b.status,timestamp:v})}catch{}},x=w=>{try{const b=JSON.parse(w.data),v=Date.now();r.current.set(b,v),a.current.set(b,Math.max(a.current.get(b)??0,v)),c({sessionId:b,status:"complete",timestamp:v}),s(N=>N.filter(k=>k.id!==b))}catch{}};return li(`/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(N=>N.id===p)?.type,w=Ua();let b=!1;if(x==="planning")try{await Yg(p,e,w)}catch(N){b=!0,N instanceof Error&&N.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of planning session ${p} despite lock by another tab`)}else if(x==="subtask")try{await Zg(p,e,w)}catch(N){b=!0,N instanceof Error&&N.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of subtask session ${p} despite lock by another tab`)}else if(x==="mission_interview")try{await ib(p,e,w)}catch(N){b=!0,N instanceof Error&&N.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 v=Date.now();r.current.set(p,v),a.current.set(p,Math.max(a.current.get(p)??0,v)),c({sessionId:p,status:"complete",timestamp:v});try{await ab(p)}catch{}s(N=>N.filter(k=>k.id!==p))},[c,e,n]),h=i.useMemo(()=>n.filter(p=>rg(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 Ql="fusion:hide-session-banners",ku="fusion:session-banner-pref-changed";function BO(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Ql)==="1"}catch{return!1}}function UO(e){if(typeof window>"u")return()=>{};const n=a=>{a.key===Ql&&e()},s=()=>e();return window.addEventListener("storage",n),window.addEventListener(ku,s),()=>{window.removeEventListener("storage",n),window.removeEventListener(ku,s)}}function P5(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(Ql,"1"):window.localStorage.removeItem(Ql),window.dispatchEvent(new Event(ku))}catch{}}function HO(){return i.useSyncExternalStore(UO,BO,()=>!1)}function ks(e){return{...e,column:bb(e.column),dependencies:Array.isArray(e.dependencies)?e.dependencies:[],steps:Array.isArray(e.steps)?e.steps:[],log:Array.isArray(e.log)?e.log:[]}}function og(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function qO(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 $d(e,n){if(og(n.updatedAt,e.updatedAt)<0)return e;if(e.column===n.column)return qO(e,n);const a=og(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 VO(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,v=i.useCallback(async ne=>{const q=++m.current,A=n,I=ne?.searchQueryOverride??f.current,D=ne?.includeArchivedOverride??d.current;try{const S=await fj(void 0,void 0,A,I,D);if(m.current!==q||n!==A)return;o(S.map(ks)),g.current=Date.now()}catch{if(m.current!==q||n!==A)return;if(ne?.clearOnError){o([]);return}o(S=>S)}},[n]);p.current=v;const N=i.useCallback(async()=>{d.current||(c(!0),d.current=!0,await p.current({includeArchivedOverride:!0}))},[]),k=i.useRef(s);i.useEffect(()=>{if(s===void 0&&k.current===void 0)return;k.current=s;const ne=setTimeout(()=>{v({searchQueryOverride:s})},300);return()=>clearTimeout(ne)},[s]),i.useEffect(()=>{v({clearOnError:!0});const ne=()=>{if(document.visibilityState!=="visible")return;const q=Date.now();q-h.current<b||(h.current=q,v())};return document.addEventListener("visibilitychange",ne),()=>{document.removeEventListener("visibilitychange",ne)}},[v]),i.useEffect(()=>{if(a===!1)return;const ne=x.current,q=n?`?projectId=${encodeURIComponent(n)}`:"",A=()=>x.current!==ne;let I=!0;const D=ce=>{if(A())return;const Ae=ks(JSON.parse(ce.data));if(f.current){p.current({searchQueryOverride:f.current});return}o(X=>{const Z=X.findIndex(O=>O.id===Ae.id);if(Z===-1)return[...X,Ae];const ee=X[Z],le=$d(ee,Ae);if(le===ee)return X;const K=[...X];return K[Z]=le,K}),g.current=Date.now()},S=ce=>{if(A())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:Ae,to:X}=JSON.parse(ce.data),Z=ks(Ae),ee={...Z,column:bb(X,Z.column)};o(le=>{const K=le.findIndex(pe=>pe.id===ee.id);if(K===-1)return[...le,ee];const O=[...le];return O[K]=ee,O}),g.current=Date.now()},G=ce=>{if(A())return;if(f.current){p.current({searchQueryOverride:f.current});return}const Ae=ks(JSON.parse(ce.data));o(X=>{const Z=X.findIndex(O=>O.id===Ae.id);if(Z===-1)return[...X,Ae];const ee=X[Z],le=$d(ee,Ae);if(le===ee)return X;const K=[...X];return K[Z]=le,K}),g.current=Date.now()},he=ce=>{if(A())return;if(f.current){p.current({searchQueryOverride:f.current});return}const Ae=ks(JSON.parse(ce.data));o(X=>X.filter(Z=>Z.id!==Ae.id))},Se=ce=>{if(A())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:Ae}=JSON.parse(ce.data),Z={...ks(Ae),column:"done"};o(ee=>{const le=ee.findIndex(O=>O.id===Z.id);if(le===-1)return[...ee,Z];const K=[...ee];return K[le]=Z,K})},Ue=li(`/api/events${q}`,{events:{"task:created":D,"task:moved":S,"task:updated":G,"task:deleted":he,"task:merged":Se},onReconnect:()=>{I&&(A()||p.current())}});return()=>{I=!1,Ue()}},[n,a]);const E=i.useCallback(async ne=>{const q=ks(await Wg(ne,n));return o(A=>A.some(I=>I.id===q.id)?A:[...A,q]),q},[n]),y=i.useCallback(async(ne,q,A)=>ks(await bj(ne,q,n,A)),[n]),j=i.useCallback(async ne=>ks(await Kg(ne,n)),[n]),P=i.useCallback(async(ne,q)=>ks(await xj(ne,n,q)),[n]),F=i.useCallback(async ne=>vj(ne,n),[n]),_=i.useCallback(async ne=>ks(await yj(ne,n)),[n]),R=i.useCallback(async ne=>ks(await wj(ne,n)),[n]),L=i.useCallback(async ne=>{const q=ks(await kj(ne,n));return o(A=>A.some(I=>I.id===q.id)?A:[...A,q]),q},[n]),U=i.useCallback(async(ne,q)=>{const A=u.current.find(D=>D.id===ne),I=A?{...A,...q,updatedAt:new Date().toISOString()}:void 0;I&&o(D=>D.map(S=>S.id===ne?I:S));try{const D=ks(await qs(ne,q,n));return o(S=>S.map(G=>G.id===ne?D:G)),D}catch(D){throw A&&o(S=>S.map(G=>G.id===ne?A:G)),D}},[n]),C=i.useCallback(async ne=>{const q=ks(await Nj(ne,n));return o(A=>A.map(I=>I.id===ne?q:I)),q},[n]),$=i.useCallback(async ne=>{const q=ks(await Sj(ne,n));return o(A=>A.map(I=>I.id===ne?q:I)),q},[n]),V=i.useCallback(async()=>{const q=(await Cj(n)).map(ks);return o(A=>A.map(I=>q.find(S=>S.id===I.id)||I)),q},[n]),Y=i.useCallback(ne=>{if(ne.length===0)return;if(f.current){p.current({searchQueryOverride:f.current});return}const q=ne.map(ks);o(A=>{let I=A;for(const D of q){const S=I.findIndex(Se=>Se.id===D.id);if(S===-1){I===A&&(I=[...A]),I.push(D);continue}const G=I[S],he=$d(G,D);he!==G&&(I===A&&(I=[...A]),I[S]=he)}return I}),g.current=Date.now()},[]);return{tasks:r,createTask:E,moveTask:y,pauseTask:j,deleteTask:P,mergeTask:F,retryTask:_,resetTask:R,duplicateTask:L,updateTask:U,archiveTask:C,unarchiveTask:$,archiveAllDone:V,loadArchivedTasks:N,includeArchived:l,ingestCreatedTasks:Y,lastFetchTimeMs:g.current}}const WO=5e3,KO=1e3;function GO(e){const s=(BS(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 lg(e){return e.map(n=>({...n,nodeMappings:GO(n)}))}function JO(){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 Fm();n(lg(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 Fm(),b=lg(w),v=Math.round(performance.now()-x);console.log(`[useProjects] initial fetchProjectsAcrossNodes took ${v}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<KO||(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()},WO),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,d]);const u=i.useCallback(async f=>{const p=await JS(f);return n(g=>[...g,p]),p},[]),m=i.useCallback(async(f,p)=>{const g=await n1(f,p);return n(x=>x.map(w=>w.id===f?g:w)),g},[]),h=i.useCallback(async f=>{await tb(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 YO="kb-dashboard-current-project";function QO(e){return e??"local"}function XO(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=QO(s);i.useEffect(()=>{let p=!1;async function g(){try{const x=await Ki();if(p)return;u.current=x.dashboardCurrentProjectIdByNode??{};const w=u.current[m];if(w){const b=e.find(v=>v.id===w);b&&(r(b),c.current=!0)}if(!w)try{const b=localStorage.getItem(YO);if(b){const v=JSON.parse(b);v?.id&&e.some(k=>k.id===v.id)&&(r(v),c.current=!0,u.current={...u.current,[m]:v.id},await Pn({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,Pn({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,Pn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}},[m]),f=i.useCallback(()=>{d.current=!0,r(null);const p={...u.current};delete p[m],u.current=p,Pn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:a,setCurrentProject:h,clearCurrentProject:f,loading:o}}const Av=i.createContext(null);function ZO({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()},[]),Ml.createElement(Av.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function ez(){const e=i.useContext(Av);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const Rv="kb-dashboard-theme-mode",Pv="kb-dashboard-color-theme",Iv="kb-dashboard-font-scale-pct",ju=100,tz=85,nz=125,Tv=[...hC],Nu="theme-data",to="theme-data.css";function sz(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.startsWith("http://")||e.startsWith("https://")?new URL(`/${to}`,e).toString():e.startsWith("file://")?e.endsWith("/")?e.slice(0,-1)+`/${to}`:e.replace(/\/[^/]+$/,`/${to}`):`/${to}`:`/${to}`}const Vs=typeof window<"u",iz=Vs?i.useLayoutEffect:i.useEffect;function $v(e){return e==="dark"||e==="light"||e==="system"}function cg(){if(!Vs)return"dark";try{const e=localStorage.getItem(Rv);if($v(e))return e}catch{}return"dark"}function dg(){if(!Vs)return"default";try{const e=localStorage.getItem(Pv);if(e&&Tv.includes(e))return e}catch{}return"default"}function ug(e){if(Vs)try{localStorage.setItem(Rv,e)}catch{}}function mg(e){if(Vs)try{localStorage.setItem(Pv,e)}catch{}}function No(e){return typeof e!="number"||!Number.isFinite(e)?ju:Math.min(nz,Math.max(tz,Math.round(e)))}function hg(){if(!Vs)return ju;try{const e=Number(localStorage.getItem(Iv));return No(e)}catch{return ju}}function pg(e){if(Vs)try{localStorage.setItem(Iv,String(No(e)))}catch{}}function az(e,n){return e==="system"?n?"dark":"light":e}function rz(e,n,s,a){if(!Vs)return;const r=az(e,a);document.documentElement.setAttribute("data-theme",r),document.documentElement.setAttribute("data-color-theme",n),document.documentElement.style.fontSize=`${No(s)}%`}function fg(){if(!Vs)return;const e=sz(),n=document.getElementById(Nu);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=Nu,document.head.appendChild(s)}function gg(){if(!Vs)return;const e=document.getElementById(Nu);e&&e.remove()}function oz(){const[e,n]=i.useState(()=>cg()),[s,a]=i.useState(()=>dg()),[r,o]=i.useState(()=>hg()),[l,c]=i.useState(!0),[d,u]=i.useState(()=>Vs?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(!Vs||!l)return;let N=!1;return Ki().then(k=>{if(!N&&($v(k.themeMode)&&!p.current&&(m.current!==k.themeMode&&(m.current=k.themeMode,n(k.themeMode)),cg()!==k.themeMode&&ug(k.themeMode)),k.colorTheme&&Tv.includes(k.colorTheme)&&!g.current&&(h.current!==k.colorTheme&&(h.current=k.colorTheme,a(k.colorTheme)),dg()!==k.colorTheme&&mg(k.colorTheme)),!x.current)){const E=No(k.dashboardFontScalePct);f.current!==E&&(f.current=E,o(E)),hg()!==E&&pg(E)}}).catch(k=>{console.warn("[useTheme] Failed to hydrate theme from global settings",k)}).finally(()=>{N||c(!1)}),()=>{N=!0}},[l]),i.useEffect(()=>{if(!Vs)return;const N=window.matchMedia("(prefers-color-scheme: dark)"),k=E=>{u(E.matches)};return N.addEventListener("change",k),()=>N.removeEventListener("change",k)},[]),iz(()=>{rz(e,s,r,d)},[e,s,r,d]),i.useEffect(()=>{!Vs||l||(s!=="default"?fg():gg())},[s,l]);const w=i.useCallback(N=>{p.current=!0,m.current=N,n(N),ug(N),Pn({themeMode:N}).catch(k=>{console.warn("[useTheme] Failed to persist themeMode to global settings",k)})},[]),b=i.useCallback(N=>{g.current=!0,h.current=N,a(N),mg(N),N!=="default"?fg():gg(),Pn({colorTheme:N}).catch(k=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",k)})},[]),v=i.useCallback(N=>{const k=No(N);x.current=!0,f.current=k,o(k),pg(k),Pn({dashboardFontScalePct:k}).catch(E=>{console.warn("[useTheme] Failed to persist dashboardFontScalePct to global settings",E)})},[]);return{themeMode:e,colorTheme:s,dashboardFontScalePct:r,setThemeMode:w,setColorTheme:b,setDashboardFontScalePct:v,isSystemDark:d}}function lz(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),[v,N]=i.useState("definition"),[k,E]=i.useState(null),[y,j]=i.useState(!1),[P,F]=i.useState(void 0),[_,R]=i.useState(!1),[L,U]=i.useState(!1),[C,$]=i.useState(!1),[V,Y]=i.useState(null),[ne,q]=i.useState(!1),[A,I]=i.useState(!1),[D,S]=i.useState(void 0),[G,he]=i.useState(!1),[Se,Ue]=i.useState(!1),[ce,Ae]=i.useState("project"),[X,Z]=i.useState(!1),[ee,le]=i.useState(!1),[K,O]=i.useState(!1),[pe,ve]=i.useState(!1),[B,we]=i.useState(!1),[ze,re]=i.useState(!1),[He,Pe]=i.useState(!1),tt=!!(w||y||s||r||m||A||G||Se||X||ee||K||B||pe||C||ne||_||L||ze||He),qe=i.useCallback(()=>a(!0),[]),de=i.useCallback(()=>a(!1),[]),De=i.useCallback(()=>o(!0),[]),Te=i.useCallback(wt=>{c(wt),o(!0)},[]),ct=i.useCallback(()=>{const wt=n[0];wt&&(u(wt.id),o(!0))},[n]),Ve=i.useCallback(wt=>{u(wt),o(!0)},[]),me=i.useCallback(()=>{o(!1),c(null),u(void 0)},[]),oe=i.useCallback(wt=>{p(wt),h(!0)},[]),Me=i.useCallback(wt=>{x(wt),h(!0)},[]),Xe=i.useCallback(()=>{h(!1),p(null),x(void 0)},[]),rt=i.useCallback((wt,zt="definition",Lt)=>{b(wt),N(zt),E(Lt?.origin??null)},[]),ht=i.useCallback(wt=>{b(wt),N("changes"),E(null)},[]),yt=i.useCallback(wt=>{b(zt=>zt&&{...zt,...wt})},[]),Re=i.useCallback(()=>{b(null),E(null)},[]),Ge=i.useCallback(wt=>{F(wt),j(!0)},[]),at=i.useCallback(()=>{j(!1),F(void 0)},[]),ie=i.useCallback(()=>R(!0),[]),Ke=i.useCallback(()=>R(!1),[]),je=i.useCallback(()=>U(!0),[]),Fe=i.useCallback(()=>U(!1),[]),Be=i.useCallback(wt=>{Y(wt??null),$(!0)},[]),St=i.useCallback(()=>{$(!1),Y(null)},[]),ye=i.useCallback(()=>q(!0),[]),kt=i.useCallback(()=>q(!1),[]),It=i.useCallback(()=>{I(wt=>!wt)},[]),Ie=i.useCallback(()=>{I(!1),S(void 0)},[]),be=i.useCallback(()=>he(!0),[]),ot=i.useCallback(()=>he(!1),[]),gt=i.useCallback(()=>Ue(!0),[]),xt=i.useCallback(()=>Ue(!1),[]),jt=i.useCallback(wt=>{Ae(wt)},[]),Bt=i.useCallback(()=>Z(!0),[]),Jt=i.useCallback(()=>Z(!1),[]),Vt=i.useCallback(()=>le(!0),[]),pn=i.useCallback(()=>le(!1),[]),Xt=i.useCallback(()=>O(!0),[]),mn=i.useCallback(()=>O(!1),[]),Ht=i.useCallback(()=>ve(!0),[]),Zt=i.useCallback(()=>ve(!1),[]),tn=i.useCallback(()=>we(!0),[]),dn=i.useCallback(()=>we(!1),[]),qt=i.useCallback(async(wt,zt)=>{we(!1),S(zt),I(!0)},[]),ke=i.useCallback(()=>re(!0),[]),$e=i.useCallback(()=>re(!1),[]),Ye=i.useCallback(()=>Pe(!0),[]),ut=i.useCallback(()=>Pe(!1),[]),We=i.useCallback((wt,zt)=>{zt(`Created ${wt.id} from planning mode`,"success"),o(!1),c(null)},[]),$t=i.useCallback((wt,zt)=>{const Lt=wt.map(Ot=>Ot.id).join(", ");zt(`Created ${Lt} from planning mode`,"success"),o(!1),c(null)},[]),At=i.useCallback((wt,zt)=>{const Lt=wt.map(Ot=>Ot.id).join(", ");zt(`Created ${Lt} 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:v,detailTaskOrigin:k,settingsOpen:y,settingsInitialSection:P,schedulesOpen:_,githubImportOpen:L,usageOpen:C,usageAnchorRect:V,systemStatsOpen:ne,terminalOpen:A,terminalInitialCommand:D,filesOpen:G,todosOpen:Se,fileBrowserWorkspace:ce,activityLogOpen:X,gitManagerOpen:ee,workflowStepsOpen:K,agentsOpen:pe,scriptsOpen:B,setupWizardOpen:ze,modelOnboardingOpen:He,anyModalOpen:tt,openNewTask:qe,closeNewTask:de,openPlanning:De,openPlanningWithInitialPlan:Te,resumePlanning:ct,openPlanningWithSession:Ve,closePlanning:me,openSubtaskBreakdown:oe,openSubtaskWithSession:Me,closeSubtask:Xe,openDetailTask:rt,openDetailWithChangesTab:ht,updateDetailTask:yt,closeDetailTask:Re,openSettings:Ge,closeSettings:at,openSchedules:ie,closeSchedules:Ke,openGitHubImport:je,closeGitHubImport:Fe,openUsage:Be,closeUsage:St,openSystemStats:ye,closeSystemStats:kt,toggleTerminal:It,closeTerminal:Ie,openFiles:be,closeFiles:ot,openTodos:gt,closeTodos:xt,setFileWorkspace:jt,openActivityLog:Bt,closeActivityLog:Jt,openGitManager:Vt,closeGitManager:pn,openWorkflowSteps:Xt,closeWorkflowSteps:mn,openAgents:Ht,closeAgents:Zt,openScripts:tn,closeScripts:dn,runScript:qt,openSetupWizard:ke,closeSetupWizard:$e,openModelOnboarding:Ye,closeModelOnboarding:ut,onPlanningTaskCreated:We,onPlanningTasksCreated:$t,onSubtaskTasksCreated:At}}function cz(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(!1),[x,w]=i.useState(!1),[b,v]=i.useState(!1),[N,k]=i.useState({}),[E,y]=i.useState(!1),[j,P]=i.useState(!1),[F,_]=i.useState(!1),[R,L]=i.useState(!1),[U,C]=i.useState(!0),$=i.useCallback(async()=>{const[I,D]=await Promise.allSettled([Mj(e),oc(e)]);if(I.status==="fulfilled"&&(s(I.value.maxConcurrent),r(I.value.rootDir)),D.status==="fulfilled"){const S=D.value;l(!!S.autoMerge),d(!!S.globalPause),m(!!S.enginePaused),w(!!S.prAuthAvailable),f(S.taskStuckTimeoutMs),g(S.showQuickChatFAB===!0),k(S.experimentalFeatures??{});const G=S.experimentalFeatures??{};y(G.insights===!0),P(G.memoryView===!0),_(G.devServerView===!0||G.devServer===!0),L(G.todoView===!0);const he=S.autoReloadOnVersionChange!==!1;C(he),Nc(he)}v(!0)},[e]);i.useEffect(()=>{v(!1),k({}),y(!1),P(!1),_(!1),L(!1),$()},[$]);const V=i.useCallback(async()=>{const I=!o;l(I);try{await qo({autoMerge:I},e)}catch{l(!I)}},[o,e]),Y=i.useCallback(async()=>{const I=!c;d(I);try{await qo({globalPause:I,globalPauseReason:I?"manual":void 0},e)}catch{d(!I)}},[c,e]),ne=i.useCallback(async()=>{const I=!u;m(I);try{await qo({enginePaused:I},e)}catch{m(!I)}},[u,e]),q=i.useCallback(async()=>{const I=!p;g(I);try{await qo({showQuickChatFAB:I},e)}catch{g(!I)}},[p,e]),A=i.useCallback(async()=>{const I=!U;C(I),Nc(I);try{await Pn({autoReloadOnVersionChange:I})}catch{C(!I),Nc(!I)}},[U]);return{maxConcurrent:n,rootDir:a,autoMerge:o,globalPaused:c,enginePaused:u,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:x,settingsLoaded:b,experimentalFeatures:N,insightsEnabled:E,memoryEnabled:j,devServerEnabled:F,todosEnabled:R,autoReloadOnVersionChange:U,toggleAutoMerge:V,toggleGlobalPause:Y,toggleEnginePause:ne,toggleShowQuickChatFAB:q,toggleAutoReloadOnVersionChange:A,refresh:$}}function dz(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 v=b[1];if(/^[A-Z]+-\d+$/.test(v)){const N=new URLSearchParams(window.location.search);N.set("task",v);const k=N.toString(),E=window.history.state??{};window.history.replaceState(E,"",k?`/?${k}`:"/"),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(v=>v.id===g);if(!b){l(`Project '${g}' not found`,"error");return}r?.id!==b.id&&o(b)}if(u.current)return;u.current=!0,$a(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 uz(){const[e,n]=i.useState([]),[s,a]=i.useState([]),[r,o]=i.useState([]),l=i.useRef(s),c=i.useRef(r);i.useEffect(()=>{Fs().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 Pn({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 Pn({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 mz({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;xo().then(({providers:d})=>{const u=d.some(h=>h.authenticated);if(d.length>0&&!u||d.length>0&&u)return Ki().then(h=>{const f=!!(h.defaultProvider&&h.defaultModelId);(h.modelOnboardingComplete===!1||h.modelOnboardingComplete===void 0)&&(!u||!f)&&!Cr()?l=!0:!u&&!Cr()&&(c=!0)})}).then(()=>{if(o.current){r.current=!1;return}l?(ii("onboarding:auto-triggered",{trigger:"first-run"}),s()):c&&(ii("onboarding:auto-triggered",{trigger:"missing-provider"}),a("authentication"))}).catch(()=>{})},[e,n,s,a])}const bg="kb-update-banner-dismissed";function hz(){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(bg)==="true";u(h);let f=!1;return Aj().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(bg,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:d,dismiss:m}}const pz=["board","list","graph","agents","missions","chat","documents","research","evals","skills","mailbox","insights","memory","devserver","dev-server","stash-recovery"];function fz(e){return e!==null&&pz.includes(e)}function Dd(e){return e!==null&&(fz(e)||ur(e))}const gz=zo("roadmap-planner","roadmaps");function xg(e){return e==="devserver"?"dev-server":e}function vg(e){return e!=="roadmaps"?"board":mb("roadmap-planner","roadmaps")?gz:"board"}function bz(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=Fn("kb-dashboard-task-view");return b==="roadmaps"?vg(b):Dd(b)?b:"board"}),g=i.useRef(!1);i.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),i.useEffect(()=>{const b=Fn("kb-dashboard-task-view",r?.id);if(b==="roadmaps")p(vg(b));else if(Dd(b)){const v=!g.current&&b==="devserver";p(v?"devserver":xg(b))}else p("board");r?.id&&(g.current=!0)},[r?.id]),i.useEffect(()=>{ds("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&&Dd(b)&&p(xg(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"],v=b.indexOf(d),N=b[(v+1)%b.length];u(N)},[d,u]);return{viewMode:m,setViewMode:h,taskView:f,setTaskView:p,handleChangeTaskView:x,handleToggleTheme:w}}function xz(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 Ld=new Map,vz=6e4;function yz(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";Ld.delete(h),d(f=>f+1)},[e]);return i.useEffect(()=>{const h=e??"default";let f=!1;async function p(){const g=Ld.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 f0(e);if(f)return;Ld.set(h,{views:x,expiresAt:Date.now()+vz}),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 wz({taskView:e,context:n}){return t.jsx(eC,{viewId:e,context:n})}let yg=!1;function Dv(e,n){return function(){return i.createElement("span",null,`Bundled plugin view unavailable: ${e}#${n}`)}}async function kz(){const e="@fusion-plugin-examples/dependency-graph/dashboard-view",n="DependencyGraphDashboardView",a=(await kn(()=>import("./dashboard-view-4xAN3yO5.js"),__vite__mapDeps([24,1,25,5,6,26])))[n];return a?{default:a}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Dv(e,n)})}async function jz(){const e="@fusion-plugin-examples/roadmap/dashboard-view",n="RoadmapDashboardView",a=(await kn(()=>import("./dashboard-view-CyWN-d02.js"),__vite__mapDeps([27,1,25,28])))[n];return a?{default:a}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Dv(e,n)})}function Lv(){yg||(yg=!0,uh("fusion-plugin-dependency-graph","graph",i.lazy(kz)),uh("roadmap-planner","roadmaps",i.lazy(jz)))}function Nz(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(P=>{n(P),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(P=>{h(),n(P),a("project"),d(`Project ${P.name} registered successfully`,"success"),o()},[h,n,a,d,o]),v=i.useCallback(()=>{f()},[f]),N=i.useCallback(async P=>{try{await e1(P.id),d(`Project ${P.name} paused`,"success"),await o()}catch{d(`Failed to pause project ${P.name}`,"error")}},[d,o]),k=i.useCallback(async P=>{try{await t1(P.id),d(`Project ${P.name} resumed`,"success"),await o()}catch{d(`Failed to resume project ${P.name}`,"error")}},[d,o]),E=i.useCallback(async P=>{try{await tb(P.id),d(`Project ${P.name} removed`,"success"),r?.id===P.id&&(s(),a("overview")),await o()}catch{d(`Failed to remove project ${P.name}`,"error")}},[r,s,a,d,o]),y=i.useCallback(async P=>{try{await l(P)}catch{d("Failed to update favorites","error")}},[l,d]),j=i.useCallback(async P=>{try{await c(P)}catch{d("Failed to update model favorites","error")}},[c,d]);return{handleSelectProject:p,handleViewAllProjects:g,handleOpenSettings:x,handleAddProject:w,handleSetupComplete:b,handleModelOnboardingComplete:v,handlePauseProject:N,handleResumeProject:k,handleRemoveProject:E,handleToggleFavorite:y,handleToggleModelFavorite:j}}function Sz(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 Cz(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 v=[j0(e),N0(e)];s&&(v.push(S0(e,s,a)),v.push(C0(e,s)));const N=await Promise.allSettled(v);if(b.signal.aborted)return;const k=N[0],E=N[1];if(k.status==="rejected"){p(`Failed to fetch node health: ${k.reason}`),h(!1);return}if(u(k.value),E.status==="rejected"){p(`Failed to fetch projects: ${E.reason}`),h(!1);return}if(o(E.value),s&&N[2]){const y=N[2];if(y.status==="rejected"){p(`Failed to fetch tasks: ${y.reason}`),h(!1);return}y.status==="fulfilled"&&c(y.value)}h(!1)}catch(v){b.signal.aborted||(p(v instanceof Error?v.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 Ez(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 li(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 _z="fusion-dashboard-current-node",Ov=i.createContext(null);function Mz({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 Ki();if(m)return;l.current=f.dashboardCurrentNodeId;const p=f.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const g=localStorage.getItem(_z);if(g){const x=JSON.parse(g);x?.id&&x?.type==="remote"&&(l.current=x.id,await Pn({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,Pn({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,Pn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,a]);const c=i.useCallback(m=>{s(m)},[]),d=i.useCallback(()=>{s(null),l.current=void 0,Pn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),u={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:d};return t.jsx(Ov.Provider,{value:u,children:e})}function Az(){const e=i.useContext(Ov);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}const Rz=["shellKind","shellMode","profileId","serverBaseUrl","serverLabel","shellCanOpenConnectionManager","hostKind","mode","connectionId","serverUrl","canOpenConnectionManager"],Pz=["__FUSION_SHELL_HOST_CONTEXT__","__fusionShellHostContext","__FUSION_SHELL_CONTEXT__"];let Xl=null,wg=!1;function Iz(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 Tz(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 zv(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 $z(e){return e==="local"||e==="remote"?e:void 0}function Fv(e){const n=$z(e.mode),s=typeof e.connectionId=="string"&&e.connectionId.trim()?e.connectionId:void 0,a=Tz(e.serverUrl),r=Iz(e.canOpenConnectionManager);return{kind:e.kind,...n?{mode:n}:{},...s?{connectionId:s}:{},...a?{serverUrl:a}:{},...r!==void 0?{canOpenConnectionManager:r}:{}}}function Dz(e){for(const n of Pz){const s=e[n];if(!s||typeof s!="object")continue;const a=s,r=zv(a.kind??a.shellKind??a.hostKind);if(r)return r==="browser"?{kind:r}:Fv({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 Lz(e){let n;try{n=new URL(e.location.href)}catch{return null}const s=n.searchParams,a=zv(s.get("hostKind")??s.get("kind")??s.get("shellKind"));return a?a==="browser"?{kind:a}:Fv({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 Oz(e){try{const n=new URL(e.location.href);let s=!1;for(const r of Rz)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 zz(e=window){const n=Dz(e);if(n)return n;const s=Lz(e);return s||(typeof e.fusionAPI<"u"?{kind:"desktop-shell"}:{kind:"browser"})}function Bv(e=window){return!wg&&typeof window<"u"&&(Xl=zz(e),Oz(e),wg=!0),Xl??{kind:"browser"}}function Fz(){return Xl||(typeof window>"u"?{kind:"browser"}:Bv(window))}const Bz={kind:"browser"},Uv=i.createContext({host:Bz,isNativeShell:!1,kind:"browser"});function Uz(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 Hz({children:e}){const n=i.useMemo(()=>Uz(Fz()),[]);return t.jsx(Uv.Provider,{value:n,children:e})}function qz(){return i.useContext(Uv)}function Vz(e,n){const s=new URL(e);return n&&s.searchParams.set("rt",n),s.toString()}function Wz({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),v=s.host==="desktop-shell";i.useEffect(()=>{v&&o(s.desktopMode??"remote")},[v,s.desktopMode]);const N=i.useMemo(()=>v&&r==="local"?!0:d.trim().length>0,[v,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."}),v&&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"})]}),(!v||r==="remote")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn",onClick:async()=>{p(null),x(!0);try{const k=await n.startQrScan();u(k.serverUrl),h(k.authToken??"")}catch(k){p(k.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:k=>c(k.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:k=>u(k.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:k=>h(k.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:!N||w,onClick:async()=>{p(null),b(!0);try{if(v&&r==="local"){await n.setDesktopMode("local"),a();return}const k=await n.saveProfile({name:l.trim()||"Remote Server",serverUrl:d,authToken:m||null});if(v&&await n.setDesktopMode("remote"),await n.setActiveProfile(k.id),typeof window<"u"&&s.host!=="web"){window.location.href=Vz(k.serverUrl,k.authToken??null);return}a()}catch(k){p(k.message)}finally{b(!1)}},children:w?"Saving…":"Continue"})})]})}):null}function Kz({open:e,shellApi:n,shellState:s,onClose:a}){const r=i.useMemo(()=>s.profiles.find(y=>y.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(y=>y.id===o)??r,x=c.name??g?.name??"",w=c.serverUrl??g?.serverUrl??"",b=c.authToken??g?.authToken??"",v=()=>{l(null),d({}),f(null)},N=async()=>{f(null);try{const y=new URL(w.trim());if(!/^https?:$/.test(y.protocol))throw new Error("Server URL must use http or https");const j=await n.saveProfile({id:p?void 0:o??g?.id,name:x||"Remote Server",serverUrl:w,authToken:b||null});await n.setActiveProfile(j.id),l(j.id),d({})}catch(y){f(y.message)}},k=async()=>{f(null);try{const y=await n.startQrScan();l("__new__"),d({name:"",serverUrl:y.serverUrl,authToken:y.authToken??""})}catch(y){f(y.message)}},E=async()=>{u&&(await n.deleteProfile(u.id),m(null),v())};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 k(),children:"Scan QR"})]})]}):s.profiles.map(y=>t.jsxs("div",{className:"card native-shell-connection-manager__profile",children:[t.jsxs("div",{children:[t.jsx("strong",{children:y.name}),t.jsx("div",{className:"settings-muted",children:y.serverUrl}),y.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 ${y.name}`,onClick:()=>{l(y.id),d(y)},children:"Edit"}),t.jsx("button",{type:"button",className:"btn btn-sm","aria-label":`Use ${y.name}`,onClick:()=>void n.setActiveProfile(y.id),children:"Use"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-danger","aria-label":`Delete ${y.name}`,onClick:()=>m(y),children:"Delete"})]})]},y.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 k(),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:y=>d(j=>({...j,name:y.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:y=>d(j=>({...j,serverUrl:y.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:y=>d(j=>({...j,authToken:y.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 E(),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:v,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void N(),disabled:!w.trim(),children:"Save"})]})]})})}function Gz(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 kg({status:e,onError:n}){if(e.hostKind==="browser"||!e.available)return null;const s=Gz(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 Jz(e){if(e)try{return new URL(e).origin}catch{return}}function Yz(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 Qz(e){if(!e?.getState)return null;try{return await e.getState()}catch{return null}}async function Xz(e,n=window){const s=n.fusionAPI,a=n.fusionShell,r=await Qz(a),o=r?Yz(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=Jz(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 Zz({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&&(aj(l),window.location.reload())},[n]),o=i.useCallback(()=>{rj(),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 eF=200,tF=i.lazy(()=>kn(()=>import("./AgentsView-D6Zi5zfP.js"),__vite__mapDeps([29,1,3,4,30,15,5,6,31])).then(e=>({default:e.AgentsView}))),nF=i.lazy(()=>kn(()=>import("./DocumentsView-Bg2oaZks.js"),__vite__mapDeps([32,1,5,6,33])).then(e=>({default:e.DocumentsView}))),sF=i.lazy(()=>kn(()=>import("./InsightsView-Q1zvtF4F.js"),__vite__mapDeps([34,1,22,5,6,35])).then(e=>({default:e.InsightsView}))),iF=i.lazy(()=>kn(()=>import("./ResearchView-CERNf7sJ.js"),__vite__mapDeps([36,1,5,6,37])).then(e=>({default:e.ResearchView}))),aF=i.lazy(()=>kn(()=>import("./EvalsView-B3uOCXfr.js"),__vite__mapDeps([38,1,5,6,39])).then(e=>({default:e.EvalsView}))),rF=i.lazy(()=>kn(()=>import("./NodesView-RxXg58_Q.js"),__vite__mapDeps([40,1,17,30,5,6,41])).then(e=>({default:e.NodesView}))),oF=i.lazy(()=>kn(()=>import("./ChatView-CAHjY9uO.js"),__vite__mapDeps([42,1,5,6,43])).then(e=>({default:e.ChatView}))),lF=i.lazy(()=>kn(()=>import("./SkillsView-ClLM6u6p.js"),__vite__mapDeps([44,1,5,6,45])).then(e=>({default:e.SkillsView}))),cF=i.lazy(()=>kn(()=>import("./MemoryView-xcN_eouf.js"),__vite__mapDeps([46,1,20,21,5,6,47])).then(e=>({default:e.MemoryView}))),dF=i.lazy(()=>kn(()=>import("./DevServerView--_WBvIDQ.js"),__vite__mapDeps([48,1,5,6,49])).then(e=>({default:e.DevServerView})));i.lazy(()=>kn(()=>import("./TodoView-CTmIfy2M.js"),__vite__mapDeps([11,1,5,6,12])).then(e=>({default:e.TodoView})));const uF=i.lazy(()=>kn(()=>import("./StashRecoveryView-ze0pEZ5U.js"),__vite__mapDeps([50,1,5,6,51])).then(e=>({default:e.StashRecoveryView})));function mF(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{kn(()=>import("./AgentsView-D6Zi5zfP.js"),__vite__mapDeps([29,1,3,4,30,15,5,6,31])),kn(()=>import("./DocumentsView-Bg2oaZks.js"),__vite__mapDeps([32,1,5,6,33])),kn(()=>import("./InsightsView-Q1zvtF4F.js"),__vite__mapDeps([34,1,22,5,6,35])),kn(()=>import("./ResearchView-CERNf7sJ.js"),__vite__mapDeps([36,1,5,6,37])),kn(()=>import("./EvalsView-B3uOCXfr.js"),__vite__mapDeps([38,1,5,6,39])),kn(()=>import("./NodesView-RxXg58_Q.js"),__vite__mapDeps([40,1,17,30,5,6,41])),kn(()=>import("./ChatView-CAHjY9uO.js"),__vite__mapDeps([42,1,5,6,43])),kn(()=>import("./SkillsView-ClLM6u6p.js"),__vite__mapDeps([44,1,5,6,45])),kn(()=>import("./MemoryView-xcN_eouf.js"),__vite__mapDeps([46,1,20,21,5,6,47])),kn(()=>import("./DevServerView--_WBvIDQ.js"),__vite__mapDeps([48,1,5,6,49])),kn(()=>import("./TodoView-CTmIfy2M.js"),__vite__mapDeps([11,1,5,6,12])),kn(()=>import("./StashRecoveryView-ze0pEZ5U.js"),__vite__mapDeps([50,1,5,6,51]))})}Lv();const Od="kb-setup-warning-dismissed",hF="kb-chat-active-session",jg="kb-dashboard-working-branch-filter",Ng="kb-dashboard-base-branch-filter",Sg="__fusion:no-branch__",Hv="fusion:approval-banner-dismissed";function pF(e,n){return e==="awaiting-approval"&&n!=="awaiting-approval"}function Cg(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function fF(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(Hv);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 Eg(e){if(!(typeof window>"u"))try{const n={};for(const[s,a]of e)n[s]=a;window.localStorage.setItem(Hv,JSON.stringify(n))}catch{}}function gF(e,n){const s=new URL(e);return n&&s.searchParams.set("rt",n),s.toString()}function bF(e,n,s){return!n||s||e.host==="web"?!1:e.host==="mobile-shell"?!e.activeProfileId:e.desktopMode==="local"?!1:!e.activeProfileId}function xF(){const{toasts:e,addToast:n,removeToast:s}=ez(),{shellApi:a,state:r,ready:o,openConnectionManagerSignal:l}=xv(),c=qz();i.useEffect(()=>{mF()},[]);const{projects:d,loading:u,error:m,refresh:h}=JO(),{nodes:f}=uc(),{currentNode:p,currentNodeId:g,isRemote:x,setCurrentNode:w,clearCurrentNode:b}=Az(),{currentProject:v,setCurrentProject:N,clearCurrentProject:k,loading:E}=XO(d,{nodeId:g}),{hasAiProvider:y,hasGithub:j,loading:P,hasWarnings:F}=pv(v?.id),{updateAvailable:_,latestVersion:R,currentVersion:L,dismissed:U,dismiss:C}=hz();i.useEffect(()=>{if(g&&!p&&f.length>0){const Qe=f.find(Dt=>Dt.id===g);if(Qe){w(Qe);return}}g&&f.length>0&&(f.some(Dt=>Dt.id===g)||b())},[g,p,f,w,b]);const[$,V]=i.useState(""),[Y,ne]=i.useState(""),[q,A]=i.useState("");i.useEffect(()=>{ne(Fn(jg,v?.id)??""),A(Fn(Ng,v?.id)??"")},[v?.id]);const I=i.useCallback(Qe=>{ne(Qe),ds(jg,Qe,v?.id)},[v?.id]),D=i.useCallback(Qe=>{A(Qe),ds(Ng,Qe,v?.id)},[v?.id]),S=Cz(g,{projectId:v?.id,searchQuery:$||void 0});Ez(g);const G=x&&S.projects.length>0?S.projects:d,{themeMode:he,colorTheme:Se,dashboardFontScalePct:Ue,setThemeMode:ce,setColorTheme:Ae,setDashboardFontScalePct:X}=oz(),{sessions:Z,generating:ee,needsInput:le,planningSessions:K,dismissSession:O}=FO(v?.id),pe=Z.filter(Qe=>Qe.status==="awaiting_input"||Qe.status==="error"),ve=HO(),B=lz({projectId:v?.id,planningSessions:K}),ze=Zs()==="mobile",{pushNav:re,replaceCurrent:He}=xz({enabled:!0}),{viewMode:Pe,setViewMode:tt,taskView:qe,handleChangeTaskView:de}=bz({projectsLoading:u,projectsError:m,currentProjectLoading:E,currentProject:v,projectsLength:d.length,setupWizardOpen:B.setupWizardOpen,openSetupWizard:B.openSetupWizard,themeMode:he,setThemeMode:ce}),{views:De}=yz(v?.id),Te=i.useMemo(()=>{const Qe=De.find(Dt=>Dt.pluginId==="fusion-plugin-dependency-graph"&&Dt.view.viewId==="graph");return Qe?`plugin:${Qe.pluginId}:${Qe.view.viewId}`:mb("fusion-plugin-dependency-graph","graph")?"plugin:fusion-plugin-dependency-graph:graph":null},[De]),ct=i.useCallback(Qe=>{Qe==="missions"&&(rn(void 0),it(void 0),Rt(void 0));const Dt=qe;de(Qe),Dt!==Qe&&re({type:"view",revert:()=>de(Dt)})},[de,qe,re]),Ve=qe==="board"||qe==="list",{tasks:me,createTask:oe,moveTask:Me,pauseTask:Xe,deleteTask:rt,mergeTask:ht,retryTask:yt,resetTask:Re,updateTask:Ge,duplicateTask:at,archiveTask:ie,unarchiveTask:Ke,archiveAllDone:je,loadArchivedTasks:Fe,ingestCreatedTasks:Be,lastFetchTimeMs:St}=VO({...v?{projectId:v.id}:{},searchQuery:$||void 0,sseEnabled:Ve}),ye=x&&S.tasks.length>0?S.tasks:me,[kt,It]=i.useState(!1),[Ie,be]=i.useState(0),ot=i.useRef(performance.now()),gt=i.useRef(!1),xt=i.useRef(!1),jt=i.useMemo(()=>u?"projects":E?"project":"tasks",[u,E]);i.useEffect(()=>{if(!u&&!gt.current){gt.current=!0;const Qe=`projects loaded at ${Math.round(performance.now()-ot.current)}ms from mount`;console.log(`[App] ${Qe}`)}if(!E&&!xt.current){xt.current=!0;const Qe=`current-project resolved at ${Math.round(performance.now()-ot.current)}ms from mount`;console.log(`[App] ${Qe}`)}},[u,E]),i.useEffect(()=>{if(kt||u||E)return;const Qe=performance.now(),Dt=window.setTimeout(()=>{const on=`dashboard ready at ${Math.round(performance.now()-ot.current)}ms from mount (settle delay=${Math.round(performance.now()-Qe)}ms)`;console.log(`[App] ${on}`),It(!0)},eF);return()=>{window.clearTimeout(Dt)}},[kt,u,E]);const{keyboardOpen:Bt}=Yi({enabled:ze}),Jt=ze&&Bt&&!B.anyModalOpen;ji(Jt);const[Vt,pn]=i.useState(0),[Xt,mn]=i.useState(0),[Ht,Zt]=i.useState(!1),[tn,dn]=i.useState(0),[qt,ke]=i.useState(null),$e=i.useRef(new Map),Ye=i.useRef(new Set),ut=i.useRef(fF()),We=i.useCallback(()=>{rb(v?.id).then(Qe=>{pn(Qe.unreadCount),mn(Qe.pendingApprovalCount??0)}).catch(Qe=>{console.warn("[App] Failed to fetch mailbox unread count:",Qe)})},[v?.id]);i.useEffect(()=>{const Qe=new Map,Dt=new Set;for(const on of me)Qe.set(on.id,on.status),on.status==="awaiting-approval"&&Dt.add(`task:${on.id}`);$e.current=Qe,Ye.current=Dt},[me]),i.useEffect(()=>{We();const Qe=new URLSearchParams;v?.id&&Qe.set("projectId",v.id);const Dt=Qe.size>0?`?${Qe.toString()}`:"",on=os=>{const H=ut.current.get(os.dedupeKey);H!==void 0&&os.updatedAtMs<=H||ke(os)};return li(`/api/events${Dt}`,{onReconnect:We,events:{"message:sent":We,"message:received":We,"message:read":We,"message:deleted":We,"approval:requested":os=>{We();try{const H=JSON.parse(os.data),Ne=H.id?`approval:${H.id}`:H.taskId?`task:${H.taskId}`:void 0;if(!Ne||Ye.current.has(Ne))return;Ye.current.add(Ne),on({dedupeKey:Ne,updatedAtMs:Cg(H.updatedAt??H.createdAt)})}catch{}},"approval:updated":We,"approval:decided":We,"task:updated":os=>{try{const H=JSON.parse(os.data);if(!H?.id)return;const Ne=`task:${H.id}`,Je=$e.current.get(H.id);if($e.current.set(H.id,H.status),H.status!=="awaiting-approval"){Ye.current.delete(Ne),ut.current.delete(Ne),Eg(ut.current);return}if(Ye.current.has(Ne))return;pF(H.status,Je)&&(Ye.current.add(Ne),on({dedupeKey:Ne,updatedAtMs:Cg(H.updatedAt)}),We())}catch{}}}})},[v?.id,We]),i.useEffect(()=>{qe==="chat"&&Zt(!1)},[qe]),i.useEffect(()=>{let Qe=!1;const Dt=async()=>{try{const os=await T("/stash-recovery/orphans");Qe||dn(os.count??0)}catch{Qe||dn(0)}};Dt();const on=window.setInterval(()=>void Dt(),3e4);return()=>{Qe=!0,window.clearInterval(on)}},[v?.id]),i.useEffect(()=>{const Qe=new URLSearchParams;v?.id&&Qe.set("projectId",v.id);const Dt=Qe.size>0?`?${Qe.toString()}`:"";return li(`/api/events${Dt}`,{events:{"chat:message:added":on=>{try{const os=JSON.parse(on.data),H=Fn(hF,v?.id);if(!H||os.role!=="assistant"||qe==="chat"||os.sessionId!==H||os.projectId&&v?.id&&os.projectId!==v.id)return;Zt(!0)}catch{}}}})},[v?.id,qe]);const $t=i.useMemo(()=>Array.from(new Set(ye.map(Qe=>Qe.branch?.trim()).filter(Qe=>!!(Qe&&Qe.length>0)))).sort((Qe,Dt)=>Qe.localeCompare(Dt)),[ye]),At=i.useMemo(()=>Array.from(new Set(ye.map(Qe=>Qe.baseBranch?.trim()).filter(Qe=>!!(Qe&&Qe.length>0)))).sort((Qe,Dt)=>Qe.localeCompare(Dt)),[ye]),wt=i.useMemo(()=>ye.filter(Qe=>{const Dt=Qe.branch?.trim()??"",on=Qe.baseBranch?.trim()??"";if(Y===Sg){if(Dt.length>0)return!1}else if(Y.length>0&&Dt!==Y)return!1;if(q===Sg){if(on.length>0)return!1}else if(q.length>0&&on!==q)return!1;return!0}),[ye,Y,q]),[zt,Lt]=i.useState(!1),[Ot,nn]=i.useState(!1),[Yt,rn]=i.useState(void 0),[_e,it]=i.useState(void 0),[bt,Rt]=i.useState(void 0),[se,te]=i.useState(!1),[Oe,mt]=i.useState(!1),[Pt,sn]=i.useState(()=>Fn(Od,v?.id)==="true");i.useEffect(()=>{sn(Fn(Od,v?.id)==="true")},[v?.id]),i.useEffect(()=>{const Qe=()=>{mt(!0)};return window.addEventListener(Gd,Qe),()=>{window.removeEventListener(Gd,Qe)}},[]);const In=i.useCallback(()=>{ds(Od,"true",v?.id),sn(!0)},[v?.id]),{maxConcurrent:fe,autoMerge:ft,globalPaused:lt,enginePaused:vt,taskStuckTimeoutMs:et,showQuickChatFAB:_t,prAuthAvailable:Gt,settingsLoaded:ae,experimentalFeatures:pt,insightsEnabled:gn,memoryEnabled:us,devServerEnabled:Kn,todosEnabled:_n,toggleAutoMerge:$n,toggleGlobalPause:hn,toggleEnginePause:Ut,refresh:Dn}=cz(v?.id),as=pt.skillsView===!0,Rn=pt.nodesView===!0,ms=pt.researchView===!0,Xn=pt.evalsView===!0,vs=pt.agentOnboarding===!0,Gn=!0,hs=i.useCallback(()=>{B.closeSettings(),be(Qe=>Qe+1),Dn()},[B,Dn]);i.useEffect(()=>{if(ae&&!ur(qe)){if(qe==="graph"&&!Te){de("board");return}qe==="skills"&&!as&&de("board"),qe==="insights"&&!gn&&de("board"),qe==="memory"&&!us&&de("board"),(qe==="devserver"||qe==="dev-server")&&!Kn&&de("board"),qe==="research"&&!ms&&de("board"),qe==="evals"&&!Xn&&de("board")}},[qe,ae,as,gn,de,Gn,us,Kn,ms,Xn,Te]),i.useEffect(()=>{zt&&!Rn&&Lt(!1)},[zt,Rn]);const{availableModels:Ln,favoriteProviders:En,favoriteModels:ps,toggleFavoriteProvider:Nn,toggleFavoriteModel:As}=uz();mz({projectId:v?.id,setupWizardOpen:B.setupWizardOpen,openModelOnboarding:B.openModelOnboarding,openSettings:B.openSettings});const{handleSelectProject:Cs,handleViewAllProjects:Es,handleAddProject:Q,handleSetupComplete:M,handleModelOnboardingComplete:ue,handlePauseProject:Ee,handleResumeProject:z,handleRemoveProject:ge,handleToggleFavorite:xe,handleToggleModelFavorite:dt}=Nz({setCurrentProject:N,clearCurrentProject:k,setViewMode:tt,currentProject:v,refreshProjects:h,toggleFavoriteProvider:Nn,toggleFavoriteModel:As,addToast:n,openSettings:B.openSettings,openSetupWizard:B.openSetupWizard,closeSetupWizard:B.closeSetupWizard,closeModelOnboarding:B.closeModelOnboarding}),{handleDetailClose:Tt}=dz({projectId:v?.id,projects:d,projectsLoading:u,currentProject:v,setCurrentProject:N,addToast:n,openTaskDetail:B.openDetailTask,closeTaskDetail:B.closeDetailTask}),Wt=i.useCallback(async({insightId:Qe,title:Dt,description:on})=>{await oe({title:Dt,description:on,column:"triage",source:{sourceType:"dashboard_ui",sourceMetadata:{origin:"insights",insightId:Qe}}})},[oe]),{handleBoardQuickCreate:bn,handleModalCreate:Mn,handlePlanningTaskCreated:Zn,handlePlanningTasksCreated:On,handleSubtaskTasksCreated:Un,handleGitHubImport:rs}=Sz({createTask:oe,ingestCreatedTasks:Be,onPlanningTaskCreated:B.onPlanningTaskCreated,onPlanningTasksCreated:B.onPlanningTasksCreated,onSubtaskTasksCreated:B.onSubtaskTasksCreated,addToast:n}),ts=i.useCallback((Qe,Dt)=>{Dt==="changes"?B.openDetailWithChangesTab(Qe):B.openDetailTask(Qe,Dt),re({type:"modal",close:B.closeDetailTask})},[B,re]),xn=i.useCallback(async Qe=>{try{const Dt=await $a(Qe,v?.id);B.openDetailTask(Dt,"logs"),re({type:"modal",close:B.closeDetailTask})}catch(Dt){n(`Failed to open task logs: ${Dt.message}`,"error")}},[B,v?.id,n,re]),[Jn,Hn]=i.useState([]);i.useEffect(()=>{let Qe=!1;return $o(v?.id).then(Dt=>{Qe||Hn(Dt)}).catch(()=>{Qe||Hn([])}),()=>{Qe=!0}},[v?.id]);const ws=i.useMemo(()=>new Map(Jn.map(Qe=>[Qe.id,Qe.name])),[Jn]);i.useCallback(()=>{Rn&&Lt(Qe=>!Qe)},[Rn]);const ns=i.useCallback(()=>{Rn&&(zt?Lt(!1):(Lt(!0),re({type:"view",revert:()=>Lt(!1)})))},[Rn,zt,re]),es=i.useCallback((Qe,Dt,on)=>{B.openDetailTask(Qe,Dt,on),re({type:"modal",close:B.closeDetailTask})},[B,re]),Bs=i.useCallback(Qe=>{B.openSettings(Qe),re({type:"modal",close:hs})},[B,re,hs]),Ds=i.useCallback(()=>{B.openNewTask(),re({type:"modal",close:B.closeNewTask})},[B,re]),wn=i.useCallback(()=>{B.openPlanning(),re({type:"modal",close:B.closePlanning})},[B,re]),ma=i.useCallback(Qe=>{B.openPlanningWithInitialPlan(Qe),re({type:"modal",close:B.closePlanning})},[B,re]),ha=i.useCallback(()=>{B.resumePlanning(),re({type:"modal",close:B.closePlanning})},[B,re]),pa=i.useCallback(Qe=>{B.openSubtaskBreakdown(Qe),re({type:"modal",close:B.closeSubtask})},[B,re]),Ha=i.useCallback(()=>{B.openGitHubImport(),re({type:"modal",close:B.closeGitHubImport})},[B,re]),ei=i.useCallback(()=>{B.terminalOpen?B.toggleTerminal():(B.toggleTerminal(),re({type:"modal",close:B.closeTerminal}))},[B,re]),di=i.useCallback(()=>{B.openFiles(),re({type:"modal",close:B.closeFiles})},[B,re]),Di=i.useCallback(()=>{B.openTodos(),re({type:"modal",close:B.closeTodos})},[B,re]),fa=i.useCallback(()=>{B.openActivityLog(),re({type:"modal",close:B.closeActivityLog})},[B,re]),qa=i.useCallback(()=>{B.openGitManager(),re({type:"modal",close:B.closeGitManager})},[B,re]),Va=i.useCallback(()=>{B.openSystemStats(),re({type:"modal",close:B.closeSystemStats})},[B,re]),ga=i.useCallback(()=>{B.openSchedules(),re({type:"modal",close:B.closeSchedules})},[B,re]),ti=i.useCallback(()=>{B.openScripts(),re({type:"modal",close:B.closeScripts})},[B,re]),ui=i.useCallback(()=>{B.openWorkflowSteps(),re({type:"modal",close:B.closeWorkflowSteps})},[B,re]),ni=i.useCallback(Qe=>{B.openUsage(Qe),re({type:"modal",close:B.closeUsage})},[B,re]),ba=i.useCallback(async(Qe,Dt)=>{await B.runScript(Qe,Dt),He({type:"modal",close:B.closeTerminal})},[B,He]),xa=i.useCallback(()=>{B.closeSettings(),B.openModelOnboarding(),He({type:"modal",close:B.closeModelOnboarding})},[B,He]),va=i.useCallback(()=>{B.setFileWorkspace("project"),B.openFiles()},[B]),Ls=i.useCallback(async()=>{nn(!0);try{await h()}finally{nn(!1)}},[h]),Wa=i.useCallback(Qe=>{it(Qe),rn(void 0),de("missions")},[de]),ya=i.useCallback(Qe=>{Qe.type==="planning"?B.openPlanningWithSession(Qe.id):Qe.type==="subtask"?B.openSubtaskWithSession(Qe.id):Qe.type==="mission_interview"?(it(void 0),rn(Qe.id),Rt(void 0),de("missions")):(Qe.type==="milestone_interview"||Qe.type==="slice_interview")&&(rn(void 0),it(void 0),Rt(Qe.id),de("missions"))},[de,B]),Qi=i.useCallback(()=>{},[]),Tr=i.useCallback(()=>{},[]),[$r,Dr]=i.useState(!1),[wa,ka]=i.useState(!1),[Li,Ka]=i.useState(null),Oi=bF(r,o,$r);i.useEffect(()=>{!a||l===0||ka(!0)},[a,l]),i.useEffect(()=>{let Qe=!1;return Xz(c.host).then(Dt=>{Qe||Ka(Dt)}),()=>{Qe=!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 Qe=r.profiles.find(on=>on.id===r.activeProfileId);if(!Qe||typeof window>"u")return;const Dt=gF(Qe.serverUrl,Qe.authToken??null);window.location.href!==Dt&&(window.location.href=Dt)},[r]);const ja=!u&&!E&&d.length===0&&!v&&!!m,Ga=()=>{if(ja)return t.jsx(qL,{errorMessage:m??"Failed to fetch projects",isRetrying:Ot,onRetry:Ls,onManageConnection:a?()=>{a.openConnectionManager()}:void 0});if(zt)return t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(rF,{addToast:n,onClose:()=>Lt(!1)})})})});if(Pe==="overview")return t.jsx(_s,{children:t.jsx(ET,{projects:d,loading:u,onSelectProject:Cs,onAddProject:Q,onPauseProject:Ee,onResumeProject:z,onRemoveProject:ge,nodes:f})});const Qe=qe==="graph"?Te:ur(qe)?qe:null;return Qe?t.jsx(_s,{children:t.jsx(wz,{taskView:Qe,context:{projectId:v?.id,tasks:x&&S.tasks.length>0?S.tasks:me,workflowSteps:Jn,openTaskDetail:(Dt,on)=>es(Dt,on),renderTaskCard:Dt=>t.jsx(yo,{task:Dt,projectId:v?.id,onOpenDetail:on=>es(on),addToast:n,workflowStepNameLookup:ws,disableDrag:!0}),addToast:n}})}):qe==="skills"?!ae||!as?null:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(lF,{addToast:n,projectId:v?.id,onClose:()=>de("board")})})}):qe==="chat"?t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(oF,{addToast:n,projectId:v?.id,experimentalFeatures:pt})})}):qe==="mailbox"?t.jsx(_s,{children:t.jsx(x4,{projectId:v?.id,addToast:n,onUnreadCountChange:pn})}):qe==="missions"?t.jsx(_s,{children:t.jsx(h4,{isInline:!0,isOpen:!0,onClose:()=>{it(void 0),rn(void 0),Rt(void 0),de("board")},addToast:n,projectId:v?.id,onSelectTask:Dt=>{const on=me.find(os=>os.id===Dt);on&&es(on)},availableTasks:me.map(Dt=>({id:Dt.id,title:Dt.title})),resumeSessionId:Yt,targetMissionId:_e,milestoneSliceResumeSessionId:bt,onMilestoneSliceResumeFetchError:()=>Rt(void 0)})}):qe==="agents"&&Gn?t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(tF,{addToast:n,projectId:v?.id,onOpenTaskLogs:xn,agentOnboardingEnabled:vs})})}):qe==="documents"?t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(nF,{projectId:v?.id,addToast:n,onOpenDetail:es})})}):qe==="stash-recovery"?t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(uF,{})})}):qe==="insights"?!ae||!gn?null:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(sF,{projectId:v?.id,addToast:n,onClose:()=>de("board"),onCreateTask:Wt})})}):qe==="research"?!ae||!ms?null:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(iF,{projectId:v?.id,addToast:n,onOpenSettings:Dt=>B.openSettings(Dt),readinessVersion:Ie})})}):qe==="evals"?!ae||!Xn?null:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(aF,{projectId:v?.id,onOpenSettings:Dt=>B.openSettings(Dt),onOpenTaskDetail:Dt=>{$a(Dt,v?.id).then(on=>es(on)).catch(on=>n(on instanceof Error?on.message:"Failed to open task detail","error"))}})})}):qe==="memory"?!ae||!us?null:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(cF,{addToast:n,projectId:v?.id})})}):qe==="devserver"||qe==="dev-server"?!ae||!Kn?null:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(dF,{addToast:n,projectId:v?.id})})}):qe==="board"?t.jsx(_s,{children:t.jsx(SE,{tasks:wt,projectId:v?.id,maxConcurrent:fe,onMoveTask:Me,onPauseTask:Xe,onOpenDetail:es,addToast:n,onQuickCreate:bn,onNewTask:Ds,onPlanningMode:ma,onSubtaskBreakdown:pa,autoMerge:ft,onToggleAutoMerge:$n,globalPaused:lt,onUpdateTask:Ge,onRetryTask:yt,onArchiveTask:ie,onUnarchiveTask:Ke,onDeleteTask:rt,onArchiveAllDone:je,onLoadArchivedTasks:Fe,searchQuery:$,availableModels:Ln,onOpenDetailWithTab:ts,favoriteProviders:En,favoriteModels:ps,onToggleFavorite:xe,onToggleModelFavorite:dt,taskStuckTimeoutMs:et,onOpenMission:Wa,lastFetchTimeMs:St})}):t.jsx(_s,{children:t.jsx(fT,{tasks:x&&S.tasks.length>0?S.tasks:me,projectId:v?.id,onMoveTask:Me,onRetryTask:yt,onDeleteTask:rt,onMergeTask:ht,onResetTask:Re,onDuplicateTask:at,onOpenDetail:(Dt,on)=>es(Dt,void 0,on),addToast:n,globalPaused:lt,onNewTask:Ds,onQuickCreate:bn,onPlanningMode:ma,onSubtaskBreakdown:pa,availableModels:Ln,favoriteProviders:En,favoriteModels:ps,onToggleFavorite:xe,onToggleModelFavorite:dt,taskStuckTimeoutMs:et,searchQuery:$,lastFetchTimeMs:St,prAuthAvailable:Gt})})};if(!kt)return t.jsxs(t.Fragment,{children:[t.jsx(WL,{stage:jt}),t.jsx(jv,{toasts:e,onRemove:s})]});const Na=!B.modelOnboardingOpen&&pL(),Ni=!B.modelOnboardingOpen&&!Na&&Cr()&&!vv();return t.jsxs(t.Fragment,{children:[t.jsx(iC,{shellHost:c.host,onOpenSettings:Bs,onOpenGitHubImport:Ha,onOpenPlanning:wn,onResumePlanning:ha,activePlanningSessionCount:K.length,onOpenUsage:ni,onOpenActivityLog:fa,onOpenSystemStats:Va,onOpenMailbox:()=>ct("mailbox"),mailboxUnreadCount:Vt,mailboxPendingApprovalCount:Xt,chatHasUnreadResponse:Ht,stashOrphanCount:tn,onOpenSchedules:ga,onOpenGitManager:qa,onOpenNodes:ns,showNodesButton:Rn,onOpenWorkflowSteps:ui,onOpenScripts:ti,onRunScript:ba,onToggleTerminal:ei,onOpenFiles:di,filesOpen:B.filesOpen,onOpenTodos:Di,todosOpen:B.todosOpen,todosEnabled:_n,globalPaused:lt,enginePaused:vt,onToggleGlobalPause:hn,onToggleEnginePause:Ut,view:qe,onChangeView:Pe==="project"&&v?ct:void 0,showSkillsTab:as,showAgentsTab:Gn,searchQuery:$,onSearchChange:V,branchFilter:Y,baseBranchFilter:q,branchOptions:$t,baseBranchOptions:At,onBranchFilterChange:I,onBaseBranchFilterChange:D,projects:G,currentProject:v,onSelectProject:Cs,onViewAllProjects:Es,projectId:v?.id,mobileNavEnabled:ze,availableNodes:f,currentNode:p,onSelectNode:Qe=>{Qe===null?b():w(Qe)},isRemote:x,experimentalFeatures:{insights:gn,memoryView:us,devServer:Kn,devServerView:Kn,researchView:ms,evalsView:Xn},pluginDashboardViews:De,shellConnectionControl:!ze&&Li?t.jsx(kg,{status:Li,onError:Qe=>n(Qe,"error")}):void 0}),Pe==="project"&&v&&!zt&&qe!=="missions"&&!B.isPlanningOpen&&!ve&&t.jsx(oO,{sessions:pe,onResumeSession:ya,onDismissSession:Qi,onDismissAll:Tr}),Pe==="project"&&v&&t.jsx(dO,{onOpenSettings:()=>B.openSettings("general")}),Pe==="project"&&v&&Na&&t.jsx(hO,{onResume:B.openModelOnboarding}),Pe==="project"&&v&&Ni&&t.jsx(pO,{onOpenModelOnboarding:B.openModelOnboarding,onOpenSettings:Qe=>B.openSettings(Qe)}),Pe==="project"&&v&&_&&R&&L&&!U&&t.jsx(uO,{latestVersion:R,currentVersion:L,onDismiss:C}),Pe==="project"&&v&&!P&&F&&!Pt&&t.jsx(fv,{hasAiProvider:y,hasGithub:j,onDismiss:In}),Pe==="project"&&v&&qt&&t.jsx(mO,{pendingCount:Math.max(Xt,1),onOpenMailbox:()=>ct("mailbox"),onDismiss:()=>{ut.current.set(qt.dedupeKey,Math.max(Date.now(),qt.updatedAtMs)),Eg(ut.current),ke(null)}}),t.jsx("div",{className:`project-content${Pe==="project"&&v?" project-content--with-footer":""}${ze&&!Jt?" project-content--with-mobile-nav":""}`,children:Ga()}),Pe==="project"&&v&&!zt&&t.jsx(nO,{tasks:x&&S.tasks.length>0?S.tasks:me,projectId:v.id,taskStuckTimeoutMs:et,backgroundSessions:Z,backgroundGenerating:ee,backgroundNeedsInput:le,onOpenBackgroundSession:ya,onDismissBackgroundSession:O,lastFetchTimeMs:St,currentProjectPath:v.path,onOpenProjectDirectory:va,keyboardOpen:Jt}),t.jsx(gO,{view:qe,onChangeView:Pe==="project"&&v?ct:()=>{},footerVisible:Pe==="project"&&!!v,modalOpen:B.anyModalOpen,keyboardOpen:Jt,onOpenSettings:Bs,onOpenActivityLog:fa,onOpenSystemStats:Va,onOpenMailbox:()=>ct("mailbox"),onOpenNodes:ns,mailboxUnreadCount:Vt,mailboxPendingApprovalCount:Xt,chatHasUnreadResponse:Ht,stashOrphanCount:tn,onOpenGitManager:qa,onOpenWorkflowSteps:ui,onOpenSchedules:ga,onOpenScripts:ti,onToggleTerminal:ei,onOpenFiles:di,onOpenTodos:Di,todosOpen:B.todosOpen,onOpenGitHubImport:Ha,onOpenPlanning:wn,onResumePlanning:ha,activePlanningSessionCount:K.length,onOpenUsage:()=>ni(null),onViewAllProjects:Es,onRunScript:ba,projectId:v?.id,showSkillsTab:as,experimentalFeatures:{insights:gn,memoryView:us,devServer:Kn,devServerView:Kn,todoView:_n,researchView:ms,evalsView:Xn,nodesView:Rn},pluginDashboardViews:De,shellConnectionControl:ze&&Li?t.jsx(kg,{status:Li,onError:Qe=>n(Qe,"error")}):void 0}),Pe==="project"&&v&&qe!=="chat"&&qe!=="mailbox"&&qe!=="insights"&&qe!=="evals"&&qe!=="devserver"&&qe!=="dev-server"&&qe!=="graph"&&!ur(qe)&&t.jsx(zO,{projectId:v.id,addToast:n,showFAB:_t,open:se,onOpenChange:te,favoriteProviders:En,favoriteModels:ps,onToggleFavorite:xe,onToggleModelFavorite:dt}),t.jsx(HL,{projectId:v?.id,tasks:me,projects:d,currentProject:v,addToast:n,toasts:e,removeToast:s,modalManager:B,projectActions:{handleAddProject:Q,handleSetupComplete:M,handleModelOnboardingComplete:ue},taskHandlers:{handleModalCreate:Mn,handlePlanningTaskCreated:Zn,handlePlanningTasksCreated:On,handleSubtaskTasksCreated:Un,handleGitHubImport:rs},taskOperations:{moveTask:Me,deleteTask:rt,mergeTask:ht,retryTask:yt,resetTask:Re,duplicateTask:at},deepLink:{handleDetailClose:Tt},settings:{prAuthAvailable:Gt,themeMode:he,colorTheme:Se,dashboardFontScalePct:Ue,setThemeMode:ce,setColorTheme:Ae,setDashboardFontScalePct:X},onSettingsClose:hs,onReopenOnboarding:xa}),t.jsx(Zz,{open:Oe}),a&&t.jsxs(t.Fragment,{children:[t.jsx(Wz,{open:Oi,shellApi:a,shellState:r,onComplete:()=>Dr(!0)}),t.jsx(Kz,{open:wa,shellApi:a,shellState:r,onClose:()=>ka(!1)})]})]})}function vF(){return t.jsx(ZO,{children:t.jsx(Hz,{children:t.jsx(nL,{children:t.jsx(Mz,{children:t.jsx(xC,{children:t.jsx(xF,{})})})})})})}function qv(e){e.postMessage({type:"SKIP_WAITING"})}function _g(e){e.addEventListener("statechange",()=>{e.state==="installed"&&navigator.serviceWorker.controller&&qv(e)})}function yF(){if(!("serviceWorker"in navigator))return;const e=!!navigator.serviceWorker.controller;let n=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{n||!e||(n=!0,_u("service worker activated new version"))}),navigator.serviceWorker.register("/sw.js").then(s=>{console.log("SW registered:",s.scope),s.waiting&&navigator.serviceWorker.controller&&qv(s.waiting),s.installing&&_g(s.installing),s.addEventListener("updatefound",()=>{const a=s.installing;a&&_g(a)})}).catch(s=>{console.log("SW registration failed:",s)})}hj();Xk();Bv();Lv();Qv.createRoot(document.getElementById("root")).render(t.jsx(i.StrictMode,{children:t.jsx(Zk,{children:t.jsx(vF,{})})}));yF();export{TS as $,Ys as A,Vn as B,Wn as C,fC as D,Q3 as E,oa as F,tc as G,qd as H,Cn as I,Al as J,R5 as K,Nt as L,Ao as M,nk as N,HD as O,Tn as P,Pd as Q,fs as R,Hi as S,Ro as T,ss as U,xi as V,Sn as W,an as X,zD as Y,is as Z,kn as _,un as a,uc as a$,PD as a0,ID as a1,$S as a2,G3 as a3,DS as a4,o3 as a5,l3 as a6,FN as a7,Su as a8,Er as a9,f5 as aA,h5 as aB,Vg as aC,fj as aD,xo as aE,c5 as aF,u5 as aG,d5 as aH,k5 as aI,y5 as aJ,w5 as aK,j5 as aL,A5 as aM,bo as aN,zd as aO,Ck as aP,Mi as aQ,bk as aR,Fy as aS,jT as aT,Os as aU,Ug as aV,fk as aW,l6 as aX,c6 as aY,d6 as aZ,u6 as a_,Fa as aa,wi as ab,ki as ac,Ri as ad,n5 as ae,o5 as af,r5 as ag,s5 as ah,l5 as ai,i5 as aj,a5 as ak,xs as al,So as am,co as an,Ts as ao,Lk as ap,Pi as aq,$g as ar,Wi as as,ry as at,m5 as au,p5 as av,v5 as aw,x5 as ax,b5 as ay,g5 as az,zn as b,lS as b$,JO as b0,Km as b1,Or as b2,ng as b3,k0 as b4,vr as b5,x0 as b6,G6 as b7,J6 as b8,y0 as b9,BF as bA,FF as bB,zF as bC,UF as bD,QF as bE,XF as bF,GF as bG,VF as bH,WF as bI,KF as bJ,qF as bK,HF as bL,OF as bM,JF as bN,v$ as bO,_3 as bP,E3 as bQ,T3 as bR,C3 as bS,M3 as bT,A3 as bU,R3 as bV,P3 as bW,dS as bX,I3 as bY,Au as bZ,oS as b_,yO as ba,w0 as bb,vO as bc,Z6 as bd,e5 as be,Y6 as bf,Q6 as bg,X6 as bh,t5 as bi,EO as bj,Yi as bk,Cv as bl,g0 as bm,bs as bn,ra as bo,Zl as bp,bO as bq,Aa as br,Fg as bs,SO as bt,Lg as bu,ym as bv,qi as bw,W6 as bx,V6 as by,K6 as bz,nt as c,aN as c$,cS as c0,rS as c1,S3 as c2,rc as c3,Nk as c4,fr as c5,g6 as c6,b6 as c7,x6 as c8,v6 as c9,p3 as cA,f3 as cB,py as cC,Xj as cD,y3 as cE,Zj as cF,w3 as cG,ai as cH,Ti as cI,HO as cJ,a$ as cK,ZF as cL,h6 as cM,SF as cN,CF as cO,Gf as cP,i6 as cQ,EF as cR,MF as cS,LF as cT,DF as cU,mN as cV,tN as cW,Ii as cX,nN as cY,iN as cZ,sN as c_,y6 as ca,w6 as cb,k6 as cc,f6 as cd,Wg as ce,Iw as cf,T as cg,zl as ch,yo as ci,gr as cj,JS as ck,aj as cl,rj as cm,Hj as cn,qj as co,L6 as cp,d3 as cq,c3 as cr,O6 as cs,u3 as ct,v3 as cu,g3 as cv,m3 as cw,b3 as cx,h3 as cy,x3 as cz,s6 as d,RD as d$,rN as d0,n3 as d1,a6 as d2,r6 as d3,o6 as d4,Gi as d5,S5 as d6,C5 as d7,p6 as d8,AF as d9,S6 as dA,_6 as dB,C6 as dC,N6 as dD,E6 as dE,M6 as dF,Yd as dG,Cm as dH,V3 as dI,K3 as dJ,m0 as dK,Ta as dL,Ps as dM,kw as dN,A6 as dO,Y3 as dP,_o as dQ,dI as dR,Ma as dS,W3 as dT,Z3 as dU,X3 as dV,Dg as dW,H3 as dX,U3 as dY,D3 as dZ,L3 as d_,Fd as da,ys as db,b$ as dc,VD as dd,KD as de,GD as df,ia as dg,Id as dh,YD as di,PF as dj,_F as dk,IF as dl,RF as dm,TF as dn,$F as dp,Da as dq,P5 as dr,uC as ds,cc as dt,E5 as du,Tp as dv,_5 as dw,M5 as dx,YF as dy,j6 as dz,t6 as e,Xa as e0,J3 as e1,F3 as e2,z3 as e3,BN as e4,B3 as e5,q3 as e6,R6 as e7,l0 as e8,O3 as e9,$3 as ea,oi as eb,N3 as ec,k3 as ed,j3 as ee,P6 as ef,z6 as eg,Vd as eh,U6 as ei,H6 as ej,B6 as ek,$6 as el,T6 as em,D6 as en,I6 as eo,F6 as ep,m6 as eq,N5 as er,s3 as es,e3 as et,t3 as eu,dk as ev,a3 as ew,r3 as ex,i3 as ey,$a as f,n6 as g,Fs as h,Mr as i,Pn as j,Gl as k,q6 as l,Ns as m,IS as n,e6 as o,Zs as p,NO as q,TD as r,li as s,Fn as t,ji as u,ci as v,ds as w,oc as x,qo as y,Ce as z};