@runfusion/fusion 0.22.0 → 0.24.0

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 (206) hide show
  1. package/dist/bin.js +30071 -20735
  2. package/dist/client/assets/AgentDetailView-BwJaLqZh.css +1 -0
  3. package/dist/client/assets/AgentDetailView-gy_5SUj2.js +18 -0
  4. package/dist/client/assets/AgentsView-BkB9FiMT.js +29 -0
  5. package/dist/client/assets/AgentsView-CV3vm7Qk.css +1 -0
  6. package/dist/client/assets/ChatView-B_-B8fqu.js +1 -0
  7. package/dist/client/assets/ChatView-DwJAd5G1.css +1 -0
  8. package/dist/client/assets/{DevServerView-l8RCyL2k.js → DevServerView-BkvtjZBa.js} +1 -1
  9. package/dist/client/assets/{DirectoryPicker-CS1dwqcC.js → DirectoryPicker-BK-KbnhP.js} +1 -1
  10. package/dist/client/assets/{DocumentsView-DmthQWDZ.js → DocumentsView-BEg1CQAk.js} +1 -1
  11. package/dist/client/assets/{DocumentsView-BrhyOdeE.css → DocumentsView-gv4zG3aT.css} +1 -1
  12. package/dist/client/assets/EvalsView-Berf9bQm.js +1 -0
  13. package/dist/client/assets/EvalsView-CUNJ1TLc.css +1 -0
  14. package/dist/client/assets/{agentSkills-DDHJnrkn.css → ExperimentalAgentOnboardingModal-B-APN_lM.css} +1 -1
  15. package/dist/client/assets/ExperimentalAgentOnboardingModal-jcInE50G.js +499 -0
  16. package/dist/client/assets/InsightsView-B0J4mhzV.css +1 -0
  17. package/dist/client/assets/InsightsView-BX5bSF1J.js +11 -0
  18. package/dist/client/assets/{MemoryView-CPwlKnUI.js → MemoryView-CKElJY_3.js} +2 -2
  19. package/dist/client/assets/NodesView-DLUOBLf6.js +14 -0
  20. package/dist/client/assets/NodesView-DT4pXowv.css +1 -0
  21. package/dist/client/assets/{PiExtensionsManager-j8rPXqmB.js → PiExtensionsManager-COlJf0Kx.js} +2 -2
  22. package/dist/client/assets/PluginManager-CfW55BF4.js +1 -0
  23. package/dist/client/assets/PluginManager-DtRQXia5.css +1 -0
  24. package/dist/client/assets/{ResearchView-D9DNJYDq.js → ResearchView-B256Lr8I.js} +1 -1
  25. package/dist/client/assets/SettingsModal-BeA_nQtW.js +31 -0
  26. package/dist/client/assets/SettingsModal-DzsLquBu.css +1 -0
  27. package/dist/client/assets/{SettingsModal-fxvTFLtR.js → SettingsModal-yRqM4DV8.js} +1 -1
  28. package/dist/client/assets/SetupWizardModal-uUZk3TKT.js +1 -0
  29. package/dist/client/assets/{SkillsView-Ddf0YL8z.js → SkillsView-CP8JX0P_.js} +1 -1
  30. package/dist/client/assets/TodoView-Cx9cVhq7.css +1 -0
  31. package/dist/client/assets/TodoView-DCRIkDZ-.js +6 -0
  32. package/dist/client/assets/createLucideIcon-BazL2hk5.js +21 -0
  33. package/dist/client/assets/dashboard-view-BkTMSZYn.css +1 -0
  34. package/dist/client/assets/dashboard-view-CyWN-d02.js +63 -0
  35. package/dist/client/assets/dashboard-view-lR7YYmSC.js +21 -0
  36. package/dist/client/assets/{folder-open-BiJpmnaT.js → folder-open-DHjELt8-.js} +1 -1
  37. package/dist/client/assets/index-CQyVRLOb.js +692 -0
  38. package/dist/client/assets/index-CxA2Nn0_.css +1 -0
  39. package/dist/client/assets/projectDetection-G3XuxD2X.js +1 -0
  40. package/dist/client/assets/{star-BwRZmiuZ.js → star-DYesq1AV.js} +1 -1
  41. package/dist/client/assets/{upload-D4NwZhPp.js → upload-DTWF3Db5.js} +1 -1
  42. package/dist/client/assets/{users-DNISDtI1.js → users--syrel4l.js} +1 -1
  43. package/dist/client/index.html +12 -20
  44. package/dist/client/theme-data.css +106 -0
  45. package/dist/client/version.json +1 -1
  46. package/dist/droid-cli/package.json +1 -1
  47. package/dist/extension.js +17072 -9627
  48. package/dist/pi-claude-cli/package.json +1 -1
  49. package/dist/plugins/fusion-plugin-cursor-runtime/bundled.js +218 -0
  50. package/dist/plugins/fusion-plugin-cursor-runtime/manifest.json +6 -0
  51. package/dist/plugins/fusion-plugin-cursor-runtime/package.json +11 -0
  52. package/dist/plugins/fusion-plugin-dependency-graph/manifest.json +1 -1
  53. package/dist/plugins/fusion-plugin-dependency-graph/package.json +6 -4
  54. package/dist/plugins/fusion-plugin-dependency-graph/src/DependencyGraph.css +58 -0
  55. package/dist/plugins/fusion-plugin-dependency-graph/src/DependencyGraph.tsx +301 -0
  56. package/dist/plugins/fusion-plugin-dependency-graph/src/GraphHighlight.css +27 -0
  57. package/dist/plugins/fusion-plugin-dependency-graph/src/GraphTaskNode.css +157 -0
  58. package/dist/plugins/fusion-plugin-dependency-graph/src/GraphTaskNode.tsx +126 -0
  59. package/dist/plugins/fusion-plugin-dependency-graph/src/GraphToolbar.css +35 -0
  60. package/dist/plugins/fusion-plugin-dependency-graph/src/GraphToolbar.tsx +36 -0
  61. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/DependencyGraph.highlighting.test.tsx +112 -0
  62. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/DependencyGraph.persistence.test.tsx +115 -0
  63. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/DependencyGraph.test.tsx +128 -0
  64. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/GraphTaskNode.drag.test.tsx +82 -0
  65. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/GraphTaskNode.test.tsx +307 -0
  66. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/GraphToolbar.test.tsx +60 -0
  67. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/edges.test.tsx +75 -0
  68. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/filtering.test.tsx +62 -0
  69. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/filters.test.ts +78 -0
  70. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/graphPositionStorage.test.ts +95 -0
  71. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/host-integration.test.ts +74 -0
  72. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/index.test.ts +58 -0
  73. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/interactions.test.tsx +121 -0
  74. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/layout.test.ts +70 -0
  75. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/persistence.test.tsx +89 -0
  76. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/useGraphData.test.ts +86 -0
  77. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/useGraphInteraction.test.ts +167 -0
  78. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/useGraphPositions.test.ts +66 -0
  79. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/useNodeDrag.test.ts +81 -0
  80. package/dist/plugins/fusion-plugin-dependency-graph/src/dashboard-interop.d.ts +35 -0
  81. package/dist/plugins/fusion-plugin-dependency-graph/src/dashboard-view.tsx +19 -0
  82. package/dist/plugins/fusion-plugin-dependency-graph/src/edges.tsx +70 -0
  83. package/dist/plugins/fusion-plugin-dependency-graph/src/filters.ts +8 -0
  84. package/dist/plugins/fusion-plugin-dependency-graph/src/hooks/__tests__/useDependencyChain.test.ts +53 -0
  85. package/dist/plugins/fusion-plugin-dependency-graph/src/hooks/useDependencyChain.ts +60 -0
  86. package/dist/plugins/fusion-plugin-dependency-graph/src/hooks/useGraphPositions.ts +45 -0
  87. package/dist/plugins/fusion-plugin-dependency-graph/src/hooks/useNodeDrag.ts +114 -0
  88. package/dist/plugins/fusion-plugin-dependency-graph/src/index.ts +1 -2
  89. package/dist/plugins/fusion-plugin-dependency-graph/src/layout.ts +91 -0
  90. package/dist/plugins/fusion-plugin-dependency-graph/src/styles/drag.css +15 -0
  91. package/dist/plugins/fusion-plugin-dependency-graph/src/types.ts +21 -0
  92. package/dist/plugins/fusion-plugin-dependency-graph/src/useGraphData.ts +17 -0
  93. package/dist/plugins/fusion-plugin-dependency-graph/src/useGraphInteraction.ts +292 -0
  94. package/dist/plugins/fusion-plugin-dependency-graph/src/utils/graphPositionStorage.ts +65 -0
  95. package/dist/plugins/fusion-plugin-droid-runtime/bundled.js +136680 -0
  96. package/dist/plugins/fusion-plugin-droid-runtime/manifest.json +13 -0
  97. package/dist/plugins/fusion-plugin-droid-runtime/mcp-schema-server.cjs +49 -0
  98. package/dist/plugins/fusion-plugin-droid-runtime/package.json +11 -0
  99. package/dist/plugins/fusion-plugin-hermes-runtime/bundled.js +176 -7
  100. package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
  101. package/dist/plugins/fusion-plugin-openclaw-runtime/bundled.js +93 -6
  102. package/dist/plugins/fusion-plugin-openclaw-runtime/mcp-schema-server.cjs +59 -0
  103. package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
  104. package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
  105. package/dist/plugins/fusion-plugin-reports/manifest.json +33 -0
  106. package/dist/plugins/fusion-plugin-reports/package.json +26 -0
  107. package/dist/plugins/fusion-plugin-reports/src/__tests__/manifest.test.ts +51 -0
  108. package/dist/plugins/fusion-plugin-reports/src/__tests__/review-panel.test.ts +166 -0
  109. package/dist/plugins/fusion-plugin-reports/src/__tests__/settings.test.ts +157 -0
  110. package/dist/plugins/fusion-plugin-reports/src/index.ts +41 -0
  111. package/dist/plugins/fusion-plugin-reports/src/review-panel.ts +294 -0
  112. package/dist/plugins/fusion-plugin-reports/src/review-types.ts +75 -0
  113. package/dist/plugins/fusion-plugin-reports/src/settings.ts +105 -0
  114. package/dist/plugins/fusion-plugin-roadmap/manifest.json +16 -0
  115. package/dist/plugins/fusion-plugin-roadmap/package.json +48 -0
  116. package/dist/plugins/fusion-plugin-roadmap/src/__tests__/api-client.test.ts +101 -0
  117. package/dist/plugins/fusion-plugin-roadmap/src/__tests__/index.test.ts +92 -0
  118. package/dist/plugins/fusion-plugin-roadmap/src/__tests__/roadmap-routes.test.ts +48 -0
  119. package/dist/plugins/fusion-plugin-roadmap/src/__tests__/roadmap-suggestions.test.ts +31 -0
  120. package/dist/plugins/fusion-plugin-roadmap/src/dashboard/RoadmapsView.css +1299 -0
  121. package/dist/plugins/fusion-plugin-roadmap/src/dashboard/RoadmapsView.tsx +2559 -0
  122. package/dist/plugins/fusion-plugin-roadmap/src/dashboard/__tests__/RoadmapsView.test.tsx +1144 -0
  123. package/dist/plugins/fusion-plugin-roadmap/src/dashboard/__tests__/useRoadmaps.test.ts +1756 -0
  124. package/dist/plugins/fusion-plugin-roadmap/src/dashboard/api.ts +70 -0
  125. package/dist/plugins/fusion-plugin-roadmap/src/dashboard/test-setup.ts +7 -0
  126. package/dist/plugins/fusion-plugin-roadmap/src/dashboard/types.ts +1 -0
  127. package/dist/plugins/fusion-plugin-roadmap/src/dashboard/useConfirm.ts +8 -0
  128. package/dist/plugins/fusion-plugin-roadmap/src/dashboard/useRoadmaps.ts +1188 -0
  129. package/dist/plugins/fusion-plugin-roadmap/src/dashboard/useViewportMode.ts +20 -0
  130. package/dist/plugins/fusion-plugin-roadmap/src/dashboard-view.tsx +6 -0
  131. package/dist/plugins/fusion-plugin-roadmap/src/index.ts +74 -0
  132. package/dist/plugins/fusion-plugin-roadmap/src/roadmap-routes.ts +1 -0
  133. package/dist/plugins/fusion-plugin-roadmap/src/roadmap-schema.ts +41 -0
  134. package/dist/plugins/fusion-plugin-roadmap/src/roadmap-suggestions.d.ts +15 -0
  135. package/dist/plugins/fusion-plugin-roadmap/src/roadmap-suggestions.ts +15 -0
  136. package/dist/plugins/fusion-plugin-roadmap/src/roadmap-types.d.ts +283 -0
  137. package/dist/plugins/fusion-plugin-roadmap/src/roadmap-types.d.ts.map +1 -0
  138. package/dist/plugins/fusion-plugin-roadmap/src/roadmap-types.js +21 -0
  139. package/dist/plugins/fusion-plugin-roadmap/src/roadmap-types.js.map +1 -0
  140. package/dist/plugins/fusion-plugin-roadmap/src/roadmap-types.ts +310 -0
  141. package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-routes.d.ts +5 -0
  142. package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-routes.d.ts.map +1 -0
  143. package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-routes.js +361 -0
  144. package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-routes.js.map +1 -0
  145. package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-routes.ts +408 -0
  146. package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-suggestions.d.ts +68 -0
  147. package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-suggestions.d.ts.map +1 -0
  148. package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-suggestions.js +300 -0
  149. package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-suggestions.js.map +1 -0
  150. package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-suggestions.ts +381 -0
  151. package/dist/plugins/fusion-plugin-roadmap/src/server/index.d.ts +3 -0
  152. package/dist/plugins/fusion-plugin-roadmap/src/server/index.ts +1 -0
  153. package/dist/plugins/fusion-plugin-roadmap/src/store/__tests__/roadmap-handoff.test.ts +445 -0
  154. package/dist/plugins/fusion-plugin-roadmap/src/store/__tests__/roadmap-ordering.test.ts +334 -0
  155. package/dist/plugins/fusion-plugin-roadmap/src/store/__tests__/roadmap-store.test.ts +1318 -0
  156. package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-handoff.ts +163 -0
  157. package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-ordering.d.ts +37 -0
  158. package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-ordering.d.ts.map +1 -0
  159. package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-ordering.js +188 -0
  160. package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-ordering.js.map +1 -0
  161. package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-ordering.ts +311 -0
  162. package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-store.d.ts +299 -0
  163. package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-store.d.ts.map +1 -0
  164. package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-store.js +765 -0
  165. package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-store.js.map +1 -0
  166. package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-store.ts +1001 -0
  167. package/dist/plugins/fusion-plugin-whatsapp-chat/manifest.json +8 -0
  168. package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +34 -0
  169. package/dist/plugins/fusion-plugin-whatsapp-chat/src/__tests__/auth-state.test.ts +99 -0
  170. package/dist/plugins/fusion-plugin-whatsapp-chat/src/__tests__/connection.test.ts +145 -0
  171. package/dist/plugins/fusion-plugin-whatsapp-chat/src/__tests__/index.test.ts +216 -0
  172. package/dist/plugins/fusion-plugin-whatsapp-chat/src/__tests__/reply.test.ts +52 -0
  173. package/dist/plugins/fusion-plugin-whatsapp-chat/src/auth-state.ts +89 -0
  174. package/dist/plugins/fusion-plugin-whatsapp-chat/src/connection.ts +253 -0
  175. package/dist/plugins/fusion-plugin-whatsapp-chat/src/index.ts +262 -0
  176. package/dist/plugins/fusion-plugin-whatsapp-chat/src/qrcode.d.ts +1 -0
  177. package/dist/plugins/fusion-plugin-whatsapp-chat/src/reply.ts +37 -0
  178. package/package.json +2 -2
  179. package/skill/fusion/SKILL.md +2 -2
  180. package/skill/fusion/references/engine-tools.md +8 -2
  181. package/skill/fusion/references/extension-tools.md +39 -0
  182. package/skill/fusion/references/fusion-capabilities.md +3 -0
  183. package/dist/client/assets/AgentDetailView-BKKpbp1S.js +0 -18
  184. package/dist/client/assets/AgentDetailView-CeO_1MK7.css +0 -1
  185. package/dist/client/assets/AgentsView-BRXFmrcJ.js +0 -527
  186. package/dist/client/assets/AgentsView-Bs03ptrd.css +0 -1
  187. package/dist/client/assets/ChatView-D7L2e_qu.js +0 -1
  188. package/dist/client/assets/InsightsView-AWo5o_81.css +0 -1
  189. package/dist/client/assets/InsightsView-DvXpMKmH.js +0 -11
  190. package/dist/client/assets/NodesView-BLlfUfsy.js +0 -14
  191. package/dist/client/assets/NodesView-fXqDk9ur.css +0 -1
  192. package/dist/client/assets/PluginManager-DA_T0GHn.css +0 -1
  193. package/dist/client/assets/PluginManager-pW6RMz5z.js +0 -1
  194. package/dist/client/assets/RoadmapsView-Djc_X35v.js +0 -6
  195. package/dist/client/assets/SettingsModal-BWe0KrGY.css +0 -1
  196. package/dist/client/assets/SettingsModal-WGCF_pk8.js +0 -31
  197. package/dist/client/assets/SetupWizardModal-tG_MF_nA.js +0 -1
  198. package/dist/client/assets/agentSkills-EwIwBlG8.js +0 -1
  199. package/dist/client/assets/index-D6ebxTPF.css +0 -1
  200. package/dist/client/assets/index-DYDLmOcK.js +0 -694
  201. package/dist/plugins/fusion-plugin-dependency-graph/src/DependencyGraphView.css +0 -132
  202. package/dist/plugins/fusion-plugin-dependency-graph/src/DependencyGraphView.tsx +0 -428
  203. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/DependencyGraphView.test.tsx +0 -261
  204. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/storage.test.ts +0 -31
  205. package/dist/plugins/fusion-plugin-dependency-graph/src/storage.ts +0 -23
  206. /package/dist/client/assets/{RoadmapsView-DdGlfuu-.css → dashboard-view-DdGlfuu-.css} +0 -0
@@ -1,694 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentDetailView-BKKpbp1S.js","assets/vendor-react-K0fH_qHe.js","assets/star-BwRZmiuZ.js","assets/agentSkills-EwIwBlG8.js","assets/agentSkills-DDHJnrkn.css","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/AgentDetailView-CeO_1MK7.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/SetupWizardModal-tG_MF_nA.js","assets/DirectoryPicker-CS1dwqcC.js","assets/folder-open-BiJpmnaT.js","assets/DirectoryPicker-DzKVmxOf.css","assets/SetupWizardModal-CGYGKurR.css","assets/SettingsModal-WGCF_pk8.js","assets/SettingsModal-fxvTFLtR.js","assets/SettingsModal-BWe0KrGY.css","assets/users-DNISDtI1.js","assets/SettingsModal-BNSrO1M9.css","assets/AgentsView-BRXFmrcJ.js","assets/upload-D4NwZhPp.js","assets/AgentsView-Bs03ptrd.css","assets/DocumentsView-DmthQWDZ.js","assets/DocumentsView-BrhyOdeE.css","assets/InsightsView-DvXpMKmH.js","assets/InsightsView-AWo5o_81.css","assets/ResearchView-D9DNJYDq.js","assets/ResearchView-BzCcDAS4.css","assets/NodesView-BLlfUfsy.js","assets/NodesView-fXqDk9ur.css","assets/ChatView-D7L2e_qu.js","assets/RoadmapsView-Djc_X35v.js","assets/RoadmapsView-DdGlfuu-.css","assets/SkillsView-Ddf0YL8z.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-CPwlKnUI.js","assets/MemoryView-DiajLXby.css","assets/DevServerView-l8RCyL2k.js","assets/DevServerView-DlZpuAnj.css"])))=>i.map(i=>d[i]);
2
- import{r as i,j as t,R as rl,a as aa,g as bf,c as bx}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 xf=(...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 xx=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 vx=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 Au=e=>{const n=vx(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 Xl={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 yx=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},wx=i.createContext({}),kx=()=>i.useContext(wx),jx=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=""}=kx()??{},g=a??h?Number(s??m)*24/Number(n??u):s??m;return i.createElement("svg",{ref:d,...Xl,width:n??u??Xl.width,height:n??u??Xl.height,stroke:e??f,strokeWidth:g,className:xf("lucide",p,r),...!o&&!yx(c)&&{"aria-hidden":"true"},...c},[...l.map(([x,v])=>i.createElement(x,v)),...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 Qe=(e,n)=>{const s=i.forwardRef(({className:a,...r},o)=>i.createElement(jx,{ref:o,iconNode:n,className:xf(`lucide-${xx(Au(e))}`,`lucide-${e}`,a),...r}));return s.displayName=Au(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 Nx=[["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"}]],Gs=Qe("activity",Nx);/**
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 Sx=[["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"}]],Cx=Qe("archive-restore",Sx);/**
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 Ex=[["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"}]],Zr=Qe("archive",Ex);/**
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 _x=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],eo=Qe("arrow-down",_x);/**
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 Mx=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],fa=Qe("arrow-left",Mx);/**
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 Ax=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],to=Qe("arrow-right",Ax);/**
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 Px=[["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"}]],vf=Qe("arrow-up-down",Px);/**
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 Rx=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],oa=Qe("arrow-up",Rx);/**
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 Tx=[["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"}]],Ix=Qe("book-open",Tx);/**
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 $x=[["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"}]],zn=Qe("bot",$x);/**
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 Dx=[["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"}]],cd=Qe("box",Dx);/**
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 Lx=[["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"}]],qr=Qe("brain",Lx);/**
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 Ox=[["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"}]],yf=Qe("calendar",Ox);/**
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 Fx=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],zx=Qe("check-check",Fx);/**
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 Ux=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],ts=Qe("check",Ux);/**
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 Bx=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],un=Qe("chevron-down",Bx);/**
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 Hx=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],_l=Qe("chevron-left",Hx);/**
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 qx=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Un=Qe("chevron-right",qx);/**
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 Vx=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],pi=Qe("chevron-up",Vx);/**
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 Wx=[["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"}]],Rs=Qe("circle-alert",Wx);/**
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 Kx=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],Wn=Qe("circle-check-big",Kx);/**
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 Gx=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],Ml=Qe("circle-dot",Gx);/**
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 Jx=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]],Yx=Qe("circle-plus",Jx);/**
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 Qx=[["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"}]],dd=Qe("circle-question-mark",Qx);/**
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 Xx=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],Zx=Qe("circle-stop",Xx);/**
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 ev=[["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"}]],no=Qe("circle-x",ev);/**
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 tv=[["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"}]],nv=Qe("clipboard-list",tv);/**
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 sv=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],Oi=Qe("clock",sv);/**
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 iv=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],wf=Qe("code",iv);/**
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 av=[["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"}]],Pu=Qe("columns-3",av);/**
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 rv=[["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"}]],Wi=Qe("copy",rv);/**
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 ov=[["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"}]],kf=Qe("cpu",ov);/**
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 lv=[["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"}]],cv=Qe("download",lv);/**
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 dv=[["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"}]],uv=Qe("ellipsis-vertical",dv);/**
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 mv=[["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"}]],ud=Qe("ellipsis",mv);/**
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 hv=[["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"}]],jf=Qe("external-link",hv);/**
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 pv=[["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"}]],Qd=Qe("eye-off",pv);/**
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 fv=[["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"}]],sr=Qe("eye",fv);/**
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 gv=[["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"}]],ui=Qe("file-code",gv);/**
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 bv=[["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"}]],md=Qe("file-diff",bv);/**
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 xv=[["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"}]],vv=Qe("file-minus",xv);/**
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 yv=[["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"}]],Nf=Qe("file-pen",yv);/**
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 wv=[["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"}]],kv=Qe("file-plus",wv);/**
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 jv=[["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"}]],Nv=Qe("file-question-mark",jv);/**
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 Sv=[["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"}]],Ki=Qe("file-text",Sv);/**
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 Cv=[["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"}]],Ev=Qe("file-type",Cv);/**
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 _v=[["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"}]],Sf=Qe("file",_v);/**
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 Mv=[["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"}]],Av=Qe("flag",Mv);/**
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 Pv=[["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=Qe("folder-git-2",Pv);/**
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 Rv=[["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"}]],Ru=Qe("folder-root",Rv);/**
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 Tv=[["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"}]],ws=Qe("folder",Tv);/**
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 Iv=[["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"}]],ol=Qe("funnel",Iv);/**
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 $v=[["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"}]],Bs=Qe("git-branch",$v);/**
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 Dv=[["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"}]],so=Qe("git-commit-horizontal",Dv);/**
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 Lv=[["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"}]],Cf=Qe("git-merge",Lv);/**
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 Ov=[["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"}]],Ks=Qe("git-pull-request",Ov);/**
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 Fv=[["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"}]],Al=Qe("globe",Fv);/**
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 zv=[["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"}]],Pl=Qe("grid-3x3",zv);/**
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 Uv=[["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"}]],Rl=Qe("grip-vertical",Uv);/**
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 Bv=[["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"}]],Hv=Qe("hard-drive",Bv);/**
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 qv=[["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"}]],Vv=Qe("heart",qv);/**
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 Wv=[["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"}]],Vr=Qe("history",Wv);/**
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 Kv=[["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"}]],Ar=Qe("inbox",Kv);/**
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 Gv=[["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"}]],Ef=Qe("key",Gv);/**
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 Jv=[["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"}]],Yv=Qe("keyboard",Jv);/**
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 Qv=[["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"}]],ca=Qe("layers",Qv);/**
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 Xv=[["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"}]],Gi=Qe("layout-grid",Xv);/**
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 Zv=[["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"}]],fi=Qe("lightbulb",Zv);/**
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 ey=[["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"}]],Ha=Qe("link",ey);/**
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 ty=[["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"}]],pd=Qe("list-checks",ty);/**
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 ny=[["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"}]],sy=Qe("list-ordered",ny);/**
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 iy=[["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"}]],ay=Qe("list-plus",iy);/**
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 ry=[["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"}]],Tl=Qe("list-tree",ry);/**
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 oy=[["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"}]],fd=Qe("list",oy);/**
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 ly=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],bt=Qe("loader-circle",ly);/**
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 cy=[["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"}]],Il=Qe("lock",cy);/**
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 dy=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7",key:"132q7q"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}]],da=Qe("mail",dy);/**
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 uy=[["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"}]],gd=Qe("map",uy);/**
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 my=[["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"}]],$l=Qe("maximize-2",my);/**
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 hy=[["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"}]],py=Qe("message-square-plus",hy);/**
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 fy=[["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"}]],Di=Qe("message-square",fy);/**
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 gy=[["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"}]],io=Qe("minimize-2",gy);/**
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 by=[["path",{d:"M5 12h14",key:"1ays0h"}]],xy=Qe("minus",by);/**
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 vy=[["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"}]],qa=Qe("monitor",vy);/**
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 yy=[["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"}]],wy=Qe("move",yy);/**
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 ky=[["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"}]],jy=Qe("network",ky);/**
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 Ny=[["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"}]],bd=Qe("package",Ny);/**
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 Sy=[["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"}]],_f=Qe("paperclip",Sy);/**
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 Cy=[["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"}]],mi=Qe("pause",Cy);/**
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 Ey=[["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"}]],Cs=Qe("pencil",Ey);/**
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 _y=[["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"}]],ns=Qe("play",_y);/**
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 My=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Cn=Qe("plus",My);/**
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 Ay=[["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"}]],Py=Qe("puzzle",Ay);/**
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 Ry=[["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"}]],Mf=Qe("radio",Ry);/**
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 Ty=[["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"}]],us=Qe("refresh-cw",Ty);/**
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 Iy=[["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"}]],Tu=Qe("rocket",Iy);/**
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 $y=[["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"}]],Dy=Qe("rotate-ccw",$y);/**
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 Ly=[["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"}]],Oy=Qe("rotate-cw",Ly);/**
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 Fy=[["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"}]],Af=Qe("save",Fy);/**
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 zy=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],$i=Qe("search",zy);/**
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 Uy=[["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"}]],ra=Qe("send",Uy);/**
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 By=[["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"}]],Wr=Qe("server",By);/**
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 Hy=[["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"}]],Lr=Qe("settings",Hy);/**
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 qy=[["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"}]],Vy=Qe("shield-alert",qy);/**
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 Wy=[["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"}]],Ky=Qe("shield",Wy);/**
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 Gy=[["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"}]],Jy=Qe("skull",Gy);/**
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 Yy=[["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"}]],ys=Qe("sparkles",Yy);/**
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 Qy=[["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"}]],ll=Qe("square-check-big",Qy);/**
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 Xy=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],si=Qe("square",Xy);/**
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 Zy=[["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"}]],As=Qe("target",Zy);/**
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 ew=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],Li=Qe("terminal",ew);/**
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 tw=[["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"}]],cl=Qe("text-wrap",tw);/**
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 nw=[["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=Qe("trash-2",nw);/**
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 sw=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],iw=Qe("trending-up",sw);/**
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 aw=[["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"}]],Dl=Qe("triangle-alert",aw);/**
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 rw=[["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"}]],Iu=Qe("unlink",rw);/**
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 ow=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]],Ea=Qe("user",ow);/**
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 lw=[["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"}]],Pf=Qe("webhook",lw);/**
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 cw=[["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"}]],dl=Qe("workflow",cw);/**
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 dw=[["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"}]],$u=Qe("wrench",dw);/**
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 uw=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],en=Qe("x",uw);/**
643
- * @license lucide-react v1.7.0 - ISC
644
- *
645
- * This source code is licensed under the ISC license.
646
- * See the LICENSE file in the root directory of this source tree.
647
- */const mw=[["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"}]],ds=Qe("zap",mw),xd="fusion:version-reload",vd="fusion:version-update";let Xd=!0;function Zl(e){Xd=e}function hw(){try{if(sessionStorage.getItem(vd))return sessionStorage.removeItem(vd),!0}catch{}return!1}function Zd(e){if(sessionStorage.getItem(xd)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}if(sessionStorage.setItem(xd,"1"),!Xd){console.info("[versionCheck] auto-reload disabled by setting, skipping reload:",e);return}console.info("[versionCheck] reloading:",e),window.location.reload()}function pw(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/i.test(n)}function fw(e){return pw(e)?(Zd(`chunk load error: ${e?.message??e}`),!0):!1}async function gw(){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 bw(){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&&(Xd=!1)}catch{}}const xw=6e4;let Du=0,ec=!1;async function tc(){if(!(ec||document.visibilityState!=="visible")&&!(Date.now()-Du<xw)){Du=Date.now(),ec=!0;try{const e=await gw();if(e&&e!=="4353fc960-530ee3f1"){try{sessionStorage.setItem(vd,"1")}catch{}Zd(`build version changed: 4353fc960-530ee3f1 -> ${e}`)}}finally{ec=!1}}}function vw(){bw(),window.setTimeout(()=>sessionStorage.removeItem(xd),5e3),document.addEventListener("visibilitychange",()=>{tc()}),window.addEventListener("focus",()=>{tc()}),window.setTimeout(()=>void tc(),2e3)}class ao 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),!fw(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(Dl,{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(ao,{level:"page",onError:n,children:e})}function na({children:e,onError:n}){return t.jsx(ao,{level:"modal",onError:n,children:e})}function yw({children:e,onError:n}){return t.jsx(ao,{level:"root",onError:n,children:e})}const ww="modulepreload",kw=function(e){return"/"+e},Lu={},Rn=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=kw(u),u in Lu)return;Lu[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":ww,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)})},eu="fn.authToken",Ou="token",jw="fn_token";let Oa,Fu=!1,ul=!1;const yd="fn:auth-token-recovery-required";function Nw(){try{const e=window.localStorage.getItem(eu);return e&&e.length>0?e:void 0}catch{return}}function Rf(e){try{window.localStorage.setItem(eu,e)}catch{}}function Sw(){if(!(Fu||typeof window>"u")){Fu=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(Ou);if(!n)return;Rf(n),e.searchParams.delete(Ou);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function Va(){if(Oa!==void 0)return Oa;const e=Sw();if(e)return Oa=e,e;const n=Nw();if(n)return Oa=n,n}function Cw(e){Oa=e,ul=!1,Rf(e)}function Ew(){Oa=void 0,ul=!1;try{window.localStorage.removeItem(eu)}catch{}}function zu(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function _w(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function Mw(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!_w(e.protocol))return!1;const s=e.hostname===n.hostname,a=e.port===n.port,r=zu(e.protocol)===zu(n.protocol);return s&&a&&r}function Aw(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 Ni(e){const n=Va();if(!n||typeof window>"u")return e;const s=Aw(e);return!s||!Mw(s.parsed)?e:(s.parsed.searchParams.set(jw,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function Si(e){const n=Va();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function Pw(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function Rw(){typeof window>"u"||ul||(ul=!0,window.dispatchEvent(new CustomEvent(yd)))}async function Tw(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();Pw(a)&&Rw()}catch{}}function Iw(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,Va();const e=window.fetch.bind(window);window.fetch=function(s,a){const r=Va(),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=>(Tw(d),d))}}class Tf extends Error{status;details;constructor(n,s,a){super(n),this.name="ApiRequestError",this.status=s,this.details=a}}function $w(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function Es(e){return`/api${e}`}async function R(e,n={}){const s=Es(e),a=Va(),r=(()=>{if(a){const f=new Headers(n.headers??{});return f.has("Content-Type")||f.set("Content-Type","application/json"),Si(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")||$w(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 Tf(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function iO(){return R("/health")}function aO(){return R("/updates/check")}function Dw(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 R(`/tasks${l}`)}async function Wa(e,n){const a=Es(V(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(a,{headers:Si({"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 ml(e,n){const{title:s,description:a,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:d,modelPresetId:u,modelProvider:m,modelId:h,validatorModelProvider:f,validatorModelId:p,planningModelProvider:g,planningModelId:x,thinkingLevel:v,summarize:b,reviewLevel:k,executionMode:S,priority:j,source:E}=e;return R(V("/tasks",n),{method:"POST",body:JSON.stringify({title:s,description:a,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:d,modelPresetId:u,modelProvider:m,modelId:h,validatorModelProvider:f,validatorModelId:p,planningModelProvider:g,planningModelId:x,thinkingLevel:v,summarize:b,reviewLevel:k,executionMode:S,priority:j,source:E})})}function ki(e,n,s){return R(V(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Lw(e,n,s,a,r,o,l,c,d){return R(V("/tasks/batch-update-models",d),{method:"POST",body:JSON.stringify({taskIds:e,modelProvider:n,modelId:s,validatorModelProvider:a,validatorModelId:r,planningModelProvider:o,planningModelId:l,nodeId:c})})}function Ow(e,n,s,a){return R(V(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n,...typeof a=="object"&&a?.preserveProgress?{preserveProgress:!0}:{}})})}function Fw(e,n,s){const a=new URLSearchParams;s?.removeDependencyReferences&&a.set("removeDependencyReferences","true");const r=a.size>0?`?${a.toString()}`:"";return R(V(`/tasks/${e}${r}`,n),{method:"DELETE"})}function zw(e,n){return R(V(`/tasks/${e}/merge`,n),{method:"POST"})}function Uw(e,n){return R(V(`/tasks/${e}/retry`,n),{method:"POST"})}function Bw(e,n){return R(V(`/tasks/${e}/reset`,n),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirm:!0})})}function Hw(e,n){return R(V(`/tasks/${e}/duplicate`,n),{method:"POST"})}function If(e,n){return R(V(`/tasks/${e}/pause`,n),{method:"POST"})}function qw(e,n){return R(V(`/tasks/${e}/unpause`,n),{method:"POST"})}function Vw(e,n){return R(V(`/tasks/${e}/archive`,n),{method:"POST"})}function Ww(e,n){return R(V(`/tasks/${e}/unarchive`,n),{method:"POST"})}function Kw(e){return R(V("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function Gw(e,n){return R(V(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function Jw(e,n){return R(V(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function Yw(e){return R(V("/config",e))}function Ll(e){return R(V("/settings",e))}function jo(e,n){return R(V("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function Qw(e){return R(V("/update-check",e))}function rO(e){return R(V("/remote/settings",e))}function oO(e,n){return R(V("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function lO(e){return R(V("/remote/status",e))}function cO(e){return R(V("/remote/install-cloudflared",e),{method:"POST"})}function dO(e){return R(V("/remote/tunnel/start",e),{method:"POST"})}function uO(e){return R(V("/remote/tunnel/stop",e),{method:"POST"})}function mO(e){return R(V("/remote/tunnel/kill-external",e),{method:"POST"})}function hO(e){return R(V("/remote/token/persistent/regenerate",e),{method:"POST"})}function pO(e,n){return R(V("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function $f(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 fO(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:a}=e,r=$f(null,s,a);return R(V(`/remote/url${r}`,n))}function gO(e="text",n={}){const{projectId:s,tokenType:a="persistent",ttlMs:r}=n,o=$f(e,a,r);return R(V(`/remote/qr${o}`,s))}function bO(e){return R(V("/memory",e))}function xO(e,n){return R(V("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function vO(e){return R(V("/memory/files",e))}function yO(e,n){const s=`path=${encodeURIComponent(e)}`;return R(V(`/memory/file?${s}`,n))}function wO(e,n,s){return R(V("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function kO(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 R(V("/memory/compact",a),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function jO(e){return R(V("/memory/dream",e),{method:"POST"})}function NO(e){return R(V("/memory/insights",e))}function SO(e,n){return R(V("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function CO(e){return R(V("/memory/extract",e),{method:"POST"})}function EO(e){return R(V("/memory/audit",e))}function _O(e){return R(V("/memory/stats",e))}function MO(e){return R(V("/memory/backend",e))}function AO(e){return R(V("/memory/install-qmd",e),{method:"POST"})}function PO(e,n){return R(V("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function ga(){return R("/settings/global")}function Dn(e){return R("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function RO(e){return R(V("/settings/scopes",e))}function TO(e){return R(V("/settings/pi-extensions",e))}function IO(e,n){return R(V("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function $O(e,n,s){return R(V("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function DO(){return R("/pi-settings")}async function LO(e){return R("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function OO(e){return R("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function FO(e){return R(V("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function Ol(e,n,s){const a=new FormData;a.append("file",n);const r=await fetch(Es(V(`/tasks/${e}/attachments`,s)),{method:"POST",headers:Si(),body:a}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function Xw(e,n,s){return R(V(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function Uu(e,n,s){const a=new URLSearchParams;s?.limit!==void 0&&a.set("limit",String(s.limit)),s?.offset!==void 0&&a.set("offset",String(s.offset));const r=a.toString()?`?${a.toString()}`:"",o=V(`/tasks/${e}/logs${r}`,n),l=await fetch(Es(o),{headers:Si()});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 Zw(e,n,s,a){return R(V(`/tasks/${e}/comments/${n}`,a),{method:"PATCH",body:JSON.stringify({text:s})})}function ek(e,n,s){return R(V(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function tk(e,n){return R(V(`/tasks/${e}/documents`,n))}function nk(e,n,s){return R(V(`/tasks/${e}/documents/${n}/revisions`,s))}async function zO(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 R(V(r,n))}function UO(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const a=s.toString(),r=`/files/markdown-list${a?`?${a}`:""}`;return R(V(r,e))}function Bu(e,n,s,a,r){return R(V(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:a?.author,metadata:a?.metadata})})}function sk(e,n,s){return R(V(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function ik(e,n,s){return R(V(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function ak(e,n,s){return R(V(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function rk(e,n){return R(V(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function ok(e,n,s){return R(V(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Os(){return R("/models")}function lk(){return R("/usage")}function ck(){return R("/providers/claude-cli/status")}function dk(){return R("/system/fn-binary/status")}function uk(){return R("/system/fn-binary/install",{method:"POST"})}function mk(){return R("/providers/droid-cli/status")}function hk(){return R("/providers/llama-cpp/status")}async function BO(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return R(`/providers/hermes/status${n}`)}async function HO(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await R(`/providers/hermes/profiles${n}`)).profiles??[]}async function qO(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return R(`/providers/openclaw/status${n}`)}async function VO(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),R(`/providers/paperclip/status?${n.toString()}`)}async function WO(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),(await R(`/providers/paperclip/companies?${n.toString()}`)).companies??[]}async function KO(e){const n=new URLSearchParams({apiUrl:e.apiUrl,companyId:e.companyId});return e.apiKey&&n.set("apiKey",e.apiKey),(await R(`/providers/paperclip/agents?${n.toString()}`)).agents??[]}async function GO(e){return R("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function JO(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return R(`/providers/paperclip/cli-status${s?`?${s}`:""}`)}async function YO(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 R(`/providers/paperclip/cli-companies${s?`?${s}`:""}`)).companies??[]}async function QO(e){const n=new URLSearchParams({companyId:e.companyId});return e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath),(await R(`/providers/paperclip/cli-agents?${n.toString()}`)).agents??[]}async function XO(e={}){const n=new URLSearchParams;e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return R(`/providers/paperclip/cli-discovery${s?`?${s}`:""}`)}function pk(e){return R("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function fk(e){return R("/auth/droid-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function gk(e){return R("/auth/llama-cpp",{method:"POST",body:JSON.stringify({enabled:e})})}async function bk(){const n=(await R("/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 xk(e){return R("/custom-providers",{method:"POST",body:JSON.stringify(e)})}function ZO(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 R(`/custom-providers/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(a)})}function eF(e){return R(`/custom-providers/${encodeURIComponent(e)}`,{method:"DELETE"})}function vk(e){const n=e.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible";return xk({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 Kr(){return R("/auth/status")}function yk(e){return R("/auth/login",{method:"POST",body:JSON.stringify({provider:e,origin:window.location.origin})})}function wk(e,n){return R("/auth/manual-code",{method:"POST",body:JSON.stringify({provider:e,code:n})})}function kk(e){return R("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function jk(e){return R("/auth/cancel",{method:"POST",body:JSON.stringify({provider:e})})}function Nk(e,n){return R("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function Sk(e){return R("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function Ck(e,n,s,a){return R("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:a})})}function Ek(e,n,s,a){return R(V("/github/issues/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function _k(e,n,s){return R("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function Mk(e,n,s,a){return R(V("/github/pulls/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function Ak(e){return R(V("/git/remotes",e))}function Pk(e){return R(V("/git/remotes/detailed",e))}function Rk(e,n,s){return R(V("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function Tk(e,n){return R(V(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Ik(e,n,s){return R(V(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function $k(e,n,s){return R(V(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function Dk(e,n,s){return R(V(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function Lk(e,n){return R(V(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function Ok(e,n){return(await R(V("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function No(e,n,s,a){return R(V("/terminal/sessions",a),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function Hu(e,n){return R(V(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Fk(e){return R(V("/terminal/sessions",e))}function ci(e){return R(V("/git/status",e))}function zk(e,n){const s=e?`?limit=${e}`:"";return R(V(`/git/commits${s}`,n))}function hl(e,n){return R(V(`/git/commits/${e}/diff`,n))}function Uk(e){return R(V("/git/commits/ahead",e))}function Bk(e,n,s,a){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return R(V(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,a))}function pr(e){return R(V("/git/branches",e))}function Hk(e,n,s){const a=`?limit=${n}`;return R(V(`/git/branches/${encodeURIComponent(e)}/commits${a}`,s))}function qk(e){return R(V("/git/worktrees",e))}function Vk(e,n,s){return R(V("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function Wk(e,n){return R(V(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function qu(e,n,s){const a=n?"?force=true":"";return R(V(`/git/branches/${encodeURIComponent(e)}${a}`,s),{method:"DELETE"})}function Kk(e,n){return R(V("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function Gk(e){return R(V("/git/pull",e),{method:"POST"})}function Jk(e){return R(V("/git/push",e),{method:"POST"})}function So(e){return R(V("/git/stashes",e))}function Yk(e,n){return R(V("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function Qk(e,n,s){return R(V(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function Xk(e,n){return R(V(`/git/stashes/${e}`,n),{method:"DELETE"})}function Zk(e,n,s){const a=new URLSearchParams;return a.set("path",e),a.set("staged",String(n)),R(V(`/git/diff/file?${a.toString()}`,s))}function _a(e){return R(V("/git/changes",e))}function Vu(e,n){return R(V("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function ej(e,n){return R(V("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function Wu(e,n){return R(V("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function tj(e,n){return R(V("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function nj(e){return R(V("/workspaces",e))}function sj(e,n,s){const a=new URLSearchParams({workspace:e});return n&&a.set("path",n),s&&a.set("projectId",s),R(`/files?${a.toString()}`)}function ij(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),R(`/files/${encodeURIComponent(n)}?${a.toString()}`)}function aj(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),R(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function rj(e,n,s){const a=new URLSearchParams({q:e});return n&&a.set("workspace",n),s&&a.set("projectId",s),R(`/files/search?${a.toString()}`)}function oj(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),R(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function lj(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),R(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function cj(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),R(`/files/${encodeURIComponent(n)}/delete?${a.toString()}`,{method:"POST"})}function dj(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),R(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function Df(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${a.toString()}`}function uj(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${a.toString()}`}function mj(e,n,s){return R(V("/planning/create-draft",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function hj(e,n,s,a,r){return R(V("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId,planningDepth:a?.planningDepth,customQuestionCount:a?.customQuestionCount,...r?{existingSessionId:r}:{}})})}function Ku(e,n,s,a){return R(V("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function pj(e,n,s){return R(V(`/planning/${encodeURIComponent(e)}/back`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function fj(e,n,s){return R(V(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function gj(e,n,s){return R(V(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Lf(e,n,s){return R(V("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function tF(e,n,s,a){return R(V("/agents/onboarding/start-streaming",s),{method:"POST",body:JSON.stringify({intent:e,context:n,planningModelProvider:a?.planningModelProvider,planningModelId:a?.planningModelId})})}function nF(e,n,s){return R(V("/agents/onboarding/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n})})}function sF(e,n){return R(V("/agents/onboarding/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function bj(e,n,s){return R(V("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function xj(e,n,s){return R(V("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function vj(e,n,s){return R(V("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const wd=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(wd))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function yj(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function ir(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=yj(e,d),g=new EventSource(Ni(p));r=g,g.onopen=()=>{l=0,u=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},g.onmessage=x=>{const v=x;m(v)&&n.onMessage?.(v)};for(const[x,v]of Object.entries(n.events??{}))g.addEventListener(x,b=>{const k=b;m(k)&&v(k)});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 v=Math.min(1e3*2**(l-1),3e4);c=setTimeout(()=>{c=null,h()},v)}};h();const f={close:()=>{o=!0,c&&(clearTimeout(c),c=null),r?.close(),wd.delete(f)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return wd.add(f),f}function Gu(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 Ka(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 wj(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 kj(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((a,r)=>wj(a,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function jj(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 Ju(e){return Array.isArray(e)?e.map(Gu):(e.candidates??[]).map(Gu)}async function Nj(e){try{const n=await R(V("/dev-server/candidates",e));return Ju(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await R(V("/dev-server/detect",e));return Ju(s)}throw n}}function tu(e){return R(V("/dev-server/status",e)).then(Ka)}async function iF(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 R(V(`/dev-server/logs/history${a}`,n));return kj(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await tu(n);return jj(o.logs,e)}throw r}}function Sj(e,n){const s=e.cwd??e.packagePath??".",a=e.scriptName;return R(V("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:a,scriptId:a,cwd:s,packagePath:e.packagePath})}).then(Ka)}function Cj(e){return R(V("/dev-server/stop",e),{method:"POST"}).then(Ka)}function Ej(e){return R(V("/dev-server/restart",e),{method:"POST"}).then(Ka)}async function _j(e,n){const s=typeof e=="string"?{url:e}:e;try{const a=await R(V("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return Ka(a)}catch(a){if(a instanceof Error&&/\/dev-server\/preview-url/.test(a.message)){const r=await R(V("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return Ka(r)}throw a}}function aF(e){return Es(V("/dev-server/logs/stream",e))}async function rF(e){try{return(await R(V("/devserver",e))).sessions??[]}catch{try{const n=await tu(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 oF(e,n){try{return await R(V(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await tu(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 lF(e,n){try{return await R(V(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await Sj({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 cF(e,n){try{return await R(V(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await Cj(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 dF(e,n){try{return await R(V(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await Ej(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 uF(e,n,s){try{const a=await R(V(`/devserver/${encodeURIComponent(e)}/preview`,s),{method:"POST",body:JSON.stringify({url:n})});return{url:a.url??null,source:a.source??null}}catch{const a=await _j({url:n},s);return{url:a.previewUrl??a.manualUrl??null,source:"manual"}}}async function mF(e){try{return(await R(V("/devserver/detect",e))).candidates??[]}catch{try{return(await Nj(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function hF(e,n){return Es(V(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function ro(e,n,s=25e3){const a=setInterval(()=>{j1(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(a)}}}function Mj(e,n){return Es(V(`/planning/${encodeURIComponent(e)}/stream`,n))}function Aj(e,n){return Es(V(`/agents/onboarding/${encodeURIComponent(e)}/stream`,n))}function pF(e,n,s,a){const r=Aj(e,n),o=ir(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 Pj(e,n,s,a){const r=Mj(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},d=ir(r,{onOpen:()=>{c(),o=ro(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 oo(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 Rj(e){return R(oo("/routines",e))}function Tj(e,n){return R(oo("/routines",n),{method:"POST",body:JSON.stringify(e)})}function Yu(e,n,s){return R(oo(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function Ij(e,n){await R(oo(`/routines/${e}`,n),{method:"DELETE"})}function $j(e,n){return R(oo(`/routines/${e}/trigger`,n),{method:"POST"})}function Qu(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 R(`/activity${s}`)}function Dj(e){const n=V("/activity",e);return R(n,{method:"DELETE"})}function lo(e){return R(V("/workflow-steps",e))}function Xu(e,n){return R(V("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function Lj(e,n,s){return R(V(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Oj(e,n){return R(V(`/workflow-steps/${e}`,n),{method:"DELETE"})}function Zu(e,n){return R(V(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function Fj(e,n){return R(V(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function zj(){return R("/workflow-step-templates")}function Uj(){return R("/plugin-workflow-step-templates")}function Bj(e,n){return R(V(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function Gr(e){return R(V("/scripts",e))}function Hj(e,n,s){return R(V("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function qj(e,n){return R(V(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function Of(e,n,s){return(await R(V("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const Co={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 Ff(e){if(!(e instanceof Error))return Co.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?Co.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?Co.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:Co.NETWORK}function Vj(e,n){return R(V("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function Wj(e,n,s){return R(V(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Kj(e,n){return Es(V(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function Gj(e,n,s,a){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=ir(Kj(e,n),{onOpen:()=>{l(),r=ro(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 Jj(e,n,s,a){return R(V("/subtasks/create-tasks",a),{method:"POST",body:JSON.stringify({sessionId:e,parentTaskId:s,subtasks:n.map(r=>({tempId:r.id,title:r.title,description:r.description,size:r.suggestedSize,dependsOn:r.dependsOn}))})})}function zf(e,n,s){return R(V("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function V(e,n){if(!n)return e;const s=e.includes("?")?"&":"?";return`${e}${s}projectId=${encodeURIComponent(n)}`}function Yj(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 Fl(e,n){const{nodeId:s,localNodeId:a,...r}=n??{},o=Yj(e,s,a);return R(o,r)}function ba(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 R(`/agents${a}`)}function kd(e,n){return R(V(`/agents/${encodeURIComponent(e)}`,n))}function Qj(e,n){return R(V("/agents",n),{method:"POST",body:JSON.stringify(e)})}function Xj(e,n,s){return R(V(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function fF(e,n,s){const a=new FormData;a.append("file",n);const r=await fetch(Es(V(`/agents/${encodeURIComponent(e)}/avatar`,s)),{method:"POST",headers:Si(),body:a}),o=await r.json();if(!r.ok)throw new Error(o.error||"Avatar upload failed");return o}function gF(e,n){return R(V(`/agents/${encodeURIComponent(e)}/avatar`,n),{method:"DELETE"})}function bF(e,n){return R(V(`/agents/${encodeURIComponent(e)}/upgrade-heartbeat-procedure`,n),{method:"POST"})}function xF(e,n,s){return R(V(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function vF(e,n,s){return R(V(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function yF(e,n,s){return R(V(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function wF(e,n){return R(V(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function kF(e,n,s){const a=`path=${encodeURIComponent(n)}`;return R(V(`/agents/${encodeURIComponent(e)}/memory/file?${a}`,s))}function jF(e,n,s,a){return R(V(`/agents/${encodeURIComponent(e)}/memory/file`,a),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function Zj(e,n,s){return R(V(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function eN(e,n){return R(V(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function NF(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 R(`/agents/${encodeURIComponent(e)}/runs${r}`)}function SF(e,n,s){return R(V(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function CF(e,n,s){return R(V(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function EF(e,n,s){const a=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return R(V(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:a,triggerDetail:r})})}function _F(e,n){return R(V(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function tN(e){return R(V("/agents/stats",e))}function MF(e,n){return R(V(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function AF(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const a=s.toString();return R(`/agents/org-tree${a?`?${a}`:""}`)}function PF(e,n){return R(V(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function em(e,n,s){return R(V(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function RF(e,n){return R(V(`/agents/${encodeURIComponent(e)}/tasks`,n))}function TF(){return R("/agents/companies")}function IF(e,n){return R(V("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function $F(e,n){return R(V("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function DF(e,n){return R(V(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function LF(e){return R(V("/backups",e))}function OF(e){return R(V("/backups",e),{method:"POST"})}function FF(e,n){const s=V("/settings/export",n),a=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return R(a)}function zF(e,n,s){return R(V("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function tm(){return R("/projects/across-nodes")}function Or(e,n){R("/_perf/dashboard-load",{method:"POST",body:JSON.stringify({source:e,message:n})}).catch(()=>{})}function pl(){return R("/nodes")}function UF(){return R("/docker/nodes")}function BF(e){return R(`/docker/nodes/${encodeURIComponent(e)}/container-status`)}function HF(e,n){const s=new URLSearchParams;typeof n?.tail=="number"&&s.set("tail",String(n.tail));const a=s.size>0?`?${s.toString()}`:"";return R(`/docker/nodes/${encodeURIComponent(e)}/logs${a}`)}function qF(e){return R("/docker-nodes",{method:"POST",body:JSON.stringify(e)})}function nN(e){return R("/nodes",{method:"POST",body:JSON.stringify(e)})}function sN(e,n){return R(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function iN(e){return R(`/nodes/${encodeURIComponent(e)}/docker-config`)}function aN(e,n){return R(`/nodes/${encodeURIComponent(e)}/docker-config`,{method:"PATCH",body:JSON.stringify(n)})}function rN(e){return R(`/nodes/${encodeURIComponent(e)}/docker-config/diff`)}function oN(e){return R(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function lN(e){const n=await R(`/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 VF(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=Va();l&&o.set("fn_token",l);const c=o.toString(),d=`/browse-directory${c?`?${c}`:""}`;return R(d)}function cN(e){return R("/projects",{method:"POST",body:JSON.stringify(e)})}function Uf(e){return R(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function nm(e){return R(`/projects/${encodeURIComponent(e)}/health`)}function dN(e){return R(V("/executor/stats",e))}function uN(e){return R(V("/system-stats",e))}function mN(e){return R(V("/kill-vitest",e),{method:"POST"})}function sm(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 R(`/activity-feed${s}`)}function hN(e){return R(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function pN(e){return R(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function WF(){return R("/global-concurrency")}function KF(e){return R("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function fN(e,n){return R(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function Bf(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 R(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function gN(e){return R(V("/missions",e))}function bN(e,n){return R(V("/missions",n),{method:"POST",body:JSON.stringify(e)})}function Hf(e,n){return R(V(`/missions/${encodeURIComponent(e)}`,n))}function xN(e,n,s){return R(V(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function vN(e,n){return R(V(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function yN(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 R(V(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function wN(e){return R(V("/missions/health",e))}function kN(e,n,s){return R(V(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function jN(e,n,s){return R(V(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function NN(e,n){return R(V(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function SN(e,n,s){return R(V(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function CN(e,n,s){return R(V(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function EN(e,n){return R(V(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function _N(e,n){return R(V(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function MN(e,n,s){return R(V(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function AN(e,n,s){return R(V(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function PN(e,n){return R(V(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function RN(e,n,s){return R(V(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function TN(e,n){return R(V(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function IN(e,n,s,a){return R(V(`/missions/features/${encodeURIComponent(e)}/triage`,a),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function $N(e,n){return R(V(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST"})}function nc(e,n){return R(V(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function DN(e,n,s){return R(V(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function LN(e,n,s){return R(V(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function ON(e,n,s){return R(V(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function FN(e,n,s){return R(V(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function zN(e,n){return R(V(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function sc(e,n){return R(V(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function im(e,n){return R(V(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function UN(e,n){return R(V(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function am(e,n){return R(V(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function BN(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 R(V(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function HN(e,n){return R(V(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function qN(e,n){return R(V(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function VN(e,n){return R(V(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function WN(e,n){return R(V(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function KN(e,n,s){return R(V(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function GN(e,n,s){return R(V("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function JN(e,n,s,a){return R(V("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function YN(e,n,s){return R(V(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function qf(e,n,s){return R(V("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function QN(e,n,s){return R(V("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function XN(e,n,s,a){const r=Es(V(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=ir(r,{onOpen:()=>{c(),o=ro(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 co(e,n,s){return V(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function uo(e,n,s){return V(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function ZN(e,n){return R(co(e,"/start",n),{method:"POST"})}function e1(e,n,s,a){return R(co(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function t1(e,n,s,a){const r=Es(co(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=ir(r,{onOpen:()=>{c(),o=ro(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 n1(e,n,s){return R(co(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function s1(e,n){return R(co(e,"/skip",n),{method:"POST"})}function i1(e,n){return R(uo(e,"/start",n),{method:"POST"})}function a1(e,n,s,a){return R(uo(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function r1(e,n,s,a){const r=Es(uo(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=ir(r,{onOpen:()=>{c(),o=ro(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 o1(e,n,s){return R(uo(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function l1(e,n){return R(uo(e,"/skip",n),{method:"POST"})}async function c1(e,n){try{return await R(V(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function GF(e){return R(V("/roadmaps",e))}function JF(e,n){return R(V("/roadmaps",n),{method:"POST",body:JSON.stringify(e)})}function YF(e,n){return R(V(`/roadmaps/${encodeURIComponent(e)}`,n))}function QF(e,n,s){return R(V(`/roadmaps/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function XF(e,n){return R(V(`/roadmaps/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ZF(e,n,s){return R(V(`/roadmaps/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function e3(e,n,s){return R(V(`/roadmaps/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function t3(e,n){return R(V(`/roadmaps/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function n3(e,n,s){return R(V(`/roadmaps/milestones/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function s3(e,n,s){return R(V(`/roadmaps/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function i3(e,n){return R(V(`/roadmaps/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function a3(e,n,s){return R(V(`/roadmaps/${encodeURIComponent(e)}/milestones/reorder`,s),{method:"POST",body:JSON.stringify({orderedMilestoneIds:n})})}function r3(e,n,s){return R(V(`/roadmaps/milestones/${encodeURIComponent(e)}/features/reorder`,s),{method:"POST",body:JSON.stringify({orderedFeatureIds:n})})}function o3(e,n,s,a){return R(V(`/roadmaps/features/${encodeURIComponent(e)}/move`,a),{method:"POST",body:JSON.stringify({targetMilestoneId:n,targetIndex:s})})}function l3(e,n){return R(V(`/roadmaps/${encodeURIComponent(e)}/handoff`,n))}function c3(e,n,s,a){return R(V(`/roadmaps/${encodeURIComponent(e)}/suggestions/milestones`,a),{method:"POST",body:JSON.stringify({goalPrompt:n.trim(),...s!==void 0?{count:s}:{}})})}function d3(e,n,s){return R(V(`/roadmaps/milestones/${encodeURIComponent(e)}/suggestions/features`,s),{method:"POST",body:JSON.stringify({...n?.prompt!==void 0?{prompt:n.prompt.trim()}:{},...n?.count!==void 0?{count:n.count}:{}})})}function d1(e){return R(V("/todos",e))}function u1(e,n){const s={title:e};return R(V("/todos",n),{method:"POST",body:JSON.stringify(s)})}function m1(e,n,s){const a={title:n};return R(V(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function h1(e,n){return R(V(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function p1(e,n,s){const a={text:n};return R(V(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(a)})}function f1(e,n,s){const a=n;return R(V(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function g1(e,n){return R(V(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function b1(e,n,s){return R(V(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function Ga(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function nu(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(Es(`/ai-sessions${a?`?${a}`:""}`),{headers:Si()});return r.ok?(await r.json()).sessions??[]:[]}async function x1(e){return R(`/ai-sessions/${encodeURIComponent(e)}/archive`,{method:"POST"})}async function v1(e){return R(`/ai-sessions/${encodeURIComponent(e)}/unarchive`,{method:"POST"})}async function ji(e){const n=await fetch(Es(`/ai-sessions/${encodeURIComponent(e)}`),{headers:Si()});return n.ok?n.json():null}async function y1(e,n){const s=await R(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function w1(e,n){return R(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function k1(e,n){return R(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function Vf(e){await fetch(Es(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:Si()})}function j1(e,n){return R(V(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function N1(e,n,s){return R(V(`/ai-sessions/${encodeURIComponent(e)}/draft`,s),{method:"PATCH",body:JSON.stringify(n)})}function S1(e,n){return R(V(`/planning/${encodeURIComponent(e)}/summarize-draft-title`,n),{method:"POST"})}function C1(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 R(`/messages/inbox${a}`)}function E1(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 R(`/messages/outbox${a}`)}function Wf(e){return R(V("/messages/unread-count",e))}function _1(e,n){return R(V("/messages",n),{method:"POST",body:JSON.stringify(e)})}function M1(e,n){return R(V(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function A1(e){return R(V("/messages/read-all",e),{method:"POST"})}function P1(e,n){return R(V(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function R1(e,n,s){const a=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return R(V(a,s))}function T1(e,n){return R(V(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function u3(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 R(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function m3(e,n){return R(V(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function h3(e,n,s){const a=new URLSearchParams;s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return R(`/agents/${encodeURIComponent(e)}/performance${r}`)}function p3(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 R(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function f3(e,n,s){return R(V(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function g3(e,n){return R(V(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function b3(e,n,s){return R(V(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function x3(e,n){return R(V(`/agents/${encodeURIComponent(e)}/budget`,n))}function v3(e,n){return R(V(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function y3(e){return R(V("/plugins",e))}async function w3(e,n){return R(V("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function k3(e,n){return R(V(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function j3(e,n){return R(V(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function N3(e,n){return R(V(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function S3(e,n){return R(V(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function C3(e,n,s){return R(V(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function E3(e,n){return R(V(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function I1(e){return R(V("/plugins/ui-slots",e))}async function $1(e){return R(V("/plugins/dashboard-views",e))}async function _3(e){return R(V("/plugins/runtimes",e))}async function D1(e){return(await R(V("/skills/discovered",e))).skills}async function M3(e,n,s){return R(V("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function A3(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 R(V(`/skills/catalog${r}`,s))}async function P3(e,n){return(await R(V(`/skills/${encodeURIComponent(e)}/content`,n))).content}function rm(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const a=s.toString();return R(`/chat/sessions${a?`?${a}`:""}`)}async function L1(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 R(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function O1(e,n){return R(V("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function F1(e,n){return R(V(`/chat/sessions/${encodeURIComponent(e)}`,n))}function R3(e,n,s){return R(V(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function T3(e,n){return R(V(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ic(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 R(V(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function z1(e,n){return R(V(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function U1(e,n,s,a,r,o){const l=Es(V(`/chat/sessions/${encodeURIComponent(e)}/messages`,r)),c=new AbortController;let d=!1;const u=(m,h)=>{if(m)switch(m){case"thinking":try{s.onThinking?.(JSON.parse(h))}catch{s.onThinking?.(h)}break;case"text":try{s.onText?.(JSON.parse(h))}catch{s.onText?.(h)}break;case"tool_start":try{s.onToolStart?.(JSON.parse(h))}catch{}break;case"tool_end":try{s.onToolEnd?.(JSON.parse(h))}catch{}break;case"fallback":try{s.onFallback?.(JSON.parse(h))}catch{}break;case"done":try{const f=JSON.parse(h);s.onDone?.({messageId:typeof f.messageId=="string"?f.messageId:"",...f.message&&typeof f.message=="object"?{message:f.message}:{}})}catch{s.onDone?.({messageId:""})}break;case"error":try{const f=JSON.parse(h);s.onError?.(f.message||f)}catch{s.onError?.(h||"Stream error")}break}};return(async()=>{try{const m=Array.isArray(a)&&a.length>0,h=m?(()=>{const S=new FormData;return S.append("content",n),a.forEach(j=>S.append("attachments",j)),S})():JSON.stringify({content:n}),f=await fetch(l,{method:"POST",headers:m?Si():Si({"Content-Type":"application/json"}),body:h,signal:c.signal});if(!f.ok){const S=await f.text();let j=`Request failed: ${f.status}`;try{j=JSON.parse(S).error||j}catch{}s.onError?.(j);return}if(!f.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected");const p=f.body.getReader(),g=new TextDecoder;let x="",v="",b=[];const k=(S,j=!1)=>{x+=S;const E=x.split(`
648
- `);x=E.pop()||"",j&&x.length>0&&(E.push(x),x="");for(const y of E){const N=y.endsWith("\r")?y.slice(0,-1):y;if(N.startsWith("event:"))v=N.slice(6).trim();else if(N.startsWith("data:")){const M=N.slice(5);b.push(M.startsWith(" ")?M.slice(1):M)}else if(N===""){const M=b.join(`
649
- `);u(v,M),v="",b=[]}}if(j&&v&&b.length>0){const y=b.join(`
650
- `);u(v,y),v="",b=[]}};for(;;){const{done:S,value:j}=await p.read();if(S){k(g.decode(),!0);break}k(g.decode(j,{stream:!0}))}}catch(m){if(m instanceof DOMException&&m.name==="AbortError"){d||s.onError?.("Connection aborted");return}if(d)return;s.onError?.(m instanceof Error?m.message:"Connection error")}})(),{close:()=>{d=!0,c.abort()},isConnected:()=>!d}}function I3(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 R(V(`/insights${a}`,n))}function $3(e,n){return R(V(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function D3(e,n){return R(V(`/insights/${encodeURIComponent(e)}/archive`,n),{method:"POST"})}function L3(e,n){return R(V(`/insights/${encodeURIComponent(e)}/unarchive`,n),{method:"POST"})}function O3(e="manual",n,s){return R(V("/insights/run",s),{method:"POST",body:JSON.stringify({trigger:e,inputMetadata:n})})}function F3(e){return R(V("/insights/runs",e))}function z3(e,n){return R(V(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function U3(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 R(V(`/research/runs${a}`,n))}function B3(e,n){return R(V("/research/runs",n),{method:"POST",body:JSON.stringify(e)})}function H3(e,n){return R(V(`/research/runs/${encodeURIComponent(e)}`,n))}function Kf(e){if(e instanceof Tf){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 q3(e,n){try{return await R(V(`/research/runs/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}catch(s){Kf(s)}}async function V3(e,n){try{return await R(V(`/research/runs/${encodeURIComponent(e)}/retry`,n),{method:"POST"})}catch(s){Kf(s)}}function W3(e,n,s){return R(V(`/research/runs/${encodeURIComponent(e)}/export?format=${encodeURIComponent(n)}`,s))}function K3(e,n,s){const a=n.findingId??"finding-1";return R(V(`/research/runs/${encodeURIComponent(e)}/findings/${encodeURIComponent(a)}/task`,s),{method:"POST",body:JSON.stringify({title:n.title,description:n.description,priority:n.priority,attachExport:n.attachExport})})}function G3(e,n,s){const a=n.findingId??"finding-1";return R(V(`/research/runs/${encodeURIComponent(e)}/findings/${encodeURIComponent(a)}/tasks/${encodeURIComponent(n.taskId)}/enrich`,s),{method:"POST",body:JSON.stringify({attachExport:n.attachExport})})}function B1(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 H1({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}=B1(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 q1(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ua({status:e,showLabel:n=!1,className:s,compact:a=!1}){const r=q1(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 om=new Map,V1=6e4;function Gf(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=om.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 I1(e);if(h||d.current)return;om.set(m,{slots:x,expiresAt:Date.now()+V1}),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 lm({size:e,color:n,label:s="llama.cpp"}){return t.jsx(kf,{size:e,color:n,"aria-label":s,"data-testid":"llama-cpp-icon"})}const W1={sm:16,md:20,lg:24};function K1({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 cm({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 xi({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 G1({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 dm({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 J1({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 ac({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 um({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 mm({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 hm({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 fr({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 pm({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 fm({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 oc({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 Y1({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 Q1({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 gm({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 lc({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 X1({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 bm({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 cc({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 xm({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 dc({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 vm({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 Z1({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"})]})}const eS={anthropic:{component:K1,color:"var(--provider-anthropic)"},"claude-cli":{component:vm,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:vm,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"droid-cli":{component:Z1,color:"var(--provider-openai)",label:"Factory AI — via Droid CLI"},"llama-cpp":{component:lm,color:"var(--provider-ollama)",label:"llama.cpp"},"llama-server":{component:lm,color:"var(--provider-ollama)",label:"llama.cpp"},openai:{component:cm,color:"var(--provider-openai)"},"openai-codex":{component:cm,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:xi,color:"var(--provider-gemini)"},gemini:{component:xi,color:"var(--provider-gemini)"},"google-antigravity":{component:xi,color:"var(--provider-gemini)",label:"Google Gemini"},antigravity:{component:xi,color:"var(--provider-gemini)",label:"Google Gemini"},"google-vertex":{component:xi,color:"var(--provider-gemini)",label:"Google Vertex AI"},vertex:{component:xi,color:"var(--provider-gemini)",label:"Google Vertex AI"},"google-cloud-code":{component:xi,color:"var(--provider-gemini)",label:"Google Cloud Code"},"cloud-code":{component:xi,color:"var(--provider-gemini)",label:"Google Cloud Code"},"google-gemini-cli":{component:xi,color:"var(--provider-gemini)",label:"Google Gemini CLI"},"google-generative-ai":{component:xi,color:"var(--provider-gemini)",label:"Google Generative AI"},ollama:{component:G1,color:"var(--text)"},github:{component:bm,color:"var(--text)"},"github-copilot":{component:bm,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:X1,color:"var(--provider-openrouter)"},minimax:{component:dm,color:"var(--provider-minimax)"},"minimax-cn":{component:dm,color:"var(--provider-minimax)",label:"MiniMax (CN)"},zai:{component:J1,color:"var(--provider-zai)"},kimi:{component:ac,color:"var(--provider-kimi)"},moonshot:{component:ac,color:"var(--provider-kimi)"},"kimi-coding":{component:ac,color:"var(--provider-kimi)",label:"Kimi"},bedrock:{component:um,color:"var(--provider-bedrock)"},"amazon-bedrock":{component:um,color:"var(--provider-bedrock)",label:"Amazon Bedrock"},xai:{component:mm,color:"var(--text)"},grok:{component:mm,color:"var(--text)",label:"xAI"},opencode:{component:hm,color:"var(--provider-opencode)"},"opencode-go":{component:hm,color:"var(--provider-opencode)",label:"Opencode (Go)"},qwen:{component:fr,color:"var(--provider-qwen)"},"qwen-ai":{component:fr,color:"var(--provider-qwen)",label:"Qwen"},"qwen-coder":{component:fr,color:"var(--provider-qwen)",label:"Qwen Coder"},alibaba:{component:fr,color:"var(--provider-qwen)",label:"Qwen"},tongyi:{component:fr,color:"var(--provider-qwen)",label:"Qwen"},lmstudio:{component:pm,color:"var(--provider-lmstudio)",label:"LM Studio"},"lm-studio":{component:pm,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:fm,color:"var(--provider-mistral)",label:"Mistral AI"},"mistral-ai":{component:fm,color:"var(--provider-mistral)",label:"Mistral AI"},azure:{component:oc,color:"var(--provider-azure)"},"azure-openai":{component:oc,color:"var(--provider-azure)",label:"Azure OpenAI"},"azure-openai-responses":{component:oc,color:"var(--provider-azure)",label:"Azure OpenAI"},fireworks:{component:lc,color:"var(--provider-fireworks)",label:"Fireworks AI"},"fireworks-ai":{component:lc,color:"var(--provider-fireworks)",label:"Fireworks AI"},fireworksai:{component:lc,color:"var(--provider-fireworks)",label:"Fireworks AI"},cerebras:{component:Y1,color:"var(--provider-cerebras)"},groq:{component:Q1,color:"var(--provider-groq)"},vercel:{component:gm,color:"var(--provider-vercel)"},"vercel-ai-gateway":{component:gm,color:"var(--provider-vercel)",label:"Vercel AI Gateway"},hermes:{component:cc,color:"var(--provider-hermes)",label:"Hermes"},"hermes-agent":{component:cc,color:"var(--provider-hermes)",label:"Hermes"},hermesagent:{component:cc,color:"var(--provider-hermes)",label:"Hermes"},openclaw:{component:xm,color:"var(--provider-openclaw)",label:"OpenClaw"},"open-claw":{component:xm,color:"var(--provider-openclaw)",label:"OpenClaw"},paperclip:{component:dc,color:"var(--provider-paperclip)",label:"Paperclip"},paperclipai:{component:dc,color:"var(--provider-paperclip)",label:"Paperclip"},"paperclip-ai":{component:dc,color:"var(--provider-paperclip)",label:"Paperclip"}};function Kn({provider:e,size:n="sm"}){const s=e.toLowerCase(),a=eS[s],r=a?.component,o=a?.color??"var(--text-muted)",l=a?.label,c=W1[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(kf,{size:c})})}function Jf({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 mk();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 k=await fk(b);u.current&&d({kind:k.enabled?"enabled":"disabled",restartRequired:k.restartRequired}),n?.(k.enabled),await m()}catch(k){u.current&&d({kind:"error",message:k instanceof Error?k.message:String(k)})}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."]}),v=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(bt,{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(Kn,{provider:"droid-cli",size:"sm"}),t.jsx("strong",{children:"Factory AI — via Droid CLI"}),t.jsx(tS,{status:a,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:v})]}),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(ym,{status:a,authenticated:e}),c&&t.jsx(wm,{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(Kn,{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(ym,{status:a,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(wm,{action:c})]})}function tS({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 ym({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(bt,{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 wm({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 km({actions:e}){return t.jsx(Jf,{compact:!0,authenticated:!1,onToggled:()=>{e?.refreshAuthProviders?.()}})}function nS({actions:e}){return t.jsx(Jf,{authenticated:!1,onToggled:()=>{e?.refreshAuthProviders?.()}})}function sS(){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 iS({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 aS=[{pluginId:"fusion-plugin-droid-runtime",slotId:"settings-provider-card",componentPath:"./components/settings-provider-card.js",component:km},{pluginId:"fusion-plugin-droid-runtime",slotId:"settings-integration-card",componentPath:"./components/settings-integration-card.js",component:km},{pluginId:"fusion-plugin-droid-runtime",slotId:"onboarding-provider-card",componentPath:"./components/onboarding-provider-card.js",component:nS},{pluginId:"fusion-plugin-droid-runtime",slotId:"onboarding-setup-help",componentPath:"./components/onboarding-setup-help.js",component:sS},{pluginId:"fusion-plugin-droid-runtime",slotId:"post-onboarding-recommendation",componentPath:"./components/post-onboarding-recommendation.js",component:iS}];function rS(e){return aS.find(s=>s.pluginId===e.pluginId&&s.slotId===e.slot.slotId&&s.componentPath===e.slot.componentPath)?.component??null}function oS({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 qi({slotId:e,projectId:n,pluginIds:s,renderPlaceholder:a=!0,actions:r}){const{getSlotsForId:o,loading:l,error:c}=Gf(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(ao,{level:"page",children:t.jsx(t.Fragment,{children:d.map((u,m)=>{const h=`${u.pluginId}-${u.slot.slotId}-${m}`,f=rS(u);return f?t.jsx(f,{entry:u,actions:r},h):a?t.jsx(oS,{slotId:u.slot.slotId,pluginId:u.pluginId},h):null})})})}function lS(){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 oi(){const[e,n]=i.useState(lS);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 su(e){return e.replace(/[\\/]+$/g,"")}function iu(e){const n=ar(su(e));return n?n.split("/").filter(Boolean):[]}function au(e){const n=ar(su(e));if(!n)return e;const s=n.split("/").filter(Boolean);return s[s.length-1]||n}function Yf(e,n){const s=iu(e);return s.length===0?ar(e):s.slice(-2).join("/")}function cS(e){const n=ar(su(e)),s=n.lastIndexOf("/");return s<0?"":n.slice(0,s+1)}function dS(e,n){return!e||e==="."?n:[...iu(e),n].join("/")}function uS(e){const n=iu(e);return n.length===0?".":(n.pop(),n.length===0?".":n.join("/"))}function J3(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 mS=new Map;function Qf(e,n){return`plugin:${e}:${n}`}function Xf(e){const n=/^plugin:([^:]+):(.+)$/u.exec(e);return n?{pluginId:n[1],viewId:n[2]}:null}function za(e){return Xf(e)!==null}function hS(e,n){return mS.get(Qf(e,n))??null}function uc({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(Dl,{}),"Plugin view unavailable"]}),t.jsxs("p",{className:"plugin-dashboard-view-missing-description",children:["No host registration found for ",t.jsx("code",{children:e}),"."]})]})}function pS({viewId:e}){const n=Xf(e);if(!n)return t.jsx(uc,{viewId:e});const s=hS(n.pluginId,n.viewId);return s?t.jsx(ao,{fallback:t.jsx(uc,{viewId:e}),children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(s,{})})}):t.jsx(uc,{viewId:e})}const Fr=Qf,fS={activity:Gs,bot:zn,brain:qr,checksquare:ll,clock:Oi,filetext:Ki,folder:ws,gitbranch:Bs,grid3x3:Pl,layoutgrid:Gi,mail:da,map:gd,messagesquare:Di,monitor:qa,search:$i,sparkles:ys,target:As,workflow:dl,zap:ds};function gS(e){return(e??"").trim().toLowerCase().replace(/[-_\s]/g,"")}function fl(e){return fS[gS(e)]??Pl}const Zf={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function bS({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=Zf[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:Yf(d.path)})]}),u&&t.jsx(ts,{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 jm({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 xS({onOpenSettings:e,onOpenGitHubImport:n,onOpenPlanning:s,onResumePlanning:a,activePlanningSessionCount:r=0,onOpenUsage:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:d,mailboxUnreadCount:u=0,onOpenSchedules:m,onOpenGitManager:h,onOpenNodes:f,showNodesButton:p,onOpenWorkflowSteps:g,onOpenScripts:x,onRunScript:v,onToggleTerminal:b,onOpenFiles:k,filesOpen:S,onOpenTodos:j,todosOpen:E,todosEnabled:y,globalPaused:N,enginePaused:M,onToggleGlobalPause:D,onToggleEnginePause:C,view:_="board",onChangeView:F,showSkillsTab:U,showAgentsTab:A,searchQuery:$="",onSearchChange:T,projects:J=[],currentProject:B,onSelectProject:se,onViewAllProjects:P,projectId:O,isElectron:I=!1,mobileNavEnabled:w,availableNodes:Y=[],currentNode:re,onSelectNode:le,isRemote:ve=!1,experimentalFeatures:de,pluginDashboardViews:Fe=[],shellConnectionControl:X}){const L=oi(),Q=L==="mobile",H=Q||L==="tablet",z=Q&&w,[W,we]=i.useState(!1),[Z,fe]=i.useState(!1),[Oe,Ve]=i.useState(!1),[He,Je]=i.useState(!1),[$e,he]=i.useState(!1),[ue,Ee]=i.useState(!1),[je,xe]=i.useState(!1),[Pe,ie]=i.useState(!1),[Me,We]=i.useState(!1),[mt,st]=i.useState(!1),[Ze,dt]=i.useState(!1),[Ae,Ue]=i.useState({}),[kt,De]=i.useState(!1),[be,pe]=i.useState(-1),[Re,Be]=i.useState(null),[at,me]=i.useState({}),[ft,Et]=i.useState(!1),jt=i.useRef(null),$t=i.useRef(null),Ft=i.useRef(null),Rt=i.useRef(null),It=i.useRef(null),Vt=i.useRef(null),Qt=i.useRef(!1),Jt=i.useRef(null),on=i.useRef(null),Kt=i.useRef(null),qt=i.useRef(null),kn=i.useRef(null),nn=i.useRef(null),Xt=i.useRef(null),Gt=i.useRef(null),ln=i.useRef(!1),ye=i.useMemo(()=>Y.filter(ge=>ge.type==="remote"),[Y]),Le=ye.length>0,ae=i.useMemo(()=>Object.entries(Ae).sort(([ge],[ut])=>ge.localeCompare(ut)),[Ae]),Te=ae.length>0,Ne=ae.length+(Te?1:0),ee=i.useMemo(()=>Object.entries(at).sort(([ge],[ut])=>ge.localeCompare(ut)),[at]),Ie=i.useMemo(()=>Fe.some(ge=>ge.pluginId==="fusion-plugin-roadmap"),[Fe]),St=i.useMemo(()=>!!(de?.researchView||y||de?.insights||de?.roadmap&&!Ie||U||de?.memoryView||de?.devServerView||!z||Fe.some(ge=>ge.view.placement!=="primary")),[de,y,U,z,Fe,Ie]),pt=i.useCallback(()=>{const ge=window.visualViewport;return ge&&ge.width>0&&ge.height>0?{width:ge.width,height:ge.height,offsetTop:ge.offsetTop,offsetLeft:ge.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),Dt=i.useCallback(()=>{const ge=Xt.current;if(!ge)return;const ut=ge.getBoundingClientRect(),xn=Gt.current,{width:oe,height:ct,offsetTop:rt,offsetLeft:wt}=pt(),ot=16,vt=16,Wt=6,an=xn?.offsetWidth||Math.max(ut.width,260),pn=Math.min(an,Math.max(oe-ot*2,160)),Hn=xn?.offsetHeight||280,Mn=Math.min(Hn,Math.max(ct-vt*2,160)),Qn=ut.top-rt,ms=ut.bottom-rt,Xn=ut.right-wt,mn=ct-ms,Pt=Qn,is=mn<Mn&&Pt>mn,Gn=Math.min(Math.max(Xn-pn,ot),oe-ot-pn)+wt,K=is?Math.max(vt+rt,Qn-Mn-Wt+rt):Math.min(ms+Wt+rt,ct+rt-vt-Mn);Be({top:K,left:Gn,width:pn})},[pt]),Ut=i.useCallback((ge,ut)=>{v?.(ge,ut),dt(!1),pe(-1)},[v]),Ce=i.useCallback(()=>{x?.(),dt(!1),pe(-1)},[x]),et=i.useCallback(ge=>{switch(ge.key){case"ArrowDown":ge.preventDefault(),Ne>0&&pe(ut=>ut<Ne-1?ut+1:0);break;case"ArrowUp":ge.preventDefault(),Ne>0&&pe(ut=>ut>0?ut-1:Ne-1);break;case"Enter":if(ge.preventDefault(),be>=0)if(be<ae.length){const[ut,xn]=ae[be];Ut(ut,xn)}else Te&&be===ae.length&&Ce();break;case"Home":ge.preventDefault(),Ne>0&&pe(0);break;case"End":ge.preventDefault(),Ne>0&&pe(Ne-1);break}},[Ce,Ut,be,ae,Te,Ne]);i.useEffect(()=>{Qt.current=$e},[$e]),i.useEffect(()=>{ln.current=Ze},[Ze]),i.useEffect(()=>{if(!$e||!H)return;let ge=!1;return Et(!0),Gr(O).then(ut=>{ge||me(ut)}).catch(()=>{ge||me({})}).finally(()=>{ge||Et(!1)}),()=>{ge=!0}},[$e,H,O]),i.useEffect(()=>{if(!Ze||H)return;let ge=!1;return De(!0),Gr(O).then(ut=>{ge||Ue(ut)}).catch(()=>{ge||Ue({})}).finally(()=>{ge||De(!1)}),()=>{ge=!0}},[Ze,H,O]),i.useEffect(()=>{if(!Ze)return;const ge=ut=>{nn.current&&!nn.current.contains(ut.target)&&dt(!1)};return document.addEventListener("mousedown",ge),()=>document.removeEventListener("mousedown",ge)},[Ze]),i.useEffect(()=>{if(!Ze)return;const ge=ut=>{ut.key==="Escape"&&(dt(!1),Xt.current?.focus())};return document.addEventListener("keydown",ge),()=>document.removeEventListener("keydown",ge)},[Ze]),i.useEffect(()=>{if(Ze){pe(-1);const ge=window.setTimeout(()=>Gt.current?.focus(),0);return()=>window.clearTimeout(ge)}Be(null)},[Ze]),i.useEffect(()=>{if(!Ze)return;const ge=requestAnimationFrame(()=>{Dt()});return()=>cancelAnimationFrame(ge)},[Ze,kt,ae.length,Te,Dt]),i.useEffect(()=>{if(!Ze)return;const ge=()=>Dt();window.addEventListener("resize",ge),window.addEventListener("scroll",ge,!0);const ut=window.visualViewport;return ut&&(ut.addEventListener("resize",ge),ut.addEventListener("scroll",ge)),()=>{window.removeEventListener("resize",ge),window.removeEventListener("scroll",ge,!0),ut&&(ut.removeEventListener("resize",ge),ut.removeEventListener("scroll",ge))}},[Ze,Dt]),i.useEffect(()=>{H&&(dt(!1),pe(-1))},[H]);const tt=W||$.length>0,Lt=(Z||$.length>0)&&!Oe,Zt=(_==="board"||_==="list")&&!Q&&T&&!Oe&&$.length===0,sn=(_==="board"||_==="list")&&!Q&&T;i.useEffect(()=>{$===""&&Ve(!1)},[$]),i.useEffect(()=>{if(!He)return;const ge=ut=>{$t.current&&!$t.current.contains(ut.target)&&jt.current&&!jt.current.contains(ut.target)&&Je(!1)};return document.addEventListener("mousedown",ge),()=>document.removeEventListener("mousedown",ge)},[He]),i.useEffect(()=>{if(!Me)return;const ge=ut=>{Rt.current&&!Rt.current.contains(ut.target)&&Ft.current&&!Ft.current.contains(ut.target)&&We(!1)};return document.addEventListener("mousedown",ge),()=>document.removeEventListener("mousedown",ge)},[Me]),i.useEffect(()=>{if(!ue)return;const ge=ut=>{Jt.current&&!Jt.current.contains(ut.target)&&Ee(!1)};return document.addEventListener("mousedown",ge),()=>document.removeEventListener("mousedown",ge)},[ue]),i.useEffect(()=>{const ge=ut=>{if(ut.key==="Escape"){if(ie(!1),We(!1),Qt.current){he(!1);return}if(ln.current){dt(!1),Xt.current?.focus();return}Je(!1),we(!1),Ee(!1),xe(!1)}};return document.addEventListener("keydown",ge),()=>document.removeEventListener("keydown",ge)},[]),i.useEffect(()=>{if(!je)return;const ge=ut=>{on.current&&!on.current.contains(ut.target)&&xe(!1)};return document.addEventListener("mousedown",ge),()=>document.removeEventListener("mousedown",ge)},[je]),i.useEffect(()=>{if(!mt)return;const ge=ut=>{kn.current&&!kn.current.contains(ut.target)&&st(!1)};return document.addEventListener("mousedown",ge),()=>document.removeEventListener("mousedown",ge)},[mt]),i.useEffect(()=>{if(!mt)return;const ge=ut=>{ut.key==="Escape"&&st(!1)};return document.addEventListener("keydown",ge),()=>document.removeEventListener("keydown",ge)},[mt]),i.useEffect(()=>{if(!Pe)return;const ge=ut=>{Kt.current&&!Kt.current.contains(ut.target)&&qt.current&&!qt.current.contains(ut.target)&&ie(!1)};return document.addEventListener("mousedown",ge),()=>document.removeEventListener("mousedown",ge)},[Pe]);const At=i.useCallback(()=>{we(ge=>!ge)},[]),cn=i.useCallback(()=>{fe(!0),Ve(!1)},[]),Tn=i.useCallback(()=>{fe(!1),Ve(!0),T&&T("")},[T]),En=i.useCallback(()=>{Je(ge=>!ge)},[]),bn=i.useCallback(ge=>{ge&&ge(),Je(!1),he(!1)},[]),In=i.useCallback(()=>{we(!1),T&&T("")},[T]);return t.jsxs("div",{className:"header-wrapper",children:[t.jsxs("header",{className:"header",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"})]}),Q&&J.length>=1&&se&&t.jsxs("div",{className:"mobile-project-switch",ref:on,children:[t.jsx("button",{className:`mobile-project-switch-trigger${je?" mobile-project-switch-trigger--open":""}`,onClick:()=>xe(ge=>!ge),title:"Switch project","aria-label":"Switch project","aria-expanded":je,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(un,{size:14,className:`mobile-project-switch-chevron${je?" mobile-project-switch-chevron--open":""}`})}),je&&t.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:J.map(ge=>{const ut=B?.id===ge.id,xn=Zf[ge.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${ut?" mobile-project-switch-item--current":""}`,onClick:()=>{se(ge),xe(!1)},role:"option","aria-selected":ut,"data-testid":`mobile-project-switch-item-${ge.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:xn||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:ge.name}),t.jsx("span",{className:"mobile-project-switch-path",children:Yf(ge.path)})]}),ut&&t.jsx(ts,{size:14,className:"mobile-project-switch-check"})]},ge.id)})})]}),!H&&J.length>=1&&P&&t.jsx(bS,{projects:J,currentProject:B??null,onViewAll:P,onSelectProject:se}),Le&&t.jsxs("div",{className:`header-node-selector${Q?" header-node-selector--mobile":""}`,ref:Q?void 0:Jt,children:[t.jsx(H1,{node:re??null,showDetails:!Q}),!Q&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${ue?" node-selector-trigger--open":""}`,onClick:()=>Ee(ge=>!ge),title:"Switch node","aria-label":"Switch node","aria-expanded":ue,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(Un,{size:12,className:`node-selector-chevron${ue?" node-selector-chevron--open":""}`})}),ue&&t.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[t.jsxs("button",{className:`node-selector-option${ve?"":" node-selector-option--active"}`,onClick:()=>{le?.(null),Ee(!1)},role:"option","aria-selected":!ve,"data-testid":"node-option-local",children:[t.jsx(ua,{status:"online",compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),ye.map(ge=>t.jsxs("button",{className:`node-selector-option${re?.id===ge.id?" node-selector-option--active":""}`,onClick:()=>{le?.(ge),Ee(!1)},role:"option","aria-selected":re?.id===ge.id,"data-testid":`node-option-${ge.id}`,children:[t.jsx(ua,{status:ge.status,compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:ge.name}),t.jsx("span",{className:"node-selector-option-status",children:ge.status})]},ge.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[X,z&&F&&(_==="board"||_==="list")&&t.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${_==="board"?" active":""}`,onClick:()=>F("board"),title:"Board view","aria-label":"Board view","aria-pressed":_==="board","data-testid":"mobile-view-toggle-board",children:t.jsx(Gi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${_==="list"?" active":""}`,onClick:()=>F("list"),title:"List view","aria-label":"List view","aria-pressed":_==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(fd,{size:16})})]}),T&&Q&&(z||_==="board"||_==="list")&&!tt&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:At,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx($i,{size:16})}),Zt&&t.jsx("button",{className:"btn-icon",onClick:cn,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx($i,{size:16})}),Q&&z&&o&&t.jsx("button",{className:"btn-icon",onClick:ge=>o(ge.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(Gs,{size:16})}),!z&&F&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${_==="board"?" active":""}`,onClick:()=>F("board"),title:"Board view","aria-label":"Board view","aria-pressed":_==="board",children:t.jsx(Gi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${_==="list"?" active":""}`,onClick:()=>F("list"),title:"List view","aria-label":"List view","aria-pressed":_==="list",children:t.jsx(fd,{size:16})}),A&&t.jsx("button",{className:`view-toggle-btn${_==="agents"?" active":""}`,onClick:()=>F("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":_==="agents",children:t.jsx(zn,{size:16})}),t.jsx("button",{className:`view-toggle-btn${_==="missions"?" active":""}`,onClick:()=>F("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":_==="missions",children:t.jsx(As,{size:16})}),t.jsx("button",{className:`view-toggle-btn${_==="chat"?" active":""}`,onClick:()=>F("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":_==="chat",children:t.jsx(Di,{size:16})}),t.jsx("button",{className:`view-toggle-btn${_==="documents"?" active":""}`,onClick:()=>F("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":_==="documents",children:t.jsx(Ki,{size:16})}),t.jsx("button",{className:`view-toggle-btn${_==="mailbox"?" active":""}`,onClick:()=>F("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":_==="mailbox",children:t.jsx(da,{size:16})}),Fe.filter(ge=>ge.view.placement==="primary").sort((ge,ut)=>(ge.view.order??Number.MAX_SAFE_INTEGER)-(ut.view.order??Number.MAX_SAFE_INTEGER)).map(ge=>{const ut=Fr(ge.pluginId,ge.view.viewId),xn=fl(ge.view.icon);return t.jsx("button",{className:`view-toggle-btn${_===ut?" active":""}`,onClick:()=>F(ut),title:`${ge.view.label} view`,"aria-label":`${ge.view.label} view`,"aria-pressed":_===ut,"data-testid":`view-toggle-plugin-${ge.pluginId}-${ge.view.viewId}`,children:t.jsx(xn,{size:16})},`${ge.pluginId}:${ge.view.viewId}`)}),St&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:qt,className:`view-toggle-btn${["research","skills","roadmaps","insights","memory","dev-server","devserver"].includes(_)||y&&E||za(_)?" active":""}`,onClick:()=>ie(ge=>!ge),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":Pe,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(un,{size:12})}),Pe&&t.jsxs("div",{ref:Kt,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[de?.researchView&&t.jsxs("button",{className:`view-toggle-overflow-item${_==="research"?" active":""}`,onClick:()=>{F("research"),ie(!1)},role:"menuitem","data-testid":"view-overflow-research",children:[t.jsx($i,{size:14}),t.jsx("span",{children:"Research"})]}),de?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${_==="insights"?" active":""}`,onClick:()=>{F("insights"),ie(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(ys,{size:14}),t.jsx("span",{children:"Insights"})]}),de?.roadmap&&!Ie&&t.jsx("button",{className:`view-toggle-overflow-item${_==="roadmaps"?" active":""}`,onClick:()=>{F("roadmaps"),ie(!1)},role:"menuitem","data-testid":"view-overflow-roadmaps",children:t.jsx("span",{children:"Roadmaps"})}),U&&t.jsxs("button",{className:`view-toggle-overflow-item${_==="skills"?" active":""}`,onClick:()=>{F("skills"),ie(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(ds,{size:14}),t.jsx("span",{children:"Skills"})]}),de?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${_==="memory"?" active":""}`,onClick:()=>{F("memory"),ie(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(qr,{size:14}),t.jsx("span",{children:"Memory"})]}),de?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${_==="dev-server"||_==="devserver"?" active":""}`,onClick:()=>{F("devserver"),ie(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(qa,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]}),y&&j&&t.jsxs("button",{className:`view-toggle-overflow-item${E?" active":""}`,onClick:()=>{j(),ie(!1)},role:"menuitem","data-testid":"view-overflow-todos",children:[t.jsx(ll,{size:14}),t.jsx("span",{children:"Todos"})]}),Fe.filter(ge=>ge.view.placement!=="primary").sort((ge,ut)=>(ge.view.order??Number.MAX_SAFE_INTEGER)-(ut.view.order??Number.MAX_SAFE_INTEGER)).map(ge=>{const ut=Fr(ge.pluginId,ge.view.viewId),xn=fl(ge.view.icon);return t.jsxs("button",{className:`view-toggle-overflow-item${_===ut?" active":""}`,onClick:()=>{F(ut),ie(!1)},role:"menuitem","data-testid":`view-overflow-plugin-${ge.pluginId}-${ge.view.viewId}`,children:[t.jsx(xn,{size:14}),t.jsx("span",{children:ge.view.label})]},`${ge.pluginId}:${ge.view.viewId}`)})]})]})]}),!H&&o&&t.jsx("button",{className:"btn-icon",onClick:ge=>o(ge.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"desktop-header-usage-btn",children:t.jsx(Gs,{size:16})}),!H&&c&&t.jsx("button",{className:"btn-icon",onClick:c,title:"System Stats","data-testid":"desktop-header-system-stats-btn",children:t.jsx(qa,{size:16})}),!H&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(Vr,{size:16})}),!H&&!I&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(jm,{size:16})}),!H&&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(fi,{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})]}),!H&&t.jsxs("div",{className:"terminal-split-btn",ref:nn,children:[t.jsx("button",{className:"btn-icon btn-icon--terminal terminal-split-btn__main",onClick:b,title:"Open Terminal","data-testid":"terminal-toggle-btn",children:t.jsx(Li,{size:16})}),x&&v&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"terminal-split-btn__divider"}),t.jsx("button",{ref:Xt,className:`btn-icon terminal-split-btn__chevron${Ze?" btn-icon--active":""}`,onClick:()=>dt(ge=>!ge),title:"Scripts","aria-haspopup":"listbox","aria-expanded":Ze,"aria-label":"Quick scripts","data-testid":"scripts-btn",children:t.jsx(un,{size:12,className:`quick-scripts-dropdown__trigger-chevron${Ze?" rotate":""}`})}),Ze&&t.jsx("div",{ref:Gt,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:et,"data-testid":"quick-scripts-dropdown",style:Re?{position:"fixed",top:`${Re.top}px`,left:`${Re.left}px`,width:`${Re.width}px`,right:"auto"}:void 0,children:kt?t.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[t.jsx(bt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):ae.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(Li,{size:16})}),t.jsx("p",{children:"No scripts configured"}),t.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:Ce,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:ae.map(([ge,ut],xn)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${be===xn?"highlighted":""}`,onClick:()=>Ut(ge,ut),role:"option","aria-selected":be===xn,"data-testid":`quick-script-item-${ge}`,children:[t.jsx(ns,{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:ge}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:ut,children:ut.length>50?`${ut.slice(0,50)}...`:ut})]})]},ge))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${Te&&be===ae.length?"highlighted":""}`,onClick:Ce,"data-testid":"quick-scripts-manage",children:[t.jsx(Lr,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})]}),!H&&k&&t.jsx("button",{className:`btn-icon${S?" btn-icon--active":""}`,onClick:k,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(ws,{size:16})}),!H&&y&&j&&t.jsx("button",{className:`btn-icon${E?" btn-icon--active":""}`,onClick:j,title:"Open todos","data-testid":"todos-toggle-btn",children:t.jsx(ll,{size:16})}),!H&&h&&t.jsx("button",{className:"btn-icon",onClick:h,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Bs,{size:16})}),!H&&g&&t.jsx("button",{className:"btn-icon",onClick:g,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(dl,{size:16})}),!H&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:Ft,className:"btn-icon",onClick:()=>We(ge=>!ge),title:"More actions","aria-label":"More actions","aria-expanded":Me,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(ud,{size:16})}),Me&&t.jsxs("div",{ref:Rt,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[f&&p!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{f(),We(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx(Wr,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{bn(m),We(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(Oi,{size:14}),t.jsx("span",{children:"Automation"})]})]})]}),t.jsxs("div",{className:"engine-control-split-btn",ref:kn,children:[t.jsx("button",{className:`btn-icon engine-control-split-btn__main${N?" btn-icon--stopped":""}`,onClick:D,title:N?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:N?t.jsx(ns,{size:16}):t.jsx(si,{size:16})}),t.jsx("span",{className:"engine-control-split-btn__divider"}),t.jsx("button",{className:`btn-icon engine-control-split-btn__chevron${mt?" btn-icon--active":""}`,onClick:()=>st(ge=>!ge),title:"Engine options","aria-haspopup":"menu","aria-expanded":mt,"data-testid":"engine-control-chevron-btn",children:t.jsx(un,{size:12})}),mt&&t.jsx("div",{className:"engine-control-split-btn__menu",role:"menu",children:t.jsxs("button",{className:`engine-control-split-btn__menu-item${M?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{C?.(),st(!1)},role:"menuitem",title:M?"Resume scheduling":"Pause triage",disabled:!!N,"data-testid":"engine-control-pause-triage-btn",children:[M?t.jsx(ns,{size:14}):t.jsx(mi,{size:14}),t.jsx("span",{children:M?"Resume scheduling":"Pause triage"})]})})]}),!H&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(Lr,{size:16})}),t.jsx(qi,{slotId:"header-action",projectId:O}),H&&!z&&t.jsx("button",{ref:jt,className:"btn-icon compact-overflow-trigger",onClick:En,title:"More header actions","aria-label":"More header actions","aria-expanded":He,"aria-haspopup":"menu",children:t.jsx(ud,{size:16})}),H&&!z&&He&&t.jsxs("div",{ref:$t,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[J.length>=1&&P&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>bn(P),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(Pl,{size:16}),t.jsx("span",{children:"Projects"})]}),k&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>bn(k),role:"menuitem","data-testid":"overflow-files-btn",children:[t.jsx(ws,{size:16}),t.jsx("span",{children:"Browse Files"})]}),t.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>bn(r>0&&a?a:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx(fi,{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"})]}),h&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>bn(h),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(Bs,{size:16}),t.jsx("span",{children:"Git Manager"})]}),f&&p!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>bn(f),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(Wr,{size:16}),t.jsx("span",{children:"Nodes"})]}),!I&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>bn(n),role:"menuitem",children:[t.jsx(jm,{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:()=>bn(b),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[t.jsx(Li,{size:16}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>he(ge=>!ge),role:"menuitem","aria-expanded":$e,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(Un,{size:14,className:`mobile-overflow-chevron${$e?" mobile-overflow-chevron--open":""}`})})]}),$e&&t.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:ft?t.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[t.jsx(bt,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):ee.length>0?t.jsxs(t.Fragment,{children:[ee.map(([ge,ut])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{v&&v(ge,ut),Je(!1),he(!1)},role:"menuitem","data-testid":`overflow-script-item-${ge}`,children:[t.jsx(ns,{size:14}),t.jsx("span",{children:ge})]},ge)),x&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>bn(x),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(ui,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):x&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>bn(x),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(ui,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>bn(m),role:"menuitem","data-testid":"overflow-schedules-btn",children:[t.jsx(Oi,{size:16}),t.jsx("span",{children:"Automation"})]}),l&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>bn(l),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[t.jsx(Vr,{size:16}),t.jsx("span",{children:"View Activity Log"})]}),d&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>bn(d),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(da,{size:16}),t.jsxs("span",{children:["Mailbox",u>0?` (${u})`:""]})]}),o&&t.jsxs("button",{className:"mobile-overflow-item",onClick:ge=>bn(()=>o(ge.currentTarget.getBoundingClientRect())),role:"menuitem","data-testid":"overflow-usage-btn",children:[t.jsx(Gs,{size:16}),t.jsx("span",{children:"View Usage"})]}),g&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>bn(g),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(dl,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>bn(e),role:"menuitem",children:[t.jsx(Lr,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),sn&&Lt&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{className:"header-search",children:[t.jsx($i,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:$,onChange:ge=>T(ge.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:Tn,"aria-label":"Close search",children:t.jsx(en,{size:14})})]})}),T&&Q&&tt&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{ref:It,className:"header-search mobile-search-expanded",children:[t.jsx($i,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:Vt,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:$,onChange:ge=>T(ge.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:In,"aria-label":"Close search",children:t.jsx(en,{size:14})})]})})]})}const vS={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","gridlock","fallback-used"],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,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:"none",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:{}},yS={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,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,maxPostReviewFixes:1,maxSpawnedAgentsPerParent:5,maxSpawnedAgentsGlobal:20,maintenanceIntervalMs:3e5,autoArchiveDoneTasksEnabled:!0,autoArchiveDoneAfterMs:2880*60*1e3,archiveAgentLogMode:"compact",autoUpdatePrStatus:!1,githubCommentOnDone:!1,githubCommentTemplate:void 0,autoBackupEnabled:!1,autoBackupSchedule:"0 2 * * *",autoBackupRetention:7,autoBackupDir:".fusion/backups",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}},researchEnabled:!0,researchMaxConcurrentRuns:3,researchDefaultTimeout:3e5,researchMaxSourcesPerRun:20,researchMaxSynthesisRounds:2},wS=Object.freeze(Object.keys(vS)),kS=Object.freeze(Object.keys(yS));function Y3(e){return wS.includes(e)}function Q3(e){return kS.includes(e)}function _e(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function jS(e){return!!(e?.provider&&e?.modelId)}function Ji(...e){for(const n of e)if(jS(n))return{provider:n.provider,modelId:n.modelId};return{}}function zl(e){return Ji({provider:e?.defaultProviderOverride,modelId:e?.defaultModelIdOverride},{provider:e?.defaultProvider,modelId:e?.defaultModelId})}function NS(e){return Ji({provider:e?.executionProvider,modelId:e?.executionModelId},{provider:e?.executionGlobalProvider,modelId:e?.executionGlobalModelId},zl(e))}function SS(e){return Ji({provider:e?.planningProvider,modelId:e?.planningModelId},{provider:e?.planningGlobalProvider,modelId:e?.planningGlobalModelId},zl(e))}function CS(e){return Ji({provider:e?.validatorProvider,modelId:e?.validatorModelId},{provider:e?.validatorGlobalProvider,modelId:e?.validatorGlobalModelId},zl(e))}function X3(e){return Ji({provider:e?.titleSummarizerProvider,modelId:e?.titleSummarizerModelId},{provider:e?.titleSummarizerGlobalProvider,modelId:e?.titleSummarizerGlobalModelId},{provider:e?.planningProvider,modelId:e?.planningModelId},zl(e))}function eg(e,n){return Ji({provider:e.modelProvider,modelId:e.modelId},NS(n))}function tg(e,n){return Ji({provider:e.validatorModelProvider,modelId:e.validatorModelId},CS(n))}function ng(e,n){return Ji({provider:e.planningModelProvider,modelId:e.planningModelId},SS(n))}const Z3=["off","minimal","low","medium","high"],la=["triage","todo","in-progress","in-review","done","archived"],mo=["low","normal","high","urgent"],Ds="normal",ES=["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"],cs={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},_S={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"},jd={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 MS(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 AS(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 PS({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 sg=i.createContext(null);function RS({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 rl.createElement(sg.Provider,{value:d},e,rl.createElement(PS,{isOpen:c!==null,options:c?.options??null,onConfirm:()=>l(!0),onCancel:()=>l(!1)}))}function Qs(){const e=i.useContext(sg);return e||{confirm:async n=>!1}}function TS(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 ig({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(Ks,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("a",{className:`card-github-badge ${TS(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,href:n.url,target:"_blank",rel:"noopener noreferrer",children:[t.jsx(Ml,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function Eo(e,n){return`${e??"default"}:${n}`}class IS{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=Eo(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const a=Eo(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=Eo(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(Ni(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=Eo(this.projectId,l.taskId),d=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:Nm(l,"prInfo")?l.prInfo??null:d?.prInfo,issueInfo:Nm(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 sa=new IS;let $S=0;function Nm(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function ag(e){const n=i.useRef(null);n.current===null&&(n.current=`badge-hook-${$S++}`);const s=i.useSyncExternalStore(o=>sa.subscribe(o),()=>sa.getSnapshot(),()=>sa.getSnapshot()),a=i.useCallback(o=>{sa.subscribeTask(n.current,o)},[]),r=i.useCallback(o=>{sa.unsubscribeTask(n.current,o)},[]);return i.useEffect(()=>{sa.setProjectId(e??null)},[e]),i.useEffect(()=>()=>{sa.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:a,unsubscribeFromBadge:r}}function gl(e,n,s,a){return e===void 0||!n?s:!a||n>=a?e??void 0:s}function DS({taskId:e,prInfo:n,issueInfo:s,updatedAt:a,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:d}=ag(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=gl(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??a),f=gl(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??a);return!h&&!f?null:t.jsx(ig,{prInfo:h,issueInfo:f})}const LS=i.memo(DS);LS.displayName="TaskCardBadge";const ti={data:new Map,pendingPromise:null,lastFetchTime:null},OS=5e3;function nl(e,n){return n?`${n}::${e}`:e}function FS(e,n){const s=ti.data.get(nl(e,n));if(!(!s||Date.now()-s.timestamp>OS))return s}function zS(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 Ok(c,e)}catch(h){u=h instanceof Error?h:new Error(String(h));const f=_e(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=ti.data.get(nl(f,e));return p&&p.timestamp>u})&&ti.lastFetchTime&&ti.lastFetchTime>u)return;if(a.current&&(clearTimeout(a.current),a.current=null),ti.pendingPromise){s(!0);try{await ti.pendingPromise}finally{s(!1)}return}s(!0);const h=r(c);ti.pendingPromise=h;try{const f=await h,p=Date.now();for(const[g,x]of Object.entries(f))ti.data.set(nl(g,e),{result:x,timestamp:p});ti.lastFetchTime=p}catch{}finally{ti.pendingPromise=null,s(!1)}},[r,e]),l=i.useCallback(c=>ti.data.get(nl(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:ti.lastFetchTime,getBatchData:l}}const Nd=new Map,US=3e4;function rg(e,n,s,a){return`${e}:${n??""}:${s??""}:${a??""}`}function BS(e,n,s,a){const r=rg(e,n,s,a),o=Nd.get(r);return o?Date.now()>o.expiresAt?(Nd.delete(r),null):o.stats:null}function HS(e,n,s,a,r){const o=rg(e,n,s,a);Nd.set(o,{stats:r,expiresAt:Date.now()+US})}function qS(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,v=c!==void 0?String(c):void 0;let b=!1;async function k(j=!1){if(!j){const E=BS(e,a,x,v);if(E){b||(m(E),f(!1));return}}f(!0);try{const E=await Bf(e,x,a);b||(m(E.stats),HS(e,a,x,v,E.stats))}catch{b||m(null)}finally{b||f(!1)}}k();let S;return d&&g&&(S=setInterval(()=>{k(!0)},d)),()=>{b=!0,S&&clearInterval(S)}},[e,n,s,a,o,l,c,d]),{stats:u,loading:h}}const VS=new Set(["failed","stuck-killed"]);function bl(e,n,s){if(e.column!=="in-progress"||e.status&&VS.has(e.status)||!n||n<=0)return!1;const a=new Date(e.updatedAt).getTime();return(s??Date.now())-a>n}function WS(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function KS(e){return e==="done"||e==="skipped"}function GS(e,n,s){const a=s?.get(e)?.trim();if(a)return a;const r=n?.workflowStepName?.trim();return r||e}function og(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:GS(d,u,n),status:u?WS(u.status):"pending",source:"workflow",phase:u?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(d=>KS(d.status)).length;return{total:l,completed:c,items:o}}function JS(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 lg(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??""}
651
- ${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:JS(n)}})}function YS(e){if(!e||e.length===0)return null;let n=0,s=0;for(const a of lg(e))typeof a.durationMs=="number"&&(n+=a.durationMs,s+=1);return s>0?n:null}const Sd=new Map;async function QS(e,n){const s=Sd.get(e);if(s)return s;try{const a=await Hf(e,n);return Sd.set(e,a.title),a.title}catch{return e}}const Sm=12;function XS(e){return e.length<=Sm?e:e.slice(0,Sm-3)+"..."}const Cd=new Map;async function ZS(e,n){const s=Cd.get(e);if(s)return s;try{const a=await kd(e,n);return Cd.set(e,a.name),a.name}catch{return e}}function e0(e){return typeof e=="string"&&mo.includes(e)?e:Ds}function t0(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}function cg(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 n0(e){return e.sourceType==="agent_heartbeat"||e.sourceType==="automation"||!!cg(e)}const s0=new Set(["triage","todo"]),Cm=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]),Em=new Set(["merging","merging-pr","merging-fix"]),i0={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},a0=new Set(["in-progress","in-review","done"]),r0=3e4;function o0(e){return e==="merging-fix"?"Merging fixes…":e}function ma(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function l0(e){const n=ma(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function _m(e,n){const s=ma(e.columnMovedAt??e.updatedAt);return s==null?null:Math.max(0,n-s)}function Pr(e,n){const s=ma(e.executionStartedAt);if(s==null)return null;const a=ma(e.executionCompletedAt),r=a!=null&&a>=s?a:n;return Math.max(0,r-s)}function c0(e){return e.column==="done"?l0(e):null}function dg(e,n){const s=ma(e.updatedAt);return s==null?null:Math.max(0,n-s)}function d0(e,n){const s=Pr(e,n);if(s!=null)return s;const a=dg(e,n),r=Rr(e,n);return r!=null?r+(a??0):a}function u0(e,n){const s=e.workflowStepResults;if(!s||s.length===0)return null;let a=0,r=0;for(const o of s){if(!o.startedAt)continue;const l=ma(o.startedAt);if(l==null)continue;let c;if(o.completedAt){const d=ma(o.completedAt);if(d==null||d<l)continue;c=d}else c=Math.max(l,n);a+=c-l,r+=1}return r>0?a:null}function Rr(e,n){const s=typeof e.timedExecutionMs=="number"?e.timedExecutionMs:YS(e.log),a=u0(e,n);return s==null&&a==null?null:(s??0)+(a??0)}function Mm(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 Am(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 Pm(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 m0(e,n){return e.length!==n.length?!1:e.every((s,a)=>s.name===n[a]?.name&&s.status===n[a]?.status)}function h0(e,n){return e.length!==n.length?!1:e.every((s,a)=>s===n[a])}function p0(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>s===n[a])}function f0(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function g0(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}function b0(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 x0(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 v0(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 y0(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&&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.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&&x0(s.attachments,a.attachments)&&v0(s.comments,a.comments)&&h0(s.dependencies,a.dependencies)&&m0(s.steps,a.steps)&&p0(s.enabledWorkflowSteps,a.enabledWorkflowSteps)&&b0(s.workflowStepResults,a.workflowStepResults)&&Pm(s.prInfo,a.prInfo)&&Pm(s.issueInfo,a.issueInfo)}function w0({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:v}){const[b,k]=i.useState(!1),[S,j]=i.useState(!1),[E,y]=i.useState(!1),[N,M]=i.useState(e.description||""),[D,C]=i.useState(!1),[_,F]=i.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(Ce=>Ce.status==="done"||Ce.status==="skipped")),[U,A]=i.useState(null),[$,T]=i.useState(null),[J,B]=i.useState(!1),[se,P]=i.useState(!1),[O,I]=i.useState(()=>Date.now()),w=i.useRef(null),Y=i.useRef(!1),re=i.useRef(null),le=i.useRef(null),[ve,de]=i.useState(!1),{badgeUpdates:Fe,subscribeToBadge:X,unsubscribeFromBadge:L}=ag(n),{confirm:Q}=Qs(),ne=i.useRef(null),H=i.useRef(!1),z=i.useCallback(Ce=>Ce instanceof Element?!!Ce.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);i.useEffect(()=>{M(e.description||"")},[e.id,e.description]),i.useEffect(()=>{if(!J)return;const Ce=et=>{le.current&&!le.current.contains(et.target)&&B(!1)};return document.addEventListener("click",Ce),()=>document.removeEventListener("click",Ce)},[J]),i.useEffect(()=>{if(!e.missionId){A(null);return}const Ce=Sd.get(e.missionId);if(Ce){A(Ce);return}let et=!1;return QS(e.missionId,n).then(tt=>{et||A(tt)}),()=>{et=!0}},[e.missionId,n]),i.useEffect(()=>{if(!e.assignedAgentId){T(null);return}const Ce=Cd.get(e.assignedAgentId);if(Ce){T(Ce);return}T(null);let et=!1;return ZS(e.assignedAgentId,n).then(tt=>{et||T(tt)}),()=>{et=!0}},[e.assignedAgentId,n]),i.useEffect(()=>{if(E&&w.current){const Ce=w.current;Ce.focus(),Ce.style.height="auto",Ce.style.height=Ce.scrollHeight+"px"}},[E]),i.useEffect(()=>{if(typeof IntersectionObserver>"u"){de(!0);return}const Ce=re.current;if(!Ce)return;const et=new IntersectionObserver(([tt])=>{de(tt?.isIntersecting??!0)},{rootMargin:"200px"});return et.observe(Ce),()=>et.disconnect()},[E,e.id]);const W=i.useCallback(Ce=>{Ce.dataTransfer.setData("text/plain",e.id),Ce.dataTransfer.effectAllowed="move",k(!0)},[e.id]),we=i.useCallback(()=>{k(!1)},[]),Z=i.useCallback(Ce=>Ce.dataTransfer.types.includes("Files"),[]),fe=i.useCallback(Ce=>{Z(Ce)&&(Ce.preventDefault(),Ce.stopPropagation(),Ce.dataTransfer.dropEffect="copy",j(!0))},[Z]),Oe=i.useCallback(Ce=>{Z(Ce)&&(Ce.preventDefault(),Ce.stopPropagation(),j(!1))},[Z]),Ve=i.useCallback(async Ce=>{if(!Z(Ce))return;Ce.preventDefault(),Ce.stopPropagation(),j(!1);const et=Array.from(Ce.dataTransfer.files);for(const tt of et)try{await Ol(e.id,tt,n),r(`Attached ${tt.name} to ${e.id}`,"success")}catch(Lt){r(`Failed to attach ${tt.name}: ${_e(Lt)}`,"error")}},[e.id,Z,r]),He=i.useCallback(()=>{E||a(e)},[e,a,E]),Je=i.useCallback(Ce=>{if(Y.current){Y.current=!1;return}z(Ce.target)||He()},[He,z]),$e=i.useCallback(Ce=>{const et=Ce.touches[0];et&&(ne.current={x:et.clientX,y:et.clientY,time:Date.now()},H.current=!1)},[]),he=i.useCallback(Ce=>{if(!ne.current)return;const et=Ce.touches[0];if(!et)return;const tt=Math.abs(et.clientX-ne.current.x),Lt=Math.abs(et.clientY-ne.current.y);(tt>Rm||Lt>Rm)&&(H.current=!0)},[]),ue=i.useCallback(Ce=>{if(z(Ce.target)||!ne.current)return;const tt=Date.now()-ne.current.time<k0,Lt=!H.current;tt&&Lt&&(Y.current=!0,He()),ne.current=null,H.current=!1},[He,z]),Ee=i.useCallback(async(Ce,et)=>{Ce.stopPropagation();try{const tt=await Wa(et,n);a(tt)}catch{r(`Failed to load dependency ${et}`,"error")}},[a,r]),je=e.status==="failed",xe=e.paused===!0,Pe=!!(e.paused&&e.pausedByAgentId),ie=e0(e.priority),Me=ie!==Ds,We=bl(e,f,x),mt=e.column==="triage"&&e.status==="awaiting-approval",st=e.column==="archived",Ze=!o&&!s&&!je&&!xe&&!We&&!mt&&(e.column==="in-progress"||Cm.has(e.status)),dt=!s&&!xe&&!E&&!st,Ae=s0.has(e.column)&&!Ze&&!xe&&!s&&l,Ue=!!(e.prInfo||e.issueInfo),kt=e.sourceType==="github_import",De=f0(e.sourceMetadata),be=n0(e),pe=cg(e),Re=pe?`Created by agent: ${pe}`:"Created by agent",Be=!!(e.assignedAgentId&&$===null),at=i.useMemo(()=>{const Ce=[];return e.modelProvider&&Ce.push(e.modelProvider),e.validatorModelProvider&&!Ce.includes(e.validatorModelProvider)&&Ce.push(e.validatorModelProvider),e.planningModelProvider&&!Ce.includes(e.planningModelProvider)&&Ce.push(e.planningModelProvider),Ce},[e.modelProvider,e.validatorModelProvider,e.planningModelProvider]),me=i.useMemo(()=>og(e,v),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,v]),ft=me.total>0&&(e.status==="executing"||e.column==="in-progress");i.useEffect(()=>{if(e.column!=="in-progress"&&e.column!=="in-review")return;const Ce=e.status!=null&&Em.has(e.status);if(e.column==="in-progress"){const tt=Pr(e,Date.now()),Lt=_m(e,Date.now()),Zt=Rr(e,Date.now());if(tt==null&&Lt==null&&Zt==null)return}if(!Ce&&e.column==="in-review"){const tt=Pr(e,Date.now()),Lt=Rr(e,Date.now());if(tt==null&&Lt==null)return}I(Date.now());const et=window.setInterval(()=>{I(Date.now())},r0);return()=>window.clearInterval(et)},[e.column,e.status,e.columnMovedAt,e.updatedAt,e.workflowStepResults,e.timedExecutionMs,e.executionStartedAt,e.executionCompletedAt]);const Et=i.useMemo(()=>{if(!a0.has(e.column))return null;if(e.status!=null&&Em.has(e.status)){const sn=d0(e,O);if(sn!=null){const At=Am(sn);if(At){const cn=dg(e,O),Tn=cn==null?null:Mm(cn),En=Tn?`Execution time ${At}. Merge phase ${Tn}`:`Execution time ${At}. Merging`;return{label:At,title:En,ariaLabel:En}}}}if(e.column==="in-progress"){const sn=Pr(e,O)??_m(e,O)??Rr(e,O);if(sn==null)return null;const At=Mm(sn);return At?{label:At,title:`In progress ${At}`,ariaLabel:`In progress ${At}`}:null}const et=Pr(e,O)??Rr(e,O);if(et==null)return null;const tt=Am(et);if(!tt)return null;const Lt=c0(e);if(Lt==null)return{label:tt,title:`Execution time ${tt}`,ariaLabel:`Execution time ${tt}`};const Zt=new Date(Lt).toLocaleString();return{label:tt,title:`Execution time ${tt}. Completed ${Zt}`,ariaLabel:`Execution time ${tt}. Completed ${Zt}`}},[e.column,e.status,e.columnMovedAt,e.timedExecutionMs,e.updatedAt,e.workflowStepResults,e.log,e.executionStartedAt,e.executionCompletedAt,O]);i.useEffect(()=>{if(!Ue||!ve){L(e.id);return}return X(e.id),()=>{L(e.id)}},[Ue,ve,X,e.id,L]);const jt=Fe.get(`${n??"default"}:${e.id}`),$t=e.column==="in-progress"||e.column==="in-review",Ft=i.useMemo(()=>e.steps.map(Ce=>`${Ce.name}:${Ce.status}`).join("|"),[e.steps]),{stats:Rt}=qS(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:ve,worktree:e.worktree,stepVersion:$t?Ft:void 0,pollIntervalMs:$t?3e4:void 0}),It=i.useMemo(()=>FS(e.id,n),[e.id,n]),Vt=i.useMemo(()=>{const Ce=jt?.prInfo,et=jt?.timestamp,tt=It?.result?.prInfo,Lt=It?.timestamp?new Date(It.timestamp).toISOString():void 0,Zt=e.prInfo,sn=e.prInfo?.lastCheckedAt??e.updatedAt;let At=gl(Ce,et,Zt,sn);const cn=et&&et>=sn?et:sn;return tt&&Lt&&(!cn||Lt>cn)&&(At=tt),At},[jt,It,e.prInfo,e.updatedAt]),Qt=i.useMemo(()=>{const Ce=jt?.issueInfo,et=jt?.timestamp,tt=It?.result?.issueInfo,Lt=It?.timestamp?new Date(It.timestamp).toISOString():void 0,Zt=e.issueInfo,sn=e.issueInfo?.lastCheckedAt??e.updatedAt;let At=gl(Ce,et,Zt,sn);const cn=et&&et>=sn?et:sn;return tt&&Lt&&(!cn||Lt>cn)&&(At=tt),At},[jt,It,e.issueInfo,e.updatedAt]),Jt=i.useCallback(Ce=>{Ce?.stopPropagation(),!(!Ae||D)&&(y(!0),M(e.description||""))},[Ae,D,e.description]),on=i.useCallback(()=>{y(!1),M(e.description||"")},[e.description]),Kt=i.useCallback(()=>N!==(e.description||""),[N,e.description]),qt=i.useCallback(async()=>{if(!(!l||D)){if(!Kt()){on();return}C(!0);try{await l(e.id,{description:N.trim()||void 0}),r(`Updated ${e.id}`,"success"),y(!1)}catch(Ce){r(`Failed to update ${e.id}: ${_e(Ce)}`,"error")}finally{C(!1)}}},[l,e.id,N,D,Kt,on,r]),kn=i.useCallback(Ce=>{Ce.key==="Enter"&&!Ce.shiftKey?(Ce.preventDefault(),qt()):Ce.key==="Escape"&&(Ce.preventDefault(),on())},[qt,on]),nn=i.useCallback(()=>{setTimeout(()=>{const Ce=document.activeElement;Ce===w.current||Ce?.closest(".card-editing-content")||(Kt()?qt():on())},0)},[Kt,qt,on]),Xt=i.useCallback(Ce=>{Ae&&(Ce.stopPropagation(),Jt(Ce))},[Ae,Jt]),Gt=i.useCallback(Ce=>{Ce.stopPropagation(),Jt(Ce)},[Jt]),ln=i.useCallback(Ce=>{M(Ce.target.value);const et=Ce.target;et.style.height="auto",et.style.height=et.scrollHeight+"px"},[]),ye=i.useCallback(Ce=>{Ce.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch(et=>{r(`Failed to archive ${e.id}: ${_e(et)}`,"error")})},[r,c,e.id]),Le=i.useCallback(Ce=>{Ce.stopPropagation(),d&&d(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch(et=>{r(`Failed to unarchive ${e.id}: ${_e(et)}`,"error")})},[r,d,e.id]),ae=i.useCallback(async Ce=>{if(Ce.stopPropagation(),!(!u||!await Q({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0})))try{await u(e.id),r(`Deleted ${e.id}`,"success")}catch(tt){const Lt=g0(tt);if(!Lt||Lt.dependentIds.length===0){r(`Failed to delete ${e.id}: ${_e(tt)}`,"error");return}const Zt=Lt.dependentIds.join(", ");if(!await Q({title:"Force Delete Task",message:`${e.id} is a dependency of ${Zt}.
652
-
653
- 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(At){r(`Failed to delete ${e.id}: ${_e(At)}`,"error")}}},[r,Q,u,e.id]),Te=i.useCallback(Ce=>{Ce.stopPropagation(),h?.(e,"changes")},[e,h]),Ne=i.useCallback(Ce=>{Ce.stopPropagation(),F(et=>!et)},[]),ee=i.useCallback(Ce=>{Ce.stopPropagation(),e.missionId&&p&&p(e.missionId)},[e.missionId,p]),Ie=i.useCallback(Ce=>{Ce.stopPropagation(),B(et=>!et)},[]),St=i.useCallback(async(Ce,et)=>{if(Ce.stopPropagation(),B(!1),!!g)try{const tt=e.steps.some(sn=>sn.status!=="pending"),Lt=(et==="todo"||et==="triage")&&tt;let Zt;if(Lt){if(await Q({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Zt={preserveProgress:!0};else if(!await Q({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,et,Zt),r(`Moved ${e.id} to ${cs[et]}`,"success")}catch(tt){r(`Failed to move ${e.id}: ${_e(tt)}`,"error")}},[r,Q,g,e.id,e.steps]),pt=i.useCallback(async Ce=>{if(Ce.stopPropagation(),!(!m||se)){P(!0);try{await m(e.id)}catch(et){r(`Failed to retry ${e.id}: ${_e(et)}`,"error")}finally{P(!1)}}},[r,se,m,e.id]),Dt=`card${b?" dragging":""}${s?" queued":""}${Ze?" agent-active":""}${je?" failed":""}${xe?" paused":""}${We?" stuck":""}${mt?" awaiting-approval":""}${S?" file-drop-target":""}${E?" card-editing":""}${D?" card-saving":""}`,Ut=(()=>{if(e.column==="in-progress"){const Ce=Rt?.filesChanged,et=Ce==null||Ce===0?e.modifiedFiles?.length:void 0,tt=Ce!=null&&Ce>0?Ce:et;return tt==null||tt===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Te,disabled:!h,children:[t.jsx(ws,{size:12}),t.jsxs("span",{children:[tt," ",tt===1?"file":"files"," changed"]})]})}if(e.column==="in-review"){const Ce=Rt?.filesChanged,et=Ce==null||Ce===0?e.modifiedFiles?.length:void 0,tt=Ce!=null&&Ce>0?Ce:et;return tt==null||tt===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Te,disabled:!h,children:[t.jsx(ws,{size:12}),t.jsxs("span",{children:[tt," ",tt===1?"file":"files"," changed"]})]})}if(e.column==="done"){const Ce=Rt?.filesChanged,et=e.mergeDetails?.filesChanged,tt=Ce??et;if(tt!=null&&tt>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Te,disabled:!h,children:[t.jsx(ws,{size:12}),t.jsxs("span",{children:[tt," ",tt===1?"file":"files"," changed"]})]});const Lt=e.modifiedFiles?.length;if(Lt!=null&&Lt>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Te,disabled:!h,children:[t.jsx(ws,{size:12}),t.jsxs("span",{children:[Lt," ",Lt===1?"file":"files"," changed"]})]})}return null})();return E?t.jsx("div",{ref:re,className:Dt,"data-id":e.id,onDoubleClick:Xt,children:t.jsxs("div",{className:"card-editing-content",children:[t.jsx("textarea",{ref:w,className:"card-edit-desc-textarea",placeholder:"Task description",value:N,onChange:ln,onKeyDown:kn,onBlur:nn,disabled:D,rows:4}),D&&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:re,className:Dt,"data-id":e.id,draggable:dt,onDragStart:dt?W:void 0,onDragEnd:dt?we:void 0,onDragOver:fe,onDragLeave:Oe,onDrop:Ve,onClick:Je,onTouchStart:$e,onTouchMove:he,onTouchEnd:ue,onDoubleClick:Xt,children:[t.jsxs("div",{className:"card-header",children:[t.jsx("span",{className:"card-id",children:e.id}),xe&&t.jsx("span",{className:"card-status-badge paused",children:Pe?"paused by agent":"paused"}),!xe&&e.status&&e.status!=="queued"&&t.jsx("span",{className:`card-status-badge card-status-badge--${e.column}${mt?" awaiting-approval":""}${Cm.has(e.status)?" pulsing":""}${je?" failed":""}${We?" stuck":""}`,children:We?"Stuck":mt?"Awaiting Approval":o0(e.status)}),We&&(xe||!e.status||e.status==="queued")&&t.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),Ue&&t.jsx(ig,{prInfo:Vt,issueInfo:Qt}),be&&t.jsxs("span",{className:"card-agent-created-badge",title:Re,"aria-label":Re,children:[t.jsx(zn,{size:11,"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:Re}),t.jsx("span",{"aria-hidden":"true",children:"Agent"})]}),Me&&t.jsx("span",{className:`card-priority-badge card-priority-badge--${ie}`,children:ie}),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(ds,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),e.missionId&&t.jsxs("span",{className:"card-mission-badge",onClick:ee,title:`Mission: ${U??e.missionId}`,role:p?"button":void 0,tabIndex:p?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.jsx(As,{size:11}),XS(U??e.missionId)]}),t.jsxs("div",{className:"card-header-actions",children:[Ae&&t.jsx("button",{className:"card-edit-btn",onClick:Gt,title:"Edit task","aria-label":"Edit task",children:t.jsx(Cs,{size:12})}),e.column==="triage"&&u&&t.jsx("button",{className:"card-delete-btn",onClick:ae,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:ye,title:"Archive task","aria-label":"Archive task",children:"Archive"}),e.column==="archived"&&d&&t.jsx("button",{className:"card-unarchive-btn",onClick:Le,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),e.column==="in-progress"&&g&&t.jsxs("div",{className:"card-send-back",ref:le,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:Ie,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":J,children:["Send back",t.jsx(un,{size:10})]}),J&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:jd["in-progress"].filter(Ce=>Ce!=="in-review").map(Ce=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:et=>St(et,Ce),children:cs[Ce]},Ce))})]}),e.column==="in-review"&&g&&t.jsxs("div",{className:"card-send-back",ref:le,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:Ie,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":J,children:["Move",t.jsx(un,{size:10})]}),J&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:jd["in-review"].map(Ce=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:et=>St(et,Ce),children:Ce==="done"?"Done (no merge)":cs[Ce]},Ce))})]}),e.size&&t.jsx("span",{className:`card-size-badge size-${e.size.toLowerCase()}`,children:e.size})]})]}),je&&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:pt,disabled:se,children:[t.jsx(Oy,{size:12}),se?"Retrying…":"Retry"]})]}),t.jsx("div",{className:"card-title",title:e.title||e.description||void 0,children:Im(e.title,Tm)||Im(e.description,Tm)||e.id}),ft&&(()=>{const Ce=me.completed/me.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:`${Ce}%`,backgroundColor:i0[e.column]}})}),t.jsxs("span",{className:"card-progress-label",children:[me.completed,"/",me.total]})]}),t.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:Ne,"aria-expanded":_,"aria-label":_?"Hide steps":"Show steps",children:[t.jsxs("span",{children:[me.total," step",me.total===1?"":"s"]}),t.jsx(un,{size:14,className:`card-steps-toggle-icon${_?" expanded":""}`})]}),_&&t.jsx("div",{className:"card-steps-list",children:me.items.map(et=>{const tt=et.source==="workflow"&&et.status==="failed";return t.jsxs("div",{className:"card-step-item",children:[t.jsx("span",{className:`card-step-dot card-step-dot--${et.status}${tt?" card-step-dot--workflow-failed":""}`,"aria-hidden":"true"}),t.jsx("span",{className:`card-step-name${et.status==="done"?" completed":""}`,children:et.name}),et.source==="workflow"&&t.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${et.phase}`,title:"Workflow check",children:"workflow"})]},et.id)})})]})})(),(Ut||Et||kt)&&t.jsxs("div",{className:"card-footer-row",children:[Ut,kt&&t.jsx("span",{className:"card-source-provenance",title:De?`Imported from GitHub: ${De}`:"Imported from GitHub","aria-label":"Imported from GitHub",children:t.jsx(Kn,{provider:"github",size:"sm"})}),Et&&t.jsxs("span",{className:"card-time-indicator",title:Et.title,"aria-label":Et.ariaLabel,children:[t.jsx(Oi,{size:12}),t.jsx("span",{children:Et.label})]})]}),(e.dependencies&&e.dependencies.length>0||s||e.status==="queued"||e.blockedBy)&&t.jsxs("div",{className:"card-meta",children:[e.dependencies&&e.dependencies.length>0&&t.jsx("div",{className:"card-dep-list",children:e.dependencies.map(Ce=>t.jsxs("span",{className:"card-dep-badge clickable",onClick:et=>void Ee(et,Ce),title:`Click to view ${Ce}`,children:[t.jsx(Ha,{size:12,style:{verticalAlign:"middle"}})," ",Ce]},Ce))}),e.blockedBy&&t.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${e.blockedBy} (file overlap)`,children:[t.jsx(ca,{size:12,style:{verticalAlign:"middle"}})," ",e.blockedBy]}),(s||e.status==="queued")&&e.column!=="in-progress"&&t.jsxs("span",{className:"queued-badge",children:[t.jsx(Oi,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),(e.assignedAgentId||at.length>0)&&t.jsxs("div",{className:"card-agent-row",children:[at.length>0&&t.jsx("span",{className:"card-provider-icons","data-testid":"card-provider-icons",children:at.map(Ce=>t.jsx(Kn,{provider:Ce,size:"sm"},Ce))}),e.assignedAgentId&&t.jsxs("span",{className:`card-agent-badge${Be?" card-agent-badge--loading":""}`,title:`Assigned to ${$??e.assignedAgentId}`,children:[t.jsx(zn,{size:11}),t.jsx("span",{className:"card-agent-badge-text",children:t0($??e.assignedAgentId,15)})]})]}),t.jsx(qi,{slotId:"task-card-badge",projectId:n})]})}const Rm=10,k0=300,Tm=140;function Im(e,n){return e?e.length>n?e.slice(0,n)+"…":e:""}const Jr=i.memo(w0,y0);Jr.displayName="TaskCard";function j0({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}){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(nv,{size:14}):t.jsx(Bs,{size:14})}),t.jsx("span",{className:"worktree-label",children:e})]}),n.map(g=>t.jsx(Jr,{task:g,projectId:a,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:d,onOpenDetailWithTab:u,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p},g.id)),s.map(g=>t.jsx(Jr,{task:g,projectId:a,queued:!0,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:d,onOpenDetailWithTab:u,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p},g.id))]})}const ug=i.memo(j0);ug.displayName="WorktreeGroup";function $m(e){return e.toLowerCase().replace(/[-_./]/g,"")}function N0(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 S0(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 C0(e,n){const s=$m(e),a=$m(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&&N0(s,o)||s.length>=4&&S0(s,o,1))return!0;return!1}function E0(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=>C0(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,v]=i.useState(""),[b,k]=i.useState(0),[S,j]=i.useState(null),[E,y]=i.useState(null),N=i.useRef(null),M=i.useRef(null),D=i.useRef(null),C=i.useRef(null),_=i.useRef(null),F=i.useMemo(()=>E0(e,x),[e,x]),U=i.useMemo(()=>F.reduce((Q,ne)=>((Q[ne.provider]??=[]).push(ne),Q),{}),[F]),A=i.useMemo(()=>{const Q=[];for(const ne of u){const H=ne.indexOf("/");if(H===-1)continue;const z=ne.slice(0,H),W=ne.slice(H+1),we=F.find(Z=>Z.provider===z&&Z.id===W);we&&Q.push({model:we,fullId:ne})}return Q},[u,F]),$=i.useMemo(()=>{const Q=Object.entries(U),ne=new Set(c);return Q.sort(([H],[z])=>{const W=ne.has(H),we=ne.has(z);if(W&&!we)return-1;if(!W&&we)return 1;if(W&&we){const Z=c.indexOf(H),fe=c.indexOf(z);if(Z!==fe)return Z-fe}return H.localeCompare(z)})},[U,c]),T=typeof h=="string"&&h.length>0,J=i.useMemo(()=>{if(!n||T&&n===h)return null;const Q=n.indexOf("/");return Q===-1?null:n.slice(0,Q)},[T,h,n]),B=i.useMemo(()=>{const Q=[];return T&&Q.push({type:"no-change",value:h,label:f}),Q.push({type:"default",value:"",label:"Use default"}),Q},[T,f,h]),se=i.useMemo(()=>{const Q=[...B];for(const{model:ne,fullId:H}of A)Q.push({type:"favorite",value:H,label:ne.name,provider:ne.provider});return $.forEach(([ne,H])=>{Q.push({type:"provider",value:`__group_${ne}`,label:ne,provider:ne}),H.forEach(z=>{Q.push({type:"model",value:`${z.provider}/${z.id}`,label:z.name,provider:z.provider})})}),Q},[A,$,B]),P=i.useMemo(()=>{if(T&&n===h)return f;if(!n)return"Use default";const Q=n.indexOf("/");if(Q===-1)return n;const ne=n.slice(0,Q),H=n.slice(Q+1);return e.find(W=>W.provider===ne&&W.id===H)?.name||n},[T,f,h,n,e]),O=i.useMemo(()=>se.findIndex(Q=>Q.value===n),[se,n]),I=i.useCallback(()=>{const Q=window.visualViewport;return Q&&Q.height>0&&Q.width>0?{width:Q.width,height:Q.height,offsetTop:Q.offsetTop,offsetLeft:Q.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),w=i.useCallback(()=>{const{height:Q}=I(),ne=typeof window.matchMedia=="function",H=ne?window.matchMedia("(max-width: 640px)").matches:!1,z=ne?window.matchMedia("(max-width: 768px)").matches:!1;return Q<=0?320:H?Math.min(Q*.6,360):z?Math.min(Q*.7,420):320},[I]),Y=i.useCallback(()=>{const Q=M.current;if(!Q)return;const ne=Q.getBoundingClientRect(),{width:H,height:z,offsetTop:W,offsetLeft:we}=I(),Z=16,fe=16,Oe=4,Ve=w(),He=ne.bottom-W,Je=ne.top-W,$e=ne.left-we,he=z-He,ue=Je,Ee=Math.max(he-fe-Oe,160),je=Math.max(ue-fe-Oe,160),xe=he<Ve&&ue>he,Pe=Math.max(Math.min(xe?je:Ee,Ve),160),ie=Math.min(ne.width,H-Z*2),Me=Math.min(Math.max($e,Z),H-Z-ie)+we,We=xe?Math.max(fe+W,Je-Pe-Oe+W):Math.min(He+Oe+W,z+W-fe-Pe);j({top:We,left:Me,width:ie,maxHeight:Pe})},[I,w]);i.useEffect(()=>{y(document.body)},[]);const re=i.useRef(!1);i.useEffect(()=>{if(!p){re.current=!1;return}if(re.current||se.length===0)return;const Q=se.findIndex((ne,H)=>H>=(O>=0?O:0)&&ne.type!=="provider");k(Q>=0?Q:0),re.current=!0},[p,se,O]),i.useEffect(()=>{p&&re.current&&(k(0),_.current&&(_.current.scrollTop=0))},[x,p]),i.useEffect(()=>{if(!p)return;Y();const Q=requestAnimationFrame(()=>C.current?.focus());return()=>cancelAnimationFrame(Q)},[p,Y]),i.useEffect(()=>{if(!p)return;const Q=()=>Y();window.addEventListener("resize",Q),window.addEventListener("scroll",Q,!0);const ne=window.visualViewport;return ne&&(ne.addEventListener("resize",Q),ne.addEventListener("scroll",Q)),()=>{window.removeEventListener("resize",Q),window.removeEventListener("scroll",Q,!0),ne&&(ne.removeEventListener("resize",Q),ne.removeEventListener("scroll",Q))}},[p,Y]),i.useEffect(()=>{if(!p)return;const Q=ne=>{const H=ne.target,z=N.current?.contains(H),W=D.current?.contains(H);!z&&!W&&(g(!1),v(""))};return document.addEventListener("mousedown",Q),()=>document.removeEventListener("mousedown",Q)},[p]);const le=i.useCallback(Q=>{switch(Q.key){case"ArrowDown":if(Q.preventDefault(),!p)g(!0);else{let ne=b;for(let H=1;H<=se.length;H++){const z=(b+H)%se.length;if(se[z]?.type!=="provider"){ne=z;break}}k(ne)}break;case"ArrowUp":if(Q.preventDefault(),p){let ne=b;for(let H=1;H<=se.length;H++){const z=(b-H+se.length)%se.length;if(se[z]?.type!=="provider"){ne=z;break}}k(ne)}break;case"Enter":if(Q.preventDefault(),p){const ne=se[b];ne&&ne.type!=="provider"&&ne.type!=="favorite"&&(s(ne.value),g(!1),v(""))}else g(!0);break;case"Escape":Q.preventDefault(),g(!1),v("");break;case"Tab":p&&(g(!1),v(""));break}},[p,b,se,s]),ve=i.useCallback(Q=>{s(Q),g(!1),v("")},[s]),de=i.useCallback(()=>{v(""),C.current?.focus()},[]),Fe=i.useCallback(()=>{r||g(Q=>!Q)},[r]);i.useEffect(()=>{if(p&&_.current){const Q=_.current.querySelector(`[data-index="${b}"]`);Q&&typeof Q.scrollIntoView=="function"&&Q.scrollIntoView({block:"nearest"})}},[b,p]);const X=x.length>0,L=p&&S?t.jsxs("div",{ref:D,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:le,style:{top:`${S.top}px`,left:`${S.left}px`,width:`${S.width}px`,maxHeight:`${S.maxHeight}px`},children:[t.jsxs("div",{className:"model-combobox-search-wrapper",children:[t.jsx("input",{ref:C,type:"text",className:"model-combobox-search",placeholder:"Filter models…",value:x,onChange:Q=>v(Q.target.value),onClick:Q=>Q.stopPropagation()}),X&&t.jsx("button",{type:"button",className:"model-combobox-clear",onClick:de,"aria-label":"Clear filter",children:"×"})]}),t.jsxs("div",{className:"model-combobox-results-count",children:[F.length," model",F.length!==1?"s":""]}),t.jsxs("div",{ref:_,className:"model-combobox-list",children:[B.map((Q,ne)=>t.jsx("div",{"data-index":ne,className:`model-combobox-option ${b===ne?"model-combobox-option--highlighted":""} ${n===Q.value?"model-combobox-option--selected":""}`,onClick:()=>ve(Q.value),onMouseEnter:()=>k(ne),role:"option","aria-selected":n===Q.value,children:t.jsx("span",{className:"model-combobox-option-text model-combobox-option-text--default",children:Q.label})},`${Q.type}-${Q.value}`)),A.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"model-combobox-divider"}),A.map(({model:Q,fullId:ne},H)=>{const z=H+B.length,W=b===z,we=n===ne;return t.jsxs("div",{"data-index":z,className:`model-combobox-option model-combobox-option--favorite ${W?"model-combobox-option--highlighted":""} ${we?"model-combobox-option--selected":""}`,onClick:()=>ve(ne),onMouseEnter:()=>k(z),role:"option","aria-selected":we,children:[t.jsxs("span",{className:"model-combobox-option-main",children:[t.jsx("span",{className:"model-combobox-option-icon",children:t.jsx(Kn,{provider:Q.provider,size:"sm"})}),t.jsx("span",{className:"model-combobox-option-text",children:Q.name})]}),t.jsx("span",{className:"model-combobox-option-id",children:Q.id}),m&&t.jsx("button",{type:"button",className:"model-combobox-option-favorite model-combobox-option-favorite--active",onClick:Z=>{Z.stopPropagation(),m(ne)},title:"Remove from favorites","aria-label":`Remove ${Q.name} from favorites`,children:"★"})]},ne)}),t.jsx("div",{className:"model-combobox-divider"})]}),$.map(([Q,ne])=>{const H=se.findIndex(we=>we.value===`__group_${Q}`),z=c.includes(Q),W=ne.filter(we=>{const Z=`${we.provider}/${we.id}`;return!u.includes(Z)});return W.length===0?null:t.jsxs("div",{className:"model-combobox-group",children:[t.jsxs("div",{className:"model-combobox-optgroup","data-index":H,children:[t.jsx(Kn,{provider:Q,size:"sm"}),t.jsx("span",{className:"model-combobox-optgroup-text",children:Q}),d&&t.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${z?"model-combobox-optgroup-favorite--active":""}`,onClick:we=>{we.stopPropagation(),d(Q)},title:z?"Remove from favorites":"Add to favorites","aria-label":z?`Remove ${Q} from favorites`:`Add ${Q} to favorites`,children:"★"})]}),W.map(we=>{const Z=`${we.provider}/${we.id}`,fe=se.findIndex(Je=>Je.value===Z),Oe=b===fe,Ve=n===Z,He=u.includes(Z);return t.jsxs("div",{"data-index":fe,className:`model-combobox-option ${Oe?"model-combobox-option--highlighted":""} ${Ve?"model-combobox-option--selected":""}`,onClick:()=>ve(Z),onMouseEnter:()=>k(fe),role:"option","aria-selected":Ve,children:[t.jsx("span",{className:"model-combobox-option-text",children:we.name}),t.jsx("span",{className:"model-combobox-option-id",children:we.id}),m&&t.jsx("button",{type:"button",className:`model-combobox-option-favorite ${He?"model-combobox-option-favorite--active":""}`,onClick:Je=>{Je.stopPropagation(),m(Z)},title:He?"Remove from favorites":"Add to favorites","aria-label":He?`Remove ${we.name} from favorites`:`Add ${we.name} to favorites`,children:He?"★":"☆"})]},Z)})]},Q)}),F.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:N,className:"model-combobox",onKeyDown:le,children:t.jsxs("button",{ref:M,type:"button",id:o,className:"model-combobox-trigger",onClick:Fe,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":l,children:[J&&t.jsx("span",{className:"model-combobox-trigger-icon",children:t.jsx(Kn,{provider:J,size:"sm"})}),t.jsx("span",{className:"model-combobox-trigger-text",children:P||a}),t.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),E&&L?aa.createPortal(L,E):null]})}function ru(e,n){return typeof n!="string"||n.length===0?e:`kb:${n}:${e}`}function ss(e,n){return typeof window>"u"?null:window.localStorage.getItem(ru(e,n))}function vs(e,n,s){typeof window>"u"||window.localStorage.setItem(ru(e,s),n)}function Ja(e,n){typeof window>"u"||window.localStorage.removeItem(ru(e,n))}const _0=1e4,M0=1e3;function Ul(){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 v=await pl();n(v)}catch(v){o(v instanceof Error?v.message:"Failed to fetch nodes")}},[]);i.useEffect(()=>{let v=!1;async function b(){a(!0);try{const S=await pl();v||(n(S),o(null))}catch(S){v||o(S instanceof Error?S.message:"Failed to fetch nodes")}finally{v||a(!1)}}b();const k=()=>{if(document.visibilityState!=="visible")return;const S=Date.now();S-c.current<M0||(c.current=S,d())};return document.addEventListener("visibilitychange",k),()=>{v=!0,document.removeEventListener("visibilitychange",k)}},[d]),i.useEffect(()=>{if(!s)return l.current=setInterval(()=>{d()},_0),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,d]);const u=i.useCallback(async v=>{const b=await nN(v);return n(k=>[...k,b]),b},[]),m=i.useCallback(async(v,b)=>{const k=await sN(v,b);return n(S=>S.map(j=>j.id===v?k:j)),k},[]),h=i.useCallback(async v=>{await oN(v),n(b=>b.filter(k=>k.id!==v))},[]),f=i.useCallback(async v=>{const b=await lN(v);n(k=>k.map(S=>S.id===v?{...S,status:b.status,updatedAt:b.checkedAt}:S))},[]),p=i.useCallback(v=>iN(v),[]),g=i.useCallback(async(v,b)=>{const k=await aN(v,b);return n(S=>S.map(j=>j.id===v?{...j,dockerConfig:k}:j)),k},[]),x=i.useCallback(async v=>{const b=await rN(v);return"persistedVersion"in b?b:{persistedVersion:0,deployedVersion:null,needsRecreate:!1}},[]);return{nodes:e,loading:s,error:r,refresh:d,register:u,update:m,unregister:h,healthCheck:f,fetchDockerConfig:p,patchDockerConfig:g,fetchDockerDiff:x}}const gr="kb-quick-entry-text",A0=["image/png","image/jpeg","image/gif","image/webp"];function P0(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function mc(e,n){return e&&n?`${e}/${n}`:""}function hc(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 mg({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"&&ss(gr,l)||""),[g,x]=i.useState(!1),[v,b]=i.useState(!1),[k,S]=i.useState(!1),j=i.useRef(null),E=i.useRef(null),y=i.useRef(!1),N=i.useRef(l),[M,D]=i.useState([]),C=i.useRef([]),[_,F]=i.useState([]),[U,A]=i.useState(!1),[$,T]=i.useState(""),[J,B]=i.useState(null),[se,P]=i.useState([]),[O,I]=i.useState(void 0),[w,Y]=i.useState(!1),[re,le]=i.useState(!1),[ve,de]=i.useState(!1),[Fe,X]=i.useState(!1),[L,Q]=i.useState(!1),[ne,H]=i.useState(null),[z,W]=i.useState(void 0),[we,Z]=i.useState(void 0),[fe,Oe]=i.useState(void 0),[Ve,He]=i.useState(void 0),[Je,$e]=i.useState(void 0),[he,ue]=i.useState(void 0),Ee=i.useRef(null),je=i.useRef(null),xe=i.useRef(null),Pe=i.useRef(null),ie=i.useRef(null),Me=i.useRef(null),We=i.useRef(null),mt=i.useRef(null),[st,Ze]=i.useState(null),[dt,Ae]=i.useState(null),[Ue,kt]=i.useState(null),[De,be]=i.useState(null),pe=i.useRef(null),Re=i.useRef(null),[Be,at]=i.useState(null),[me]=i.useState(()=>typeof document<"u"?document.body:null),[ft,Et]=i.useState(!1),[jt,$t]=i.useState(null),[Ft,Rt]=i.useState(a??[]),[It,Vt]=i.useState([]),[Qt,Jt]=i.useState([]),[on,Kt]=i.useState(null),[qt,kn]=i.useState(void 0),[nn,Xt]=i.useState(!1),[Gt,ln]=i.useState(Ds),[ye,Le]=i.useState(void 0),{nodes:ae}=Ul(),[Te,Ne]=i.useState(!1),[ee,Ie]=i.useState(!1),St=i.useRef(null),pt=i.useRef(null),[Dt,Ut]=i.useState(null),Ce=d??It,et=u??Qt,tt=!e;i.useEffect(()=>{if(a)Rt(a),Et(!1),$t(null);else{let G=!1;return Et(!0),$t(null),Os().then(Se=>{G||(Rt(Se.models),d||Vt(Se.favoriteProviders),u||Jt(Se.favoriteModels))}).catch(Se=>{G||$t(_e(Se)||"Failed to load models")}).finally(()=>{G||Et(!1)}),Ll(l).then(Se=>{G||Kt(Se)}).catch(()=>{}),()=>{G=!0}}},[a,d,u,l]);const Lt=mc(z,we),Zt=mc(fe,Ve),sn=mc(Je,he),At=!!(z&&we),cn=!!(fe&&Ve),Tn=!!(Je&&he),En=Number(At)+Number(cn)+Number(Tn),bn=qt?on?.modelPresets?.find(G=>G.id===qt)?.name??"Models":En>0?`${En} model${En===1?"":"s"}`:"Models",In=i.useCallback((G,Se)=>{if(!G||!Se)return"Using default";const it=Ft.find(Ct=>Ct.provider===G&&Ct.id===Se);return it?`${it.provider}/${it.id}`:`${G}/${Se}`},[Ft]);i.useEffect(()=>{p(ss(gr,l)||"")},[l]),i.useEffect(()=>{typeof window<"u"&&vs(gr,f,l)},[f,l]),i.useEffect(()=>{N.current!==l&&(N.current=l,P([]),I(void 0),B(null),Y(!1),Ze(null))},[l]),i.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),i.useEffect(()=>{C.current=M},[M]),i.useEffect(()=>()=>{C.current.forEach(G=>URL.revokeObjectURL(G.previewUrl))},[]);const ge=i.useCallback(()=>{const G=j.current;if(!G)return;G.style.height="auto";const Se=Math.min(G.scrollHeight,200);G.style.height=`${Se}px`},[]);i.useEffect(()=>{v&&ge()},[f,v,ge]),i.useEffect(()=>{if(!g&&f===""&&j.current){const G=setTimeout(()=>{j.current?.focus()},0);return()=>clearTimeout(G)}},[g,f]),i.useEffect(()=>{U||T("")},[U]),i.useEffect(()=>{if(!Te)return;const G=Se=>{const it=Se.target,Ct=St.current?.contains(it),Tt=pt.current?.contains(it);!Ct&&!Tt&&Ne(!1)};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[Te]),i.useEffect(()=>{if(!L)return;const G=Se=>{const it=Se.target,Ct=Ee.current?.contains(it),Tt=je.current?.contains(it),An=it instanceof Element&&it.closest?.(".model-combobox-dropdown--portal")!=null;!Ct&&!Tt&&!An&&(Q(!1),H(null))};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[L]),i.useEffect(()=>{if(!re)return;const G=Se=>{const it=Se.target;ie.current?.contains(it)||Me.current?.contains(it)||(le(!1),Ae(null))};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[re]),i.useEffect(()=>{if(!w)return;const G=Se=>{const it=Se.target;xe.current?.contains(it)||Pe.current?.contains(it)||(Y(!1),Ze(null))};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[w]),i.useEffect(()=>{if(!ve)return;const G=Se=>{const it=Se.target;We.current?.contains(it)||mt.current?.contains(it)||(de(!1),kt(null))};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[ve]);const ut=i.useCallback(()=>{M.forEach(G=>URL.revokeObjectURL(G.previewUrl)),D([]),E.current&&(E.current.value=""),p(""),F([]),B(null),Y(!1),Ze(null),le(!1),Ae(null),de(!1),kt(null),W(void 0),Z(void 0),Oe(void 0),He(void 0),$e(void 0),ue(void 0),kn(void 0),Xt(!1),ln(Ds),Le(void 0),A(!1),Q(!1),be(null),H(null),Ne(!1),Ie(!1),b(!1),S(!1),y.current=!0,j.current&&(j.current.style.height="auto"),typeof window<"u"&&Ja(gr,l)},[M,l]),xn=i.useCallback(G=>{if(!G||G.length===0)return;const Se=[];for(let it=0;it<G.length;it++){const Ct=G[it];A0.includes(Ct.type)&&Se.push({file:Ct,previewUrl:URL.createObjectURL(Ct)})}Se.length>0&&D(it=>[...it,...Se])},[]),oe=i.useCallback(G=>{g||xn(G.clipboardData?.files)},[xn,g]),ct=i.useCallback(G=>{D(Se=>{const it=Se[G];return it&&URL.revokeObjectURL(it.previewUrl),Se.filter((Ct,Tt)=>Tt!==G)})},[]),rt=i.useCallback(async()=>{const G=f.trim();if(!G||g||!e)return;const Se=f;x(!0),p("");try{const it=await e({description:G,column:"triage",dependencies:_.length?_:void 0,...J?{assignedAgentId:J}:{},modelPresetId:qt,modelProvider:At?z:void 0,modelId:At?we:void 0,validatorModelProvider:cn?fe:void 0,validatorModelId:cn?Ve:void 0,planningModelProvider:Tn?Je:void 0,planningModelId:Tn?he:void 0,...nn?{executionMode:"fast"}:{},priority:Gt,nodeId:ye});if(it&&M.length>0){const Ct=[];for(const Tt of M)try{await Ol(it.id,Tt.file,l)}catch{Ct.push(Tt.file.name)}Ct.length>0&&n(`Failed to upload: ${Ct.join(", ")}`,"error")}ut()}catch(it){p(Se),n(_e(it)||"Failed to create task","error")}finally{x(!1)}},[f,g,e,_,J,At,z,we,cn,fe,Ve,Tn,Je,he,M,l,n,ut,nn,Gt,ye]),wt=i.useCallback(G=>{if(G.key==="Enter"){if(G.shiftKey&&v)return;G.preventDefault(),rt()}else if(G.key==="Escape"){if(G.preventDefault(),ne){H(null);return}if(L){Q(!1),be(null);return}if(U){A(!1);return}if(Te){Ne(!1);return}if(re){le(!1),Ae(null);return}if(ve){de(!1),kt(null);return}if(w){Y(!1),Ze(null);return}f.trim()&&(p(""),j.current&&(j.current.style.height="auto"),typeof window<"u"&&Ja(gr,l)),b(!1),S(!1),j.current?.blur()}},[rt,f,v,U,w,re,L,ne,Te,ve,l,S]),ot=i.useCallback(()=>{y.current&&(y.current=!1)},[]),vt=i.useCallback(()=>{c&&b(!0)},[c]),Wt=i.useCallback(G=>{F(Se=>Se.includes(G)?Se.filter(it=>it!==G):[...Se,G])},[]),an=i.useCallback(()=>{const G=window.visualViewport;return G&&G.width>0&&G.height>0?{width:G.width,height:G.height,offsetTop:G.offsetTop,offsetLeft:G.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),pn=i.useCallback(()=>{const G=Ee.current;if(!G)return;const Se=G.getBoundingClientRect(),{width:it,height:Ct,offsetTop:Tt,offsetLeft:An}=an(),vn=16,yn=16,fn=4,Ln=it<=768,Zn=Math.min(Ln?Ct*.6:Ct*.5,360),hs=Math.max(Se.width*1.35,320),On=Ln?Math.min(it-vn*2,360):hs,$n=Math.min(On,Math.max(it-vn*2,240)),Pn=Se.top-Tt,ps=Se.bottom-Tt,qn=Se.left-An,es=Ct-ps,Fn=Pn,rs=Math.max(es-yn-fn,160),ks=Math.max(Fn-yn-fn,160),os=es<Zn&&Fn>es,xs=Math.max(Math.min(os?ks:rs,Zn),160),qs=Math.min(Math.max(qn,vn),it-vn-$n)+An,Fs=os?Math.max(yn+Tt,Pn-xs-fn+Tt):Math.min(ps+fn+Tt,Ct+Tt-yn-xs);be({top:Fs,left:qs,width:$n,maxHeight:xs})},[an]),Hn=i.useCallback(()=>{const G=St.current?.querySelector(".refine-button");if(!G)return;const Se=G.getBoundingClientRect(),{width:it,height:Ct,offsetTop:Tt,offsetLeft:An}=an(),vn=8,yn=12,fn=4,Ln=Math.min(200,Math.max(Ct-yn*2,160)),Zn=Math.min(200,it-vn*2),hs=Se.top-Tt,On=Se.bottom-Tt,$n=Se.left-An,Pn=Ct-On,ps=hs,qn=Pn<Ln&&ps>Pn,es=Math.min(Math.max($n,vn),it-vn-Zn)+An,Fn=qn?Math.max(yn+Tt,hs-Ln-fn+Tt):Math.min(On+fn+Tt,Ct+Tt-yn-Ln);Ut({top:Fn,left:es})},[an]),Mn=i.useCallback(()=>{const G=pe.current;if(!G)return;const Se=G.getBoundingClientRect(),{width:it,height:Ct,offsetTop:Tt,offsetLeft:An}=an(),vn=16,yn=16,fn=4,Ln=it<=768,Zn=Math.min(Ln?Ct*.6:Ct*.5,320),hs=Ln?Math.min(it-vn*2,360):Math.max(Se.width,280),On=Math.min(hs,Math.max(it-vn*2,240)),$n=Se.top-Tt,Pn=Se.bottom-Tt,ps=Se.left-An,qn=Ct-Pn,es=$n,Fn=Math.max(qn-yn-fn,200),rs=Math.max(es-yn-fn,200),ks=qn<Zn&&es>qn,os=Math.max(Math.min(ks?rs:Fn,Zn),200),xs=Math.min(Math.max(ps,vn),it-vn-On)+An,qs=ks?Math.max(yn+Tt,$n-os-fn+Tt):Math.min(Pn+fn+Tt,Ct+Tt-yn-os);at({top:qs,left:xs,width:On,maxHeight:os})},[an]),Qn=i.useCallback(()=>{const G=xe.current?.querySelector("button");if(!G)return;const Se=G.getBoundingClientRect(),{width:it,height:Ct,offsetTop:Tt,offsetLeft:An}=an(),vn=16,yn=16,fn=4,Ln=it<=768,Zn=Math.min(Ln?Ct*.6:Ct*.5,320),hs=Ln?Math.min(it-vn*2,280):Math.max(Se.width,240),On=Math.min(hs,Math.max(it-vn*2,200)),$n=Se.top-Tt,Pn=Se.bottom-Tt,ps=Se.left-An,qn=Ct-Pn,es=$n,Fn=Math.max(qn-yn-fn,160),rs=Math.max(es-yn-fn,160),ks=qn<Zn&&es>qn,os=Math.max(Math.min(ks?rs:Fn,Zn),160),xs=Math.min(Math.max(ps,vn),it-vn-On)+An,qs=ks?Math.max(yn+Tt,$n-os-fn+Tt):Math.min(Pn+fn+Tt,Ct+Tt-yn-os);Ze({top:qs,left:xs,width:On,maxHeight:os})},[an]),ms=i.useCallback(()=>{const G=ie.current?.querySelector("button");if(!G)return;const Se=G.getBoundingClientRect(),{width:it,height:Ct,offsetTop:Tt,offsetLeft:An}=an(),vn=16,yn=16,fn=4,Ln=it<=768,Zn=Math.min(Ln?Ct*.6:Ct*.5,320),hs=Ln?Math.min(it-vn*2,280):Math.max(Se.width,240),On=Math.min(hs,Math.max(it-vn*2,200)),$n=Se.top-Tt,Pn=Se.bottom-Tt,ps=Se.left-An,qn=Ct-Pn,es=$n,Fn=Math.max(qn-yn-fn,160),rs=Math.max(es-yn-fn,160),ks=qn<Zn&&es>qn,os=Math.max(Math.min(ks?rs:Fn,Zn),160),xs=Math.min(Math.max(ps,vn),it-vn-On)+An,qs=ks?Math.max(yn+Tt,$n-os-fn+Tt):Math.min(Pn+fn+Tt,Ct+Tt-yn-os);Ae({top:qs,left:xs,width:On,maxHeight:os})},[an]),Xn=i.useCallback(()=>{const G=We.current?.querySelector("button");if(!G)return;const Se=G.getBoundingClientRect(),{width:it,height:Ct,offsetTop:Tt,offsetLeft:An}=an(),vn=16,yn=16,fn=4,Ln=220,Zn=Math.min(Math.max(Se.width,200),Math.max(it-vn*2,200)),hs=Se.top-Tt,On=Se.bottom-Tt,$n=Se.left-An,Pn=Ct-On,ps=hs,qn=Math.max(Pn-yn-fn,160),es=Math.max(ps-yn-fn,160),Fn=Pn<Ln&&ps>Pn,rs=Math.max(Math.min(Fn?es:qn,Ln),160),ks=Math.min(Math.max($n,vn),it-vn-Zn)+An,os=Fn?Math.max(yn+Tt,hs-rs-fn+Tt):Math.min(On+fn+Tt,Ct+Tt-yn-rs);kt({top:os,left:ks,width:Zn,maxHeight:rs})},[an]);i.useEffect(()=>{if(!L)return;const G=()=>pn();window.addEventListener("resize",G),window.addEventListener("scroll",G,!0);const Se=window.visualViewport;return Se&&(Se.addEventListener("resize",G),Se.addEventListener("scroll",G)),()=>{window.removeEventListener("resize",G),window.removeEventListener("scroll",G,!0),Se&&(Se.removeEventListener("resize",G),Se.removeEventListener("scroll",G))}},[L,pn]),i.useEffect(()=>{if(!Te)return;const G=()=>Hn();window.addEventListener("resize",G),window.addEventListener("scroll",G,!0);const Se=window.visualViewport;return Se&&(Se.addEventListener("resize",G),Se.addEventListener("scroll",G)),()=>{window.removeEventListener("resize",G),window.removeEventListener("scroll",G,!0),Se&&(Se.removeEventListener("resize",G),Se.removeEventListener("scroll",G))}},[Te,Hn]),i.useEffect(()=>{if(!U)return;const G=()=>Mn();window.addEventListener("resize",G),window.addEventListener("scroll",G,!0);const Se=window.visualViewport;return Se&&(Se.addEventListener("resize",G),Se.addEventListener("scroll",G)),()=>{window.removeEventListener("resize",G),window.removeEventListener("scroll",G,!0),Se&&(Se.removeEventListener("resize",G),Se.removeEventListener("scroll",G))}},[U,Mn]),i.useEffect(()=>{if(!w)return;const G=()=>Qn();window.addEventListener("resize",G),window.addEventListener("scroll",G,!0);const Se=window.visualViewport;return Se&&(Se.addEventListener("resize",G),Se.addEventListener("scroll",G)),()=>{window.removeEventListener("resize",G),window.removeEventListener("scroll",G,!0),Se&&(Se.removeEventListener("resize",G),Se.removeEventListener("scroll",G))}},[w,Qn]),i.useEffect(()=>{if(!re)return;const G=()=>ms();window.addEventListener("resize",G),window.addEventListener("scroll",G,!0);const Se=window.visualViewport;return Se&&(Se.addEventListener("resize",G),Se.addEventListener("scroll",G)),()=>{window.removeEventListener("resize",G),window.removeEventListener("scroll",G,!0),Se&&(Se.removeEventListener("resize",G),Se.removeEventListener("scroll",G))}},[re,ms]),i.useEffect(()=>{if(!ve)return;const G=()=>Xn();window.addEventListener("resize",G),window.addEventListener("scroll",G,!0);const Se=window.visualViewport;return Se&&(Se.addEventListener("resize",G),Se.addEventListener("scroll",G)),()=>{window.removeEventListener("resize",G),window.removeEventListener("scroll",G,!0),Se&&(Se.removeEventListener("resize",G),Se.removeEventListener("scroll",G))}},[ve,Xn]);const mn=i.useCallback(G=>{const Se=hc(G);$e(Se.provider),ue(Se.modelId)},[]),Pt=i.useCallback(G=>{const Se=hc(G);W(Se.provider),Z(Se.modelId)},[]),is=i.useCallback(G=>{const Se=hc(G);Oe(Se.provider),He(Se.modelId)},[]),Gn=i.useCallback(async G=>{if(m){m(G);return}const Se=It,Ct=Se.includes(G)?Se.filter(Tt=>Tt!==G):[G,...Se];Vt(Ct);try{await Dn({favoriteProviders:Ct,favoriteModels:Qt})}catch{Vt(Se)}},[It,Qt,m]),K=i.useCallback(async G=>{if(h){h(G);return}const Se=Qt,Ct=Se.includes(G)?Se.filter(Tt=>Tt!==G):[G,...Se];Jt(Ct);try{await Dn({favoriteProviders:It,favoriteModels:Ct})}catch{Jt(Se)}},[Qt,It,h]),Ke=i.useCallback(()=>{const G=f.trim();if(!G){n("Enter a description first","error");return}r?.(G),ut()},[f,r,n,ut]),Ye=i.useCallback(()=>{const G=f.trim();if(!G){n("Enter a description first","error");return}o?.(G),ut()},[f,o,n,ut]),ht=i.useCallback(()=>{rt()},[rt]),Nt=i.useCallback(async G=>{const Se=f.trim();if(!(!Se||ee)){Ne(!1),Ie(!0);try{const it=await Of(Se,G,l);p(it),n("Description refined with AI","success"),j.current&&(j.current.style.height="auto",j.current.style.height=`${Math.min(j.current.scrollHeight,200)}px`)}catch(it){const Ct=Ff(it);n(Ct,"error")}finally{Ie(!1)}}},[f,ee,n,l]),_t=(G,Se)=>G.length>Se?G.slice(0,Se)+"…":G,zt=i.useCallback(async()=>{if(a){Rt(a),$t(null),Et(!1);return}Et(!0),$t(null);try{const G=await Os();Rt(G.models),d||Vt(G.favoriteProviders),u||Jt(G.favoriteModels)}catch(G){$t(_e(G)||"Failed to load models")}finally{Et(!1)}},[a,d,u]),Jn=i.useCallback(async()=>{if(se.length>0&&O===l){Y(!0),Qn();return}X(!0);try{const G=await ba(void 0,l);P(G),I(l),Y(!0),Qn()}catch(G){const Se=_e(G);n(Se?`Failed to load agents: ${Se}`:"Failed to load agents","error"),Y(!1)}finally{X(!1)}},[se.length,O,l,n,Qn]),ce=(J?se.find(G=>G.id===J):void 0)?.name??J,Ge=ye?ae.find(G=>G.id===ye):void 0,lt=k,tn=i.useCallback(()=>{S(G=>{const Se=!G;return b(Se),Se})},[]);return t.jsxs("div",{className:`quick-entry-box ${k?"quick-entry-box--expanded":"quick-entry-box--collapsed"}`,"data-testid":"quick-entry-box",children:[t.jsx("div",{className:"description-with-refine",children:t.jsxs("div",{className:"quick-entry-main-row",children:[t.jsx("div",{className:"quick-entry-textarea-wrap",children:t.jsx("textarea",{ref:j,className:`quick-entry-input ${v?"quick-entry-input--expanded":""}`,placeholder:g?"Creating...":"Add a task...",value:f,onChange:G=>p(G.target.value),onKeyDown:wt,onPaste:oe,onFocus:vt,onBlur:ot,disabled:g||tt,"data-testid":"quick-entry-input",rows:2,"aria-controls":"quick-entry-controls","aria-expanded":k})}),t.jsx("button",{type:"button",className:"btn btn-sm quick-entry-toggle",onClick:tn,"aria-expanded":k,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:k?"Collapse":"Expand",children:k?t.jsx(pi,{size:14}):t.jsx(un,{size:14})})]})}),t.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!lt,"aria-hidden":!lt,children:[lt&&!g&&t.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:Ke,onMouseDown:G=>G.preventDefault(),disabled:!f.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[t.jsx(fi,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:Ye,onMouseDown:G=>G.preventDefault(),disabled:!f.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[t.jsx(Tl,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),t.jsxs("div",{className:"refine-trigger-wrap",ref:St,children:[t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${ee?"refine-button--loading":""}`,onClick:()=>{Ne(G=>{const Se=!G;return Se?Hn():Ut(null),Se})},disabled:!f.trim()||ee,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(ys,{size:12,style:{verticalAlign:"middle"}}),ee?"Refining...":"Refine"]}),Te&&me&&Dt&&aa.createPortal(t.jsxs("div",{ref:pt,className:"refine-menu refine-menu--portal",onMouseDown:G=>G.preventDefault(),style:{position:"fixed",top:`${Dt.top}px`,left:`${Dt.left}px`},children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>Nt("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:()=>Nt("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:()=>Nt("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:()=>Nt("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"})]})]}),me)]}),t.jsx("div",{className:"dep-trigger-wrap",children:t.jsxs("button",{ref:pe,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{A(G=>{const Se=!G;return Se?(Q(!1),be(null),H(null),Y(!1),Ze(null),le(!1),Ae(null),de(!1),kt(null),Mn()):at(null),Se})},children:[t.jsx(Ha,{size:12,style:{verticalAlign:"middle"}}),_.length>0?`${_.length} deps`:"Deps"]})}),U&&me&&Be&&(()=>{const G=$.toLowerCase(),Se=(G?s.filter(it=>it.id.toLowerCase().includes(G)||it.title&&it.title.toLowerCase().includes(G)||it.description&&it.description.toLowerCase().includes(G)):[...s]).sort((it,Ct)=>{const Tt=Ct.createdAt.localeCompare(it.createdAt);if(Tt!==0)return Tt;const An=parseInt(it.id.slice(it.id.lastIndexOf("-")+1),10)||0;return(parseInt(Ct.id.slice(Ct.id.lastIndexOf("-")+1),10)||0)-An});return aa.createPortal(t.jsxs("div",{ref:Re,className:"dep-dropdown dep-dropdown--portal",onMouseDown:it=>it.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:it=>T(it.target.value),onClick:it=>it.stopPropagation()}),Se.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):Se.map(it=>t.jsxs("div",{className:`dep-dropdown-item${_.includes(it.id)?" selected":""}`,onMouseDown:Ct=>Ct.preventDefault(),onClick:()=>Wt(it.id),children:[t.jsx("span",{className:"dep-dropdown-id",children:it.id}),t.jsx("span",{className:"dep-dropdown-title",children:_t(it.title||it.description||it.id,60)})]},it.id))]}),me)})(),t.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>E.current?.click(),children:[t.jsx(_f,{size:12,style:{verticalAlign:"middle"}}),M.length>0?`Attach (${M.length})`:"Attach"]}),t.jsxs("button",{ref:Ee,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{A(!1),Y(!1),Ze(null),le(!1),Ae(null),de(!1),kt(null),H(null),Q(!0),pn()},children:[t.jsx(qr,{size:12,style:{verticalAlign:"middle"}}),bn]}),t.jsx("div",{className:"node-trigger-wrap",ref:ie,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-node-button",onClick:()=>{A(!1),Y(!1),Ze(null),Q(!1),be(null),H(null),de(!1),kt(null),le(G=>{const Se=!G;return Se?ms():Ae(null),Se})},children:[t.jsx(Wr,{size:12,style:{verticalAlign:"middle"}}),` ${Ge?.name??"Node"}`,Ge&&t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(ua,{status:Ge.status,showLabel:!0})})]})}),re&&me&&dt&&aa.createPortal(t.jsxs("div",{ref:Me,className:"dep-dropdown node-picker-dropdown node-picker-dropdown--portal",onMouseDown:G=>G.preventDefault(),style:{position:"fixed",top:`${dt.top}px`,left:`${dt.left}px`,width:`${dt.width}px`,maxHeight:dt.maxHeight?`${dt.maxHeight}px`:void 0,overflowY:dt.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${ye==null?" selected":""}`,onMouseDown:G=>G.preventDefault(),onClick:()=>{Le(void 0),le(!1),Ae(null)},children:t.jsx("span",{className:"node-picker-item-name",children:"Project default / local"})}),ae.map(G=>t.jsxs("div",{className:`dep-dropdown-item node-picker-item${ye===G.id?" selected":""}`,onMouseDown:Se=>Se.preventDefault(),onClick:()=>{Le(G.id),le(!1),Ae(null)},children:[t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(ua,{status:G.status})}),t.jsx("span",{className:"node-picker-item-name",children:G.name}),t.jsx("span",{className:"node-picker-item-status",children:P0(G.status)})]},G.id))]}),me),t.jsx("div",{className:"agent-trigger-wrap",ref:xe,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{w?(Y(!1),Ze(null)):(le(!1),Ae(null),de(!1),kt(null),Jn())},"data-testid":"quick-entry-agent-button",children:[t.jsx(zn,{size:12,style:{verticalAlign:"middle"}}),ce?` ${ce}`:" Agent"]})}),w&&me&&st&&aa.createPortal(t.jsxs("div",{ref:Pe,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:G=>G.preventDefault(),style:{position:"fixed",top:`${st.top}px`,left:`${st.left}px`,width:`${st.width}px`,maxHeight:st.maxHeight?`${st.maxHeight}px`:void 0,overflowY:st.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),Fe&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!Fe&&se.map(G=>t.jsxs("div",{className:`dep-dropdown-item${J===G.id?" selected":""}`,onMouseDown:Se=>Se.preventDefault(),onClick:()=>{B(G.id===J?null:G.id),Y(!1),Ze(null)},children:[t.jsx(zn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:G.role}),t.jsx("span",{className:"dep-dropdown-title",children:G.name})]},G.id)),!Fe&&se.length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),J&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:G=>G.preventDefault(),onClick:()=>{B(null),Y(!1),Ze(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),me),t.jsx("div",{className:"priority-trigger-wrap",ref:We,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-priority-button",onClick:()=>{A(!1),Y(!1),Ze(null),le(!1),Ae(null),Q(!1),be(null),H(null),de(G=>{const Se=!G;return Se?Xn():kt(null),Se})},children:[t.jsx(Av,{size:12,style:{verticalAlign:"middle"}}),` ${Gt[0].toUpperCase()}${Gt.slice(1)}`]})}),ve&&me&&Ue&&aa.createPortal(t.jsxs("div",{ref:mt,className:"dep-dropdown priority-picker-dropdown priority-picker-dropdown--portal",onMouseDown:G=>G.preventDefault(),style:{position:"fixed",top:`${Ue.top}px`,left:`${Ue.left}px`,width:`${Ue.width}px`,maxHeight:Ue.maxHeight?`${Ue.maxHeight}px`:void 0,overflowY:Ue.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select priority"}),mo.map(G=>{const Se=`${G[0].toUpperCase()}${G.slice(1)}`;return t.jsx("div",{className:`dep-dropdown-item${Gt===G?" selected":""}`,"data-testid":`quick-entry-priority-option-${G}`,onMouseDown:it=>it.preventDefault(),onClick:()=>{ln(G),de(!1),kt(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:Se})},G)})]}),me),t.jsx("button",{type:"button",className:`btn btn-sm ${nn?"btn-primary":""}`,onClick:()=>Xt(G=>!G),onMouseDown:G=>G.preventDefault(),"aria-pressed":nn,"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:ht,onMouseDown:G=>G.preventDefault(),disabled:!f.trim()||g,"data-testid":"quick-entry-save",title:"Create task",children:[t.jsx(Af,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),M.length>0&&t.jsx("div",{className:"inline-create-previews",children:M.map((G,Se)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:G.previewUrl,alt:G.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>ct(Se),disabled:g,title:"Remove image","data-testid":`quick-entry-preview-remove-${Se}`,children:"×"})]},G.previewUrl))}),L&&me&&De&&aa.createPortal(t.jsx("div",{ref:je,className:"model-nested-menu model-nested-menu--portal",onMouseDown:G=>G.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${De.top}px`,left:`${De.left}px`,width:`${De.width}px`,maxHeight:De.maxHeight?`${De.maxHeight}px`:void 0,overflowY:De.maxHeight?"auto":void 0},children:ne===null?t.jsxs("div",{className:"model-menu-items",children:[t.jsxs("button",{type:"button",className:`model-menu-item ${Tn?"model-menu-item--active":""}`,onClick:()=>H("plan"),"data-testid":"model-menu-plan",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(fi,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),t.jsx("span",{className:"model-menu-item-value",children:Tn?In(Je,he):"Using default"}),t.jsx(Un,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${At?"model-menu-item--active":""}`,onClick:()=>H("executor"),"data-testid":"model-menu-executor",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(ys,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),t.jsx("span",{className:"model-menu-item-value",children:At?In(z,we):"Using default"}),t.jsx(Un,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${cn?"model-menu-item--active":""}`,onClick:()=>H("validator"),"data-testid":"model-menu-validator",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(qr,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Reviewer"]}),t.jsx("span",{className:"model-menu-item-value",children:cn?In(fe,Ve):"Using default"}),t.jsx(Un,{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:()=>H(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:[ne==="plan"&&"Plan Model",ne==="executor"&&"Executor Model",ne==="validator"&&"Reviewer Model"]}),t.jsx(Ns,{models:Ft,value:ne==="plan"?sn:ne==="executor"?Lt:Zt,onChange:ne==="plan"?mn:ne==="executor"?Pt:is,placeholder:"Using default",disabled:ft,id:`model-${ne}-select`,label:`${ne} model`,favoriteProviders:Ce,onToggleFavorite:Gn,favoriteModels:et,onToggleModelFavorite:K}),jt&&t.jsxs("div",{className:"model-submenu-error",children:[t.jsx("span",{children:jt}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:zt,children:"Retry"})]})]})}),me)]}),t.jsx("input",{ref:E,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:G=>{xn(G.target.files),G.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),t.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function R0(e){return au(e)||e}function T0(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 I0(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,v=o.get(x)||[];v.push(g),o.set(x,v)}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 v=l.get(x);return v&&(v.column==="done"||v.column==="in-review"||v.column==="archived")})),m=T0(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:R0(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 Dm=100,pc=50,Lm=25;function $0({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:v,onDeleteTask:b,onArchiveAllDone:k,collapsed:S,onToggleCollapse:j,allTasks:E,availableModels:y,onPlanningMode:N,onSubtaskBreakdown:M,onOpenDetailWithTab:D,favoriteProviders:C,favoriteModels:_,onToggleFavorite:F,onToggleModelFavorite:U,isSearchActive:A,taskStuckTimeoutMs:$,onOpenMission:T,lastFetchTimeMs:J,workflowStepNameLookup:B}){const[se,P]=i.useState(!1),[O,I]=i.useState(pc),[w,Y]=i.useState(!1),[re,le]=i.useState(!1),[ve,de]=i.useState(!1),[Fe,X]=i.useState(!1),L=i.useRef(null),Q=AS(n.length),{confirm:ne}=Qs();i.useEffect(()=>{if(!w)return;function Me(mt){L.current?.contains(mt.target)||Y(!1)}function We(mt){mt.key==="Escape"&&Y(!1)}return document.addEventListener("mousedown",Me),document.addEventListener("keydown",We),()=>{document.removeEventListener("mousedown",Me),document.removeEventListener("keydown",We)}},[w]);const H=e==="archived",z=H&&S,W=!H&&!A&&e!=="in-progress"&&n.length>Dm;i.useEffect(()=>{I(Me=>e==="in-progress"||H||n.length<=Dm?pc:Math.min(Math.max(Me,pc),n.length))},[e,H,n.length]);const we=i.useCallback(Me=>{H||(Me.preventDefault(),Me.dataTransfer.dropEffect="move",P(!0))},[H]),Z=i.useCallback(Me=>{Me.currentTarget.contains(Me.relatedTarget)||P(!1)},[]),fe=i.useCallback(async Me=>{Me.preventDefault(),P(!1);const We=Me.dataTransfer.getData("text/plain");if(!We)return;const mt=n.find(st=>st.id===We);if(!(mt&&mt.column===e))try{const Ze=(E?.find(Ue=>Ue.id===We)??mt)?.steps.some(Ue=>Ue.status!=="pending")??!1,dt=(e==="todo"||e==="triage")&&Ze;let Ae;if(dt){if(await ne({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Ae={preserveProgress:!0};else if(!await ne({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await r(We,e,Ae)}catch(st){c(_e(st),"error")}},[c,E,e,ne,r,n]),Oe=i.useMemo(()=>e!=="in-progress"?[]:I0(n,n,a),[e,n,a]),Ve=i.useMemo(()=>W?n.slice(0,O):n,[W,n,O]),He=Math.max(0,n.length-Ve.length),Je=i.useCallback(()=>{I(Me=>Math.min(Me+Lm,n.length))},[n.length]),$e=i.useCallback(async()=>{if(Y(!1),!(n.length===0||!await ne({title:"Replan All Tasks",message:`Move all ${n.length} todo task${n.length===1?"":"s"} back to planning to be replanned?`}))){le(!0);try{const We=await Promise.allSettled(n.map(Ze=>r(Ze.id,"triage"))),mt=We.filter(Ze=>Ze.status==="rejected").length,st=We.length-mt;mt===0?c(`Moved ${st} task${st===1?"":"s"} to planning for replanning`,"success"):c(`Moved ${st} of ${We.length} tasks; ${mt} failed`,"error")}finally{le(!1)}}},[n,r,c,ne]),he=i.useMemo(()=>n.filter(Me=>!Me.paused&&!Me.assignedAgentId),[n]),ue=he.length,Ee=e==="todo"||e==="in-progress"||e==="in-review",je=re||ve||Fe,xe=i.useCallback(async()=>{if(!(!o||(Y(!1),ue===0)||!await ne({title:"Stop All Tasks",message:`Stop all ${ue} ${cs[e].toLowerCase()} task${ue===1?"":"s"}?`,danger:!0}))){de(!0);try{const We=await Promise.allSettled(he.map(Ze=>o(Ze.id))),mt=We.filter(Ze=>Ze.status==="rejected").length,st=We.length-mt;mt===0?c(`Stopped ${st} task${st===1?"":"s"}`,"success"):c(`Stopped ${st} of ${We.length} tasks; ${mt} failed`,"error")}finally{de(!1)}}},[o,ue,e,he,c,ne]),Pe=i.useCallback(async()=>{if(Y(!1),n.length===0||!await ne({title:"Move All to Todo",message:`Move all ${n.length} ${cs[e].toLowerCase()} task${n.length===1?"":"s"} to Todo?`}))return;const We=n.some(st=>st.steps.some(Ze=>Ze.status!=="pending"));let mt=!1;if(We){if(await ne({title:"Preserve Progress?",message:"Some tasks have completed steps. Keep progress before moving to Todo?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))mt=!0;else if(!await ne({title:"Reset Progress?",message:"Reset step progress for tasks before moving to Todo?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}X(!0);try{const st=await Promise.allSettled(n.map(Ae=>r(Ae.id,"todo",mt?{preserveProgress:!0}:void 0))),Ze=st.filter(Ae=>Ae.status==="rejected").length,dt=st.length-Ze;Ze===0?c(`Moved ${dt} task${dt===1?"":"s"} to Todo`,"success"):c(`Moved ${dt} of ${st.length} tasks to Todo; ${Ze} failed`,"error")}finally{X(!1)}},[n,e,r,c,ne]),ie=i.useCallback(async()=>{if(!(!k||n.length===0||!await ne({title:"Archive All Done",message:`Archive all ${n.length} done tasks?`,danger:!0})))try{const We=await k();c(`Archived ${We.length} tasks`,"success")}catch(We){c(_e(We)||"Failed to archive tasks","error")}},[k,n.length,c,ne]);return t.jsxs("div",{className:`column${se?" drag-over":""}${H?" column-archived":""}${z?" column-collapsed":""}`,"data-column":e,onDragOver:we,onDragLeave:Z,onDrop:fe,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${Q?" 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"&&k&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:ie,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:t.jsx(Zr,{})}),H&&j&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:j,title:S?"Expand archived tasks":"Collapse archived tasks","aria-label":S?"Expand archived tasks":"Collapse archived tasks",children:S?t.jsx(un,{size:16}):t.jsx(pi,{size:16})}),Ee&&t.jsxs("div",{className:"column-menu",ref:L,children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Y(Me=>!Me),"aria-haspopup":"menu","aria-expanded":w,"aria-label":`${cs[e]} column actions`,title:"Column actions",disabled:je,children:t.jsx(uv,{})}),w&&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 $e(),disabled:n.length===0||re,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 xe(),disabled:ue===0||ve||!o,children:["Stop All",t.jsx("span",{className:"column-menu-item-hint",children:n.length===0?"No tasks in this column":ue===0?"No manually pausable tasks":`Pause ${ue} active unassigned task${ue===1?"":"s"}`})]}),t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Pe(),disabled:n.length===0||Fe,children:["Move All to Todo",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Todo"]})]})]})]})]})]}),!z&&t.jsx("p",{className:"column-desc",children:_S[e]}),!z&&t.jsxs("div",{className:"column-body",children:[e==="triage"&&d&&t.jsx(mg,{onCreate:d,addToast:c,tasks:E??[],availableModels:y,onPlanningMode:N,onSubtaskBreakdown:M,projectId:s,autoExpand:!1,favoriteProviders:C,favoriteModels:_,onToggleFavorite:F,onToggleModelFavorite:U}),e==="in-progress"?Oe.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):Oe.map(Me=>t.jsx(ug,{label:Me.label,activeTasks:Me.activeTasks,queuedTasks:Me.queuedTasks,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onOpenDetailWithTab:D,taskStuckTimeoutMs:$,onOpenMission:T,lastFetchTimeMs:J,workflowStepNameLookup:B},Me.label)):n.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):t.jsxs(t.Fragment,{children:[Ve.map(Me=>t.jsx(Jr,{task:Me,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:x,onUnarchiveTask:v,onDeleteTask:b,onOpenDetailWithTab:D,taskStuckTimeoutMs:$,onOpenMission:T,onMoveTask:r,lastFetchTimeMs:J,workflowStepNameLookup:B},Me.id)),W&&He>0&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Je,children:["Load ",Math.min(Lm,He)," more (",He," remaining)"]})]}),t.jsx(qi,{slotId:"board-column-footer",projectId:s})]})]})}const hg=i.memo($0);hg.displayName="Column";const fc={low:0,normal:1,high:2,urgent:3};function Om(e){return!e||!(e in fc)?fc.normal:fc[e]}function pg(e,n){return Om(n)-Om(e)}function Ed(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 D0(e){return[...e].sort((n,s)=>{const a=pg(n.priority,s.priority);return a!==0?a:n.createdAt!==s.createdAt?n.createdAt.localeCompare(s.createdAt):Ed(n.id,s.id)})}function Fm(e){const n=e.columnMovedAt??e.updatedAt??e.createdAt,s=Date.parse(n);return Number.isFinite(s)?s:0}function L0(e,n){return n==="todo"?D0(e):[...e].sort((s,a)=>{if(n==="done"){const o=Fm(a)-Fm(s);return o!==0?o:Ed(s.id,a.id)}if(n==="in-review"){const o=s.status==="merging"||s.status==="merging-pr"||s.status==="merging-fix",l=a.status==="merging"||a.status==="merging-pr"||a.status==="merging-fix";if(o!==l)return o?-1:1}const r=pg(s.priority,a.priority);return r!==0?r:Ed(s.id,a.id)})}function O0(e,n){return e.length!==n.length?!1:e.every((s,a)=>s===n[a])}const zm=new Map;function F0(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 z0({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:v,onArchiveAllDone:b,onLoadArchivedTasks:k,searchQuery:S="",availableModels:j,onPlanningMode:E,onSubtaskBreakdown:y,onOpenDetailWithTab:N,favoriteProviders:M,favoriteModels:D,onToggleFavorite:C,onToggleModelFavorite:_,taskStuckTimeoutMs:F,onOpenMission:U,lastFetchTimeMs:A}){const[$,T]=i.useState(!0),J=i.useRef(!1),{fetchBatch:B}=zS(n),se=i.useRef(null),[P,O]=i.useState(zm),I=S.trim()!=="",w=i.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),Y=i.useCallback(()=>{T(ve=>{const de=!ve;return!de&&!J.current&&k&&(J.current=!0,k()),de})},[k]),re=i.useMemo(()=>{const ve=Object.fromEntries(la.map(X=>[X,[]]));for(const X of e)ve[X.column].push(X);const de=w.current,Fe={};for(const X of la){const L=L0(ve[X],X);Fe[X]=O0(de[X],L)?de[X]:L}return w.current=Fe,Fe},[e]);i.useEffect(()=>{let ve=!1;return lo(n).then(de=>{if(ve)return;const Fe=new Map(de.map(X=>[X.id,X.name]));O(X=>F0(X,Fe)?X:Fe)}).catch(()=>{ve||O(de=>de.size===0?de:zm)}),()=>{ve=!0}},[n]);const le=i.useMemo(()=>e.filter(ve=>ve.prInfo||ve.issueInfo).map(ve=>ve.id),[e]);return i.useEffect(()=>{if(le.length!==0)return se.current&&clearTimeout(se.current),se.current=setTimeout(()=>{const ve=[];for(let de=0;de<le.length;de+=50)ve.push(le.slice(de,de+50));ve.forEach(de=>{B(de)})},500),()=>{se.current&&clearTimeout(se.current)}},[le,B]),t.jsx(t.Fragment,{children:t.jsx("main",{className:"board",id:"board",children:la.map(ve=>t.jsx(hg,{column:ve,tasks:re[ve],projectId:n,maxConcurrent:s,onMoveTask:a,onPauseTask:r,onOpenDetail:o,addToast:l,globalPaused:h,onUpdateTask:f,onRetryTask:p,onArchiveTask:g,onUnarchiveTask:x,onDeleteTask:v,allTasks:e,availableModels:j,onOpenDetailWithTab:N,favoriteProviders:M,favoriteModels:D,onToggleFavorite:C,onToggleModelFavorite:_,isSearchActive:I,taskStuckTimeoutMs:F,onOpenMission:U,lastFetchTimeMs:A,workflowStepNameLookup:P,...ve==="triage"?{onQuickCreate:c,onNewTask:d,onPlanningMode:E,onSubtaskBreakdown:y}:{},...ve==="in-review"?{autoMerge:u,onToggleAutoMerge:m}:{},...ve==="done"?{onArchiveAllDone:b}:{},...ve==="archived"?{collapsed:$,onToggleCollapse:Y}:{}},ve))})})}function _i(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 U0(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let Ua=0,zr=null;function B0(){if(typeof window>"u")return;if(Ua>0){Ua+=1;return}const e=document.documentElement,n=document.body;zr={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=`-${zr.scrollY}px`,n.style.left="0",n.style.right="0",n.style.width="100%",n.style.overflow="hidden",Ua=1}function H0(){if(typeof window>"u"||Ua===0||(Ua-=1,Ua>0||!zr))return;const e=document.documentElement,n=document.body,{htmlOverflow:s,bodyPosition:a,bodyTop:r,bodyLeft:o,bodyRight:l,bodyWidth:c,bodyOverflow:d,scrollY:u}=zr;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,zr=null,window.scrollTo(0,0)}function Mi(e){i.useEffect(()=>{if(!(!e||!U0()))return B0(),()=>{H0()}},[e])}function Fi(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 q0(e,n){const s={};return(e[e.length-1]===""?[...e,""]:e).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const V0=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,W0=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,K0={};function Um(e,n){return(K0.jsx?W0:V0).test(e)}const G0=/[ \t\n\f\r]/g;function J0(e){return typeof e=="object"?e.type==="text"?Bm(e.value):!1:Bm(e)}function Bm(e){return e.replace(G0,"")===""}class ho{constructor(n,s,a){this.normal=s,this.property=n,a&&(this.space=a)}}ho.prototype.normal={};ho.prototype.property={};ho.prototype.space=void 0;function fg(e,n){const s={},a={};for(const r of e)Object.assign(s,r.property),Object.assign(a,r.normal);return new ho(s,a,n)}function _d(e){return e.toLowerCase()}class Hs{constructor(n,s){this.attribute=s,this.property=n}}Hs.prototype.attribute="";Hs.prototype.booleanish=!1;Hs.prototype.boolean=!1;Hs.prototype.commaOrSpaceSeparated=!1;Hs.prototype.commaSeparated=!1;Hs.prototype.defined=!1;Hs.prototype.mustUseProperty=!1;Hs.prototype.number=!1;Hs.prototype.overloadedBoolean=!1;Hs.prototype.property="";Hs.prototype.spaceSeparated=!1;Hs.prototype.space=void 0;let Y0=0;const rn=xa(),bs=xa(),Md=xa(),xt=xa(),Vn=xa(),Ba=xa(),Ws=xa();function xa(){return 2**++Y0}const Ad=Object.freeze(Object.defineProperty({__proto__:null,boolean:rn,booleanish:bs,commaOrSpaceSeparated:Ws,commaSeparated:Ba,number:xt,overloadedBoolean:Md,spaceSeparated:Vn},Symbol.toStringTag,{value:"Module"})),gc=Object.keys(Ad);class ou extends Hs{constructor(n,s,a,r){let o=-1;if(super(n,s),Hm(this,"space",r),typeof a=="number")for(;++o<gc.length;){const l=gc[o];Hm(this,gc[o],(a&Ad[l])===Ad[l])}}}ou.prototype.defined=!0;function Hm(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 ou(a,e.transform(e.attributes||{},a),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(a)&&(o.mustUseProperty=!0),n[a]=o,s[_d(a)]=a,s[_d(o.attribute)]=a}return new ho(n,s,e.space)}const gg=rr({properties:{ariaActiveDescendant:null,ariaAtomic:bs,ariaAutoComplete:null,ariaBusy:bs,ariaChecked:bs,ariaColCount:xt,ariaColIndex:xt,ariaColSpan:xt,ariaControls:Vn,ariaCurrent:null,ariaDescribedBy:Vn,ariaDetails:null,ariaDisabled:bs,ariaDropEffect:Vn,ariaErrorMessage:null,ariaExpanded:bs,ariaFlowTo:Vn,ariaGrabbed:bs,ariaHasPopup:null,ariaHidden:bs,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Vn,ariaLevel:xt,ariaLive:null,ariaModal:bs,ariaMultiLine:bs,ariaMultiSelectable:bs,ariaOrientation:null,ariaOwns:Vn,ariaPlaceholder:null,ariaPosInSet:xt,ariaPressed:bs,ariaReadOnly:bs,ariaRelevant:null,ariaRequired:bs,ariaRoleDescription:Vn,ariaRowCount:xt,ariaRowIndex:xt,ariaRowSpan:xt,ariaSelected:bs,ariaSetSize:xt,ariaSort:null,ariaValueMax:xt,ariaValueMin:xt,ariaValueNow:xt,ariaValueText:null,role:null},transform(e,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function bg(e,n){return n in e?e[n]:n}function xg(e,n){return bg(e,n.toLowerCase())}const Q0=rr({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Ba,acceptCharset:Vn,accessKey:Vn,action:null,allow:null,allowFullScreen:rn,allowPaymentRequest:rn,allowUserMedia:rn,alt:null,as:null,async:rn,autoCapitalize:null,autoComplete:Vn,autoFocus:rn,autoPlay:rn,blocking:Vn,capture:null,charSet:null,checked:rn,cite:null,className:Vn,cols:xt,colSpan:null,content:null,contentEditable:bs,controls:rn,controlsList:Vn,coords:xt|Ba,crossOrigin:null,data:null,dateTime:null,decoding:null,default:rn,defer:rn,dir:null,dirName:null,disabled:rn,download:Md,draggable:bs,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:rn,formTarget:null,headers:Vn,height:xt,hidden:Md,high:xt,href:null,hrefLang:null,htmlFor:Vn,httpEquiv:Vn,id:null,imageSizes:null,imageSrcSet:null,inert:rn,inputMode:null,integrity:null,is:null,isMap:rn,itemId:null,itemProp:Vn,itemRef:Vn,itemScope:rn,itemType:Vn,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:rn,low:xt,manifest:null,max:null,maxLength:xt,media:null,method:null,min:null,minLength:xt,multiple:rn,muted:rn,name:null,nonce:null,noModule:rn,noValidate:rn,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:rn,optimum:xt,pattern:null,ping:Vn,placeholder:null,playsInline:rn,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:rn,referrerPolicy:null,rel:Vn,required:rn,reversed:rn,rows:xt,rowSpan:xt,sandbox:Vn,scope:null,scoped:rn,seamless:rn,selected:rn,shadowRootClonable:rn,shadowRootDelegatesFocus:rn,shadowRootMode:null,shape:null,size:xt,sizes:null,slot:null,span:xt,spellCheck:bs,src:null,srcDoc:null,srcLang:null,srcSet:null,start:xt,step:null,style:null,tabIndex:xt,target:null,title:null,translate:null,type:null,typeMustMatch:rn,useMap:null,value:bs,width:xt,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Vn,axis:null,background:null,bgColor:null,border:xt,borderColor:null,bottomMargin:xt,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:rn,declare:rn,event:null,face:null,frame:null,frameBorder:null,hSpace:xt,leftMargin:xt,link:null,longDesc:null,lowSrc:null,marginHeight:xt,marginWidth:xt,noResize:rn,noHref:rn,noShade:rn,noWrap:rn,object:null,profile:null,prompt:null,rev:null,rightMargin:xt,rules:null,scheme:null,scrolling:bs,standby:null,summary:null,text:null,topMargin:xt,valueType:null,version:null,vAlign:null,vLink:null,vSpace:xt,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:rn,disableRemotePlayback:rn,prefix:null,property:null,results:xt,security:null,unselectable:null},space:"html",transform:xg}),X0=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:Ws,accentHeight:xt,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:xt,amplitude:xt,arabicForm:null,ascent:xt,attributeName:null,attributeType:null,azimuth:xt,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:xt,by:null,calcMode:null,capHeight:xt,className:Vn,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:xt,diffuseConstant:xt,direction:null,display:null,dur:null,divisor:xt,dominantBaseline:null,download:rn,dx:null,dy:null,edgeMode:null,editable:null,elevation:xt,enableBackground:null,end:null,event:null,exponent:xt,externalResourcesRequired:null,fill:null,fillOpacity:xt,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:Ba,g2:Ba,glyphName:Ba,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:xt,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:xt,horizOriginX:xt,horizOriginY:xt,id:null,ideographic:xt,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:xt,k:xt,k1:xt,k2:xt,k3:xt,k4:xt,kernelMatrix:Ws,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:xt,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:xt,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:xt,overlineThickness:xt,paintOrder:null,panose1:null,path:null,pathLength:xt,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Vn,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:xt,pointsAtY:xt,pointsAtZ:xt,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Ws,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Ws,rev:Ws,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Ws,requiredFeatures:Ws,requiredFonts:Ws,requiredFormats:Ws,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:xt,specularExponent:xt,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:xt,strikethroughThickness:xt,string:null,stroke:null,strokeDashArray:Ws,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:xt,strokeOpacity:xt,strokeWidth:null,style:null,surfaceScale:xt,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Ws,tabIndex:xt,tableValues:null,target:null,targetX:xt,targetY:xt,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Ws,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:xt,underlineThickness:xt,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:xt,values:null,vAlphabetic:xt,vMathematical:xt,vectorEffect:null,vHanging:xt,vIdeographic:xt,version:null,vertAdvY:xt,vertOriginX:xt,vertOriginY:xt,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:xt,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:bg}),vg=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()}}),yg=rr({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:xg}),wg=rr({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),Z0={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"},eC=/[A-Z]/g,qm=/-[a-z]/g,tC=/^data[-\w.:]+$/i;function nC(e,n){const s=_d(n);let a=n,r=Hs;if(s in e.normal)return e.property[e.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&tC.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(qm,iC);a="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!qm.test(o)){let l=o.replace(eC,sC);l.charAt(0)!=="-"&&(l="-"+l),n="data"+l}}r=ou}return new r(a,n)}function sC(e){return"-"+e.toLowerCase()}function iC(e){return e.charAt(1).toUpperCase()}const aC=fg([gg,Q0,vg,yg,wg],"html"),lu=fg([gg,X0,vg,yg,wg],"svg");function rC(e){return e.join(" ").trim()}var Ma={},bc,Vm;function oC(){if(Vm)return bc;Vm=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=`
654
- `,u="/",m="*",h="",f="comment",p="declaration";function g(v,b){if(typeof v!="string")throw new TypeError("First argument must be a string");if(!v)return[];b=b||{};var k=1,S=1;function j(A){var $=A.match(n);$&&(k+=$.length);var T=A.lastIndexOf(d);S=~T?A.length-T:S+A.length}function E(){var A={line:k,column:S};return function($){return $.position=new y(A),D(),$}}function y(A){this.start=A,this.end={line:k,column:S},this.source=b.source}y.prototype.content=v;function N(A){var $=new Error(b.source+":"+k+":"+S+": "+A);if($.reason=A,$.filename=b.source,$.line=k,$.column=S,$.source=v,!b.silent)throw $}function M(A){var $=A.exec(v);if($){var T=$[0];return j(T),v=v.slice(T.length),$}}function D(){M(s)}function C(A){var $;for(A=A||[];$=_();)$!==!1&&A.push($);return A}function _(){var A=E();if(!(u!=v.charAt(0)||m!=v.charAt(1))){for(var $=2;h!=v.charAt($)&&(m!=v.charAt($)||u!=v.charAt($+1));)++$;if($+=2,h===v.charAt($-1))return N("End of comment missing");var T=v.slice(2,$-2);return S+=2,j(T),v=v.slice($),S+=2,A({type:f,comment:T})}}function F(){var A=E(),$=M(a);if($){if(_(),!M(r))return N("property missing ':'");var T=M(o),J=A({type:p,property:x($[0].replace(e,h)),value:T?x(T[0].replace(e,h)):h});return M(l),J}}function U(){var A=[];C(A);for(var $;$=F();)$!==!1&&(A.push($),C(A));return A}return D(),U()}function x(v){return v?v.replace(c,h):h}return bc=g,bc}var Wm;function lC(){if(Wm)return Ma;Wm=1;var e=Ma&&Ma.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(Ma,"__esModule",{value:!0}),Ma.default=s;const n=e(oC());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 Ma}var br={},Km;function cC(){if(Km)return br;Km=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 xr,Gm;function dC(){if(Gm)return xr;Gm=1;var e=xr&&xr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=e(lC()),s=cC();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,xr=a,xr}var uC=dC();const mC=bf(uC),kg=jg("end"),cu=jg("start");function jg(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 hC(e){const n=cu(e),s=kg(e);if(n&&s)return{start:n,end:s}}function Ur(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Jm(e.position):"start"in e||"end"in e?Jm(e):"line"in e||"column"in e?Pd(e):""}function Pd(e){return Ym(e&&e.line)+":"+Ym(e&&e.column)}function Jm(e){return Pd(e&&e.start)+"-"+Pd(e&&e.end)}function Ym(e){return e&&typeof e=="number"?e:1}class Ts 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=Ur(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}}Ts.prototype.file="";Ts.prototype.name="";Ts.prototype.reason="";Ts.prototype.message="";Ts.prototype.stack="";Ts.prototype.column=void 0;Ts.prototype.line=void 0;Ts.prototype.ancestors=void 0;Ts.prototype.cause=void 0;Ts.prototype.fatal=void 0;Ts.prototype.place=void 0;Ts.prototype.ruleId=void 0;Ts.prototype.source=void 0;const du={}.hasOwnProperty,pC=new Map,fC=/[A-Z]/g,gC=new Set(["table","tbody","thead","tfoot","tr"]),bC=new Set(["td","th"]),Ng="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function xC(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=CC(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=SC(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"?lu:aC,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=Sg(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function Sg(e,n,s){if(n.type==="element")return vC(e,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return yC(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return kC(e,n,s);if(n.type==="mdxjsEsm")return wC(e,n);if(n.type==="root")return jC(e,n,s);if(n.type==="text")return NC(e,n)}function vC(e,n,s){const a=e.schema;let r=a;n.tagName.toLowerCase()==="svg"&&a.space==="html"&&(r=lu,e.schema=r),e.ancestors.push(n);const o=Eg(e,n.tagName,!1),l=EC(e,n);let c=mu(e,n);return gC.has(n.tagName)&&(c=c.filter(function(d){return typeof d=="string"?!J0(d):!0})),Cg(e,l,o,n),uu(l,c),e.ancestors.pop(),e.schema=a,e.create(n,o,l,s)}function yC(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)}Yr(e,n.position)}function wC(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);Yr(e,n.position)}function kC(e,n,s){const a=e.schema;let r=a;n.name==="svg"&&a.space==="html"&&(r=lu,e.schema=r),e.ancestors.push(n);const o=n.name===null?e.Fragment:Eg(e,n.name,!0),l=_C(e,n),c=mu(e,n);return Cg(e,l,o,n),uu(l,c),e.ancestors.pop(),e.schema=a,e.create(n,o,l,s)}function jC(e,n,s){const a={};return uu(a,mu(e,n)),e.create(n,e.Fragment,a,s)}function NC(e,n){return n.value}function Cg(e,n,s,a){typeof s!="string"&&s!==e.Fragment&&e.passNode&&(n.node=a)}function uu(e,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(e.children=s)}}function SC(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 CC(e,n){return s;function s(a,r,o,l){const c=Array.isArray(o.children),d=cu(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 EC(e,n){const s={};let a,r;for(r in n.properties)if(r!=="children"&&du.call(n.properties,r)){const o=MC(e,r,n.properties[r]);if(o){const[l,c]=o;e.tableCellAlignToStyle&&l==="align"&&typeof c=="string"&&bC.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 _C(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 Yr(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 Yr(e,n.position);else o=a.value===null?!0:a.value;s[r]=o}return s}function mu(e,n){const s=[];let a=-1;const r=e.passKeys?new Map:pC;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=Sg(e,o,l);c!==void 0&&s.push(c)}return s}function MC(e,n,s){const a=nC(e.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=a.commaSeparated?q0(s):rC(s)),a.property==="style"){let r=typeof s=="object"?s:AC(e,String(s));return e.stylePropertyNameCase==="css"&&(r=PC(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&a.space?Z0[a.property]||a.property:a.attribute,s]}}function AC(e,n){try{return mC(n,{reactCompat:!0})}catch(s){if(e.ignoreInvalidStyle)return{};const a=s,r=new Ts("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=Ng+"#cannot-parse-style-attribute",r}}function Eg(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=Um(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=Um(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(a.type==="Literal"){const r=a.value;return du.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(a);Yr(e)}function Yr(e,n){const s=new Ts("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=Ng+"#cannot-handle-mdx-estrees-without-createevaluater",s}function PC(e){const n={};let s;for(s in e)du.call(e,s)&&(n[RC(s)]=e[s]);return n}function RC(e){let n=e.replace(fC,TC);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function TC(e){return"-"+e.toLowerCase()}const xc={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"]},IC={};function hu(e,n){const s=IC,a=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return _g(e,a,r)}function _g(e,n,s){if($C(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 Qm(e.children,n,s)}return Array.isArray(e)?Qm(e,n,s):""}function Qm(e,n,s){const a=[];let r=-1;for(;++r<e.length;)a[r]=_g(e[r],n,s);return a.join("")}function $C(e){return!!(e&&typeof e=="object")}const Xm=document.createElement("i");function pu(e){const n="&"+e+";";Xm.innerHTML=n;const s=Xm.textContent;return s.charCodeAt(s.length-1)===59&&e!=="semi"||s===n?!1:s}function Js(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 ai(e,n){return e.length>0?(Js(e,e.length,0,n),e):n}const Zm={}.hasOwnProperty;function Mg(e){const n={};let s=-1;for(;++s<e.length;)DC(n,e[s]);return n}function DC(e,n){let s;for(s in n){const r=(Zm.call(e,s)?e[s]:void 0)||(e[s]={}),o=n[s];let l;if(o)for(l in o){Zm.call(r,l)||(r[l]=[]);const c=o[l];LC(r[l],Array.isArray(c)?c:c?[c]:[])}}}function LC(e,n){let s=-1;const a=[];for(;++s<n.length;)(n[s].add==="after"?e:a).push(n[s]);Js(e,0,0,a)}function Ag(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 hi(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Ls=Yi(/[A-Za-z]/),Ps=Yi(/[\dA-Za-z]/),OC=Yi(/[#-'*+\--9=?A-Z^-~]/);function xl(e){return e!==null&&(e<32||e===127)}const Rd=Yi(/\d/),FC=Yi(/[\dA-Fa-f]/),zC=Yi(/[!-/:-@[-`{-~]/);function Ht(e){return e!==null&&e<-2}function Bn(e){return e!==null&&(e<0||e===32)}function gn(e){return e===-2||e===-1||e===32}const Bl=Yi(/\p{P}|\p{S}/u),ha=Yi(/\s/);function Yi(e){return n;function n(s){return s!==null&&s>-1&&e.test(String.fromCharCode(s))}}function or(e){const n=[];let s=-1,a=0,r=0;for(;++s<e.length;){const o=e.charCodeAt(s);let l="";if(o===37&&Ps(e.charCodeAt(s+1))&&Ps(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 gn(d)?(e.enter(s),c(d)):n(d)}function c(d){return gn(d)&&o++<r?(e.consume(d),c):(e.exit(s),n(d))}}const UC={tokenize:BC};function BC(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 Ht(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),l)}}const HC={tokenize:qC},eh={tokenize:VC};function qC(e){const n=this,s=[];let a=0,r,o,l;return c;function c(S){if(a<s.length){const j=s[a];return n.containerState=j[1],e.attempt(j[0].continuation,d,u)(S)}return u(S)}function d(S){if(a++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&k();const j=n.events.length;let E=j,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 N=j;for(;N<n.events.length;)n.events[N][1].end={...y},N++;return Js(n.events,E+1,0,n.events.slice(j)),n.events.length=N,u(S)}return c(S)}function u(S){if(a===s.length){if(!r)return f(S);if(r.currentConstruct&&r.currentConstruct.concrete)return g(S);n.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return n.containerState={},e.check(eh,m,h)(S)}function m(S){return r&&k(),b(a),f(S)}function h(S){return n.parser.lazy[n.now().line]=a!==s.length,l=n.now().offset,g(S)}function f(S){return n.containerState={},e.attempt(eh,p,g)(S)}function p(S){return a++,s.push([n.currentConstruct,n.containerState]),f(S)}function g(S){if(S===null){r&&k(),b(0),e.consume(S);return}return r=r||n.parser.flow(n.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:o}),x(S)}function x(S){if(S===null){v(e.exit("chunkFlow"),!0),b(0),e.consume(S);return}return Ht(S)?(e.consume(S),v(e.exit("chunkFlow")),a=0,n.interrupt=void 0,c):(e.consume(S),x)}function v(S,j){const E=n.sliceStream(S);if(j&&E.push(null),S.previous=o,o&&(o.next=S),o=S,r.defineSkip(S.start),r.write(E),n.parser.lazy[S.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 N=n.events.length;let M=N,D,C;for(;M--;)if(n.events[M][0]==="exit"&&n.events[M][1].type==="chunkFlow"){if(D){C=n.events[M][1].end;break}D=!0}for(b(a),y=N;y<n.events.length;)n.events[y][1].end={...C},y++;Js(n.events,M+1,0,n.events.slice(N)),n.events.length=y}}function b(S){let j=s.length;for(;j-- >S;){const E=s[j];n.containerState=E[1],E[0].exit.call(n,e)}s.length=S}function k(){r.write([null]),o=void 0,r=void 0,n.containerState._closeFlow=void 0}}function VC(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 Ya(e){if(e===null||Bn(e)||ha(e))return 1;if(Bl(e))return 2}function Hl(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 Td={name:"attention",resolveAll:WC,tokenize:KC};function WC(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};th(h,-d),th(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=ai(u,[["enter",e[a][1],n],["exit",e[a][1],n]])),u=ai(u,[["enter",r,n],["enter",l,n],["exit",l,n],["enter",o,n]]),u=ai(u,Hl(n.parser.constructs.insideSpan.null,e.slice(a+1,s),n)),u=ai(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=ai(u,[["enter",e[s][1],n],["exit",e[s][1],n]])):m=0,Js(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 KC(e,n){const s=this.parser.constructs.attentionMarkers.null,a=this.previous,r=Ya(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=Ya(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 th(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const GC={name:"autolink",tokenize:JC};function JC(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 Ls(p)?(e.consume(p),l):p===64?s(p):u(p)}function l(p){return p===43||p===45||p===46||Ps(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||Ps(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||xl(p)?s(p):(e.consume(p),d)}function u(p){return p===64?(e.consume(p),m):OC(p)?(e.consume(p),u):s(p)}function m(p){return Ps(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||Ps(p))&&a++<63){const g=p===45?f:h;return e.consume(p),g}return s(p)}}const po={partial:!0,tokenize:YC};function YC(e,n,s){return a;function a(o){return gn(o)?jn(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||Ht(o)?n(o):s(o)}}const Pg={continuation:{tokenize:XC},exit:ZC,name:"blockQuote",tokenize:QC};function QC(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 gn(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(l))}}function XC(e,n,s){const a=this;return r;function r(l){return gn(l)?jn(e,o,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(Pg,n,s)(l)}}function ZC(e){e.exit("blockQuote")}const Rg={name:"characterEscape",tokenize:e2};function e2(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 zC(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):s(o)}}const Tg={name:"characterReference",tokenize:t2};function t2(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=Ps,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=FC,m):(e.enter("characterReferenceValue"),o=7,l=Rd,m(h))}function m(h){if(h===59&&r){const f=e.exit("characterReferenceValue");return l===Ps&&!pu(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 nh={partial:!0,tokenize:s2},sh={concrete:!0,name:"codeFenced",tokenize:n2};function n2(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 N=a.events[a.events.length-1];return o=N&&N[1].type==="linePrefix"?N[2].sliceSerialize(N[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"),gn(y)?jn(e,h,"whitespace")(y):h(y))}function h(y){return y===null||Ht(y)?(e.exit("codeFencedFence"),a.interrupt?n(y):e.check(nh,x,j)(y)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(y))}function f(y){return y===null||Ht(y)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(y)):gn(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||Ht(y)?h(y):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(y))}function g(y){return y===null||Ht(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,j,v)(y)}function v(y){return e.enter("lineEnding"),e.consume(y),e.exit("lineEnding"),b}function b(y){return o>0&&gn(y)?jn(e,k,"linePrefix",o+1)(y):k(y)}function k(y){return y===null||Ht(y)?e.check(nh,x,j)(y):(e.enter("codeFlowValue"),S(y))}function S(y){return y===null||Ht(y)?(e.exit("codeFlowValue"),k(y)):(e.consume(y),S)}function j(y){return e.exit("codeFenced"),n(y)}function E(y,N,M){let D=0;return C;function C($){return y.enter("lineEnding"),y.consume($),y.exit("lineEnding"),_}function _($){return y.enter("codeFencedFence"),gn($)?jn(y,F,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)($):F($)}function F($){return $===c?(y.enter("codeFencedFenceSequence"),U($)):M($)}function U($){return $===c?(D++,y.consume($),U):D>=l?(y.exit("codeFencedFenceSequence"),gn($)?jn(y,A,"whitespace")($):A($)):M($)}function A($){return $===null||Ht($)?(y.exit("codeFencedFence"),N($)):M($)}}}function s2(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:a2},i2={partial:!0,tokenize:r2};function a2(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):Ht(u)?e.attempt(i2,l,d)(u):(e.enter("codeFlowValue"),c(u))}function c(u){return u===null||Ht(u)?(e.exit("codeFlowValue"),l(u)):(e.consume(u),c)}function d(u){return e.exit("codeIndented"),n(u)}}function r2(e,n,s){const a=this;return r;function r(l){return a.parser.lazy[a.now().line]?s(l):Ht(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):Ht(l)?r(l):s(l)}}const o2={name:"codeText",previous:c2,resolve:l2,tokenize:d2};function l2(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 c2(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function d2(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)):Ht(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||Ht(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 u2{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&&vr(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),vr(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),vr(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);vr(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);vr(this.left,s.reverse())}}}function vr(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 Ig(e){const n={};let s=-1,a,r,o,l,c,d,u;const m=new u2(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,m2(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 Js(e,0,Number.POSITIVE_INFINITY,m.slice(0)),!u}function m2(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 v=[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,v.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):v.pop(),f=v.length;f--;){const b=c.slice(v[f],v[f+1]),k=o.pop();d.push([k,k+b.length-1]),e.splice(k,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 h2={resolve:f2,tokenize:g2},p2={partial:!0,tokenize:b2};function f2(e){return Ig(e),e}function g2(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):Ht(c)?e.check(p2,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 b2(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||Ht(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 $g(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||xl(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||Ht(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||xl(b)?s(b):(e.consume(b),b===92?v:x)}function v(b){return b===40||b===41||b===92?(e.consume(b),x):x(b)}}function Dg(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):Ht(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||Ht(p)||c++>999?(e.exit("chunkString"),m(p)):(e.consume(p),d||(d=!gn(p)),p===92?f:h)}function f(p){return p===91||p===92||p===93?(e.consume(p),c++,h):h(p)}}function Lg(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):Ht(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||Ht(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 Br(e,n){let s;return a;function a(r){return Ht(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s=!0,a):gn(r)?jn(e,a,s?"linePrefix":"lineSuffix")(r):n(r)}}const x2={name:"definition",tokenize:y2},v2={partial:!0,tokenize:w2};function y2(e,n,s){const a=this;let r;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return Dg.call(a,e,c,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function c(p){return r=hi(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)?Br(e,u)(p):u(p)}function u(p){return $g(e,m,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function m(p){return e.attempt(v2,h,h)(p)}function h(p){return gn(p)?jn(e,f,"whitespace")(p):f(p)}function f(p){return p===null||Ht(p)?(e.exit("definition"),a.parser.defined.push(r),n(p)):s(p)}}function w2(e,n,s){return a;function a(c){return Bn(c)?Br(e,r)(c):s(c)}function r(c){return Lg(e,o,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return gn(c)?jn(e,l,"whitespace")(c):l(c)}function l(c){return c===null||Ht(c)?n(c):s(c)}}const k2={name:"hardBreakEscape",tokenize:j2};function j2(e,n,s){return a;function a(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return Ht(o)?(e.exit("hardBreakEscape"),n(o)):s(o)}}const N2={name:"headingAtx",resolve:S2,tokenize:C2};function S2(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"},Js(e,a,s-a+1,[["enter",r,n],["enter",o,n],["exit",o,n],["exit",r,n]])),e}function C2(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||Ht(m)?(e.exit("atxHeading"),n(m)):gn(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 E2=["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"],ih=["pre","script","style","textarea"],_2={concrete:!0,name:"htmlFlow",resolveTo:P2,tokenize:R2},M2={partial:!0,tokenize:I2},A2={partial:!0,tokenize:T2};function P2(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 R2(e,n,s){const a=this;let r,o,l,c,d;return u;function u(w){return m(w)}function m(w){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(w),h}function h(w){return w===33?(e.consume(w),f):w===47?(e.consume(w),o=!0,x):w===63?(e.consume(w),r=3,a.interrupt?n:P):Ls(w)?(e.consume(w),l=String.fromCharCode(w),v):s(w)}function f(w){return w===45?(e.consume(w),r=2,p):w===91?(e.consume(w),r=5,c=0,g):Ls(w)?(e.consume(w),r=4,a.interrupt?n:P):s(w)}function p(w){return w===45?(e.consume(w),a.interrupt?n:P):s(w)}function g(w){const Y="CDATA[";return w===Y.charCodeAt(c++)?(e.consume(w),c===Y.length?a.interrupt?n:F:g):s(w)}function x(w){return Ls(w)?(e.consume(w),l=String.fromCharCode(w),v):s(w)}function v(w){if(w===null||w===47||w===62||Bn(w)){const Y=w===47,re=l.toLowerCase();return!Y&&!o&&ih.includes(re)?(r=1,a.interrupt?n(w):F(w)):E2.includes(l.toLowerCase())?(r=6,Y?(e.consume(w),b):a.interrupt?n(w):F(w)):(r=7,a.interrupt&&!a.parser.lazy[a.now().line]?s(w):o?k(w):S(w))}return w===45||Ps(w)?(e.consume(w),l+=String.fromCharCode(w),v):s(w)}function b(w){return w===62?(e.consume(w),a.interrupt?n:F):s(w)}function k(w){return gn(w)?(e.consume(w),k):C(w)}function S(w){return w===47?(e.consume(w),C):w===58||w===95||Ls(w)?(e.consume(w),j):gn(w)?(e.consume(w),S):C(w)}function j(w){return w===45||w===46||w===58||w===95||Ps(w)?(e.consume(w),j):E(w)}function E(w){return w===61?(e.consume(w),y):gn(w)?(e.consume(w),E):S(w)}function y(w){return w===null||w===60||w===61||w===62||w===96?s(w):w===34||w===39?(e.consume(w),d=w,N):gn(w)?(e.consume(w),y):M(w)}function N(w){return w===d?(e.consume(w),d=null,D):w===null||Ht(w)?s(w):(e.consume(w),N)}function M(w){return w===null||w===34||w===39||w===47||w===60||w===61||w===62||w===96||Bn(w)?E(w):(e.consume(w),M)}function D(w){return w===47||w===62||gn(w)?S(w):s(w)}function C(w){return w===62?(e.consume(w),_):s(w)}function _(w){return w===null||Ht(w)?F(w):gn(w)?(e.consume(w),_):s(w)}function F(w){return w===45&&r===2?(e.consume(w),T):w===60&&r===1?(e.consume(w),J):w===62&&r===4?(e.consume(w),O):w===63&&r===3?(e.consume(w),P):w===93&&r===5?(e.consume(w),se):Ht(w)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(M2,I,U)(w)):w===null||Ht(w)?(e.exit("htmlFlowData"),U(w)):(e.consume(w),F)}function U(w){return e.check(A2,A,I)(w)}function A(w){return e.enter("lineEnding"),e.consume(w),e.exit("lineEnding"),$}function $(w){return w===null||Ht(w)?U(w):(e.enter("htmlFlowData"),F(w))}function T(w){return w===45?(e.consume(w),P):F(w)}function J(w){return w===47?(e.consume(w),l="",B):F(w)}function B(w){if(w===62){const Y=l.toLowerCase();return ih.includes(Y)?(e.consume(w),O):F(w)}return Ls(w)&&l.length<8?(e.consume(w),l+=String.fromCharCode(w),B):F(w)}function se(w){return w===93?(e.consume(w),P):F(w)}function P(w){return w===62?(e.consume(w),O):w===45&&r===2?(e.consume(w),P):F(w)}function O(w){return w===null||Ht(w)?(e.exit("htmlFlowData"),I(w)):(e.consume(w),O)}function I(w){return e.exit("htmlFlow"),n(w)}}function T2(e,n,s){const a=this;return r;function r(l){return Ht(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 I2(e,n,s){return a;function a(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(po,n,s)}}const $2={name:"htmlText",tokenize:D2};function D2(e,n,s){const a=this;let r,o,l;return c;function c(P){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(P),d}function d(P){return P===33?(e.consume(P),u):P===47?(e.consume(P),E):P===63?(e.consume(P),S):Ls(P)?(e.consume(P),M):s(P)}function u(P){return P===45?(e.consume(P),m):P===91?(e.consume(P),o=0,g):Ls(P)?(e.consume(P),k):s(P)}function m(P){return P===45?(e.consume(P),p):s(P)}function h(P){return P===null?s(P):P===45?(e.consume(P),f):Ht(P)?(l=h,J(P)):(e.consume(P),h)}function f(P){return P===45?(e.consume(P),p):h(P)}function p(P){return P===62?T(P):P===45?f(P):h(P)}function g(P){const O="CDATA[";return P===O.charCodeAt(o++)?(e.consume(P),o===O.length?x:g):s(P)}function x(P){return P===null?s(P):P===93?(e.consume(P),v):Ht(P)?(l=x,J(P)):(e.consume(P),x)}function v(P){return P===93?(e.consume(P),b):x(P)}function b(P){return P===62?T(P):P===93?(e.consume(P),b):x(P)}function k(P){return P===null||P===62?T(P):Ht(P)?(l=k,J(P)):(e.consume(P),k)}function S(P){return P===null?s(P):P===63?(e.consume(P),j):Ht(P)?(l=S,J(P)):(e.consume(P),S)}function j(P){return P===62?T(P):S(P)}function E(P){return Ls(P)?(e.consume(P),y):s(P)}function y(P){return P===45||Ps(P)?(e.consume(P),y):N(P)}function N(P){return Ht(P)?(l=N,J(P)):gn(P)?(e.consume(P),N):T(P)}function M(P){return P===45||Ps(P)?(e.consume(P),M):P===47||P===62||Bn(P)?D(P):s(P)}function D(P){return P===47?(e.consume(P),T):P===58||P===95||Ls(P)?(e.consume(P),C):Ht(P)?(l=D,J(P)):gn(P)?(e.consume(P),D):T(P)}function C(P){return P===45||P===46||P===58||P===95||Ps(P)?(e.consume(P),C):_(P)}function _(P){return P===61?(e.consume(P),F):Ht(P)?(l=_,J(P)):gn(P)?(e.consume(P),_):D(P)}function F(P){return P===null||P===60||P===61||P===62||P===96?s(P):P===34||P===39?(e.consume(P),r=P,U):Ht(P)?(l=F,J(P)):gn(P)?(e.consume(P),F):(e.consume(P),A)}function U(P){return P===r?(e.consume(P),r=void 0,$):P===null?s(P):Ht(P)?(l=U,J(P)):(e.consume(P),U)}function A(P){return P===null||P===34||P===39||P===60||P===61||P===96?s(P):P===47||P===62||Bn(P)?D(P):(e.consume(P),A)}function $(P){return P===47||P===62||Bn(P)?D(P):s(P)}function T(P){return P===62?(e.consume(P),e.exit("htmlTextData"),e.exit("htmlText"),n):s(P)}function J(P){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(P),e.exit("lineEnding"),B}function B(P){return gn(P)?jn(e,se,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(P):se(P)}function se(P){return e.enter("htmlTextData"),l(P)}}const fu={name:"labelEnd",resolveAll:z2,resolveTo:U2,tokenize:B2},L2={tokenize:H2},O2={tokenize:q2},F2={tokenize:V2};function z2(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&&Js(e,0,e.length,s),e}function U2(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=ai(c,e.slice(o+1,o+a+3)),c=ai(c,[["enter",m,n]]),c=ai(c,Hl(n.parser.constructs.insideSpan.null,e.slice(o+a+4,l-3),n)),c=ai(c,[["exit",m,n],e[l-2],e[l-1],["exit",u,n]]),c=ai(c,e.slice(l+1)),c=ai(c,[["exit",d,n]]),Js(e,o,e.length,c),e}function B2(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(hi(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(L2,m,l?m:h)(f):f===91?e.attempt(O2,m,l?u:h)(f):l?m(f):h(f)}function u(f){return e.attempt(F2,m,h)(f)}function m(f){return n(f)}function h(f){return o._balanced=!0,s(f)}}function H2(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)?Br(e,o)(h):o(h)}function o(h){return h===41?m(h):$g(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function l(h){return Bn(h)?Br(e,d)(h):m(h)}function c(h){return s(h)}function d(h){return h===34||h===39||h===40?Lg(e,u,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):m(h)}function u(h){return Bn(h)?Br(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 q2(e,n,s){const a=this;return r;function r(c){return Dg.call(a,e,o,l,"reference","referenceMarker","referenceString")(c)}function o(c){return a.parser.defined.includes(hi(a.sliceSerialize(a.events[a.events.length-1][1]).slice(1,-1)))?n(c):s(c)}function l(c){return s(c)}}function V2(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 W2={name:"labelStartImage",resolveAll:fu.resolveAll,tokenize:K2};function K2(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 G2={name:"labelStartLink",resolveAll:fu.resolveAll,tokenize:J2};function J2(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 yc={name:"lineEnding",tokenize:Y2};function Y2(e,n){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),jn(e,n,"linePrefix")}}const sl={name:"thematicBreak",tokenize:Q2};function Q2(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||Ht(u))?(e.exit("thematicBreak"),n(u)):s(u)}function d(u){return u===r?(e.consume(u),a++,d):(e.exit("thematicBreakSequence"),gn(u)?jn(e,c,"whitespace")(u):c(u))}}const zs={continuation:{tokenize:tE},exit:sE,name:"list",tokenize:eE},X2={partial:!0,tokenize:iE},Z2={partial:!0,tokenize:nE};function eE(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:Rd(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(sl,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 Rd(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(po,a.interrupt?s:m,e.attempt(X2,f,h))}function m(p){return a.containerState.initialBlankLine=!0,o++,f(p)}function h(p){return gn(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 tE(e,n,s){const a=this;return a.containerState._closeFlow=void 0,e.check(po,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||!gn(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(Z2,n,l)(c))}function l(c){return a.containerState._closeFlow=!0,a.interrupt=void 0,jn(e,e.attempt(zs,n,s),"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function nE(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 sE(e){e.exit(this.containerState.type)}function iE(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!gn(o)&&l&&l[1].type==="listItemPrefixWhitespace"?n(o):s(o)}}const ah={name:"setextUnderline",resolveTo:aE,tokenize:rE};function aE(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 rE(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"),gn(u)?jn(e,d,"lineSuffix")(u):d(u))}function d(u){return u===null||Ht(u)?(e.exit("setextHeadingLine"),n(u)):s(u)}}const oE={tokenize:lE};function lE(e){const n=this,s=e.attempt(po,a,e.attempt(this.parser.constructs.flowInitial,r,jn(e,e.attempt(this.parser.constructs.flow,r,e.attempt(h2,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 cE={resolveAll:Fg()},dE=Og("string"),uE=Og("text");function Og(e){return{resolveAll:Fg(e==="text"?mE: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 Fg(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 mE(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 hE={42:zs,43:zs,45:zs,48:zs,49:zs,50:zs,51:zs,52:zs,53:zs,54:zs,55:zs,56:zs,57:zs,62:Pg},pE={91:x2},fE={[-2]:vc,[-1]:vc,32:vc},gE={35:N2,42:sl,45:[ah,sl],60:_2,61:ah,95:sl,96:sh,126:sh},bE={38:Tg,92:Rg},xE={[-5]:yc,[-4]:yc,[-3]:yc,33:W2,38:Tg,42:Td,60:[GC,$2],91:G2,92:[k2,Rg],93:fu,95:Td,96:o2},vE={null:[Td,cE]},yE={null:[42,95]},wE={null:[]},kE=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:yE,contentInitial:pE,disable:wE,document:hE,flow:gE,flowInitial:fE,insideSpan:vE,string:bE,text:xE},Symbol.toStringTag,{value:"Module"}));function jE(e,n,s){let a={_bufferIndex:-1,_index:0,line:s&&s.line||1,column:s&&s.column||1,offset:s&&s.offset||0};const r={},o=[];let l=[],c=[];const d={attempt:N(E),check:N(y),consume:k,enter:S,exit:j,interrupt:N(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(_){return l=ai(l,_),v(),l[l.length-1]!==null?[]:(M(n,0),u.events=Hl(o,u.events,u),u.events)}function f(_,F){return SE(p(_),F)}function p(_){return NE(l,_)}function g(){const{_bufferIndex:_,_index:F,line:U,column:A,offset:$}=a;return{_bufferIndex:_,_index:F,line:U,column:A,offset:$}}function x(_){r[_.line]=_.column,C()}function v(){let _;for(;a._index<l.length;){const F=l[a._index];if(typeof F=="string")for(_=a._index,a._bufferIndex<0&&(a._bufferIndex=0);a._index===_&&a._bufferIndex<F.length;)b(F.charCodeAt(a._bufferIndex));else b(F)}}function b(_){m=m(_)}function k(_){Ht(_)?(a.line++,a.column=1,a.offset+=_===-3?2:1,C()):_!==-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=_}function S(_,F){const U=F||{};return U.type=_,U.start=g(),u.events.push(["enter",U,u]),c.push(U),U}function j(_){const F=c.pop();return F.end=g(),u.events.push(["exit",F,u]),F}function E(_,F){M(_,F.from)}function y(_,F){F.restore()}function N(_,F){return U;function U(A,$,T){let J,B,se,P;return Array.isArray(A)?I(A):"tokenize"in A?I([A]):O(A);function O(le){return ve;function ve(de){const Fe=de!==null&&le[de],X=de!==null&&le.null,L=[...Array.isArray(Fe)?Fe:Fe?[Fe]:[],...Array.isArray(X)?X:X?[X]:[]];return I(L)(de)}}function I(le){return J=le,B=0,le.length===0?T:w(le[B])}function w(le){return ve;function ve(de){return P=D(),se=le,le.partial||(u.currentConstruct=le),le.name&&u.parser.constructs.disable.null.includes(le.name)?re():le.tokenize.call(F?Object.assign(Object.create(u),F):u,d,Y,re)(de)}}function Y(le){return _(se,P),$}function re(le){return P.restore(),++B<J.length?w(J[B]):T}}}function M(_,F){_.resolveAll&&!o.includes(_)&&o.push(_),_.resolve&&Js(u.events,F,u.events.length-F,_.resolve(u.events.slice(F),u)),_.resolveTo&&(u.events=_.resolveTo(u.events,u))}function D(){const _=g(),F=u.previous,U=u.currentConstruct,A=u.events.length,$=Array.from(c);return{from:A,restore:T};function T(){a=_,u.previous=F,u.currentConstruct=U,u.events.length=A,c=$,C()}}function C(){a.line in r&&a.column<2&&(a.column=r[a.line],a.offset+=r[a.line]-1)}}function NE(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 SE(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=`
655
- `;break}case-3:{l=`\r
656
- `;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 CE(e){const a={constructs:Mg([kE,...(e||{}).extensions||[]]),content:r(UC),defined:[],document:r(HC),flow:r(oE),lazy:{},string:r(dE),text:r(uE)};return a;function r(o){return l;function l(c){return jE(a,o,c)}}}function EE(e){for(;!Ig(e););return e}const rh=/[\0\t\n\r]/g;function _E(){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(rh.lastIndex=h,u=rh.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 ME=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function AE(e){return e.replace(ME,PE)}function PE(e,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),o=r===120||r===88;return Ag(s.slice(o?2:1),o?16:10)}return pu(s)||e}const zg={}.hasOwnProperty;function RE(e,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),TE(s)(EE(CE(s).document().write(_E()(e,n,!0))))}function TE(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(fe),autolinkProtocol:D,autolinkEmail:D,atxHeading:o(z),blockQuote:o(X),characterEscape:D,characterReference:D,codeFenced:o(L),codeFencedFenceInfo:l,codeFencedFenceMeta:l,codeIndented:o(L,l),codeText:o(Q,l),codeTextData:D,data:D,codeFlowValue:D,definition:o(ne),definitionDestinationString:l,definitionLabelString:l,definitionTitleString:l,emphasis:o(H),hardBreakEscape:o(W),hardBreakTrailing:o(W),htmlFlow:o(we,l),htmlFlowData:D,htmlText:o(we,l),htmlTextData:D,image:o(Z),label:l,link:o(fe),listItem:o(Ve),listItemValue:f,listOrdered:o(Oe,h),listUnordered:o(Oe),paragraph:o(He),reference:w,referenceString:l,resourceDestinationString:l,resourceTitleString:l,setextHeading:o(z),strong:o(Je),thematicBreak:o(he)},exit:{atxHeading:d(),atxHeadingSequence:E,autolink:d(),autolinkEmail:Fe,autolinkProtocol:de,blockQuote:d(),characterEscapeValue:C,characterReferenceMarkerHexadecimal:re,characterReferenceMarkerNumeric:re,characterReferenceValue:le,characterReference:ve,codeFenced:d(v),codeFencedFence:x,codeFencedFenceInfo:p,codeFencedFenceMeta:g,codeFlowValue:C,codeIndented:d(b),codeText:d($),codeTextData:C,data:C,definition:d(),definitionDestinationString:j,definitionLabelString:k,definitionTitleString:S,emphasis:d(),hardBreakEscape:d(F),hardBreakTrailing:d(F),htmlFlow:d(U),htmlFlowData:C,htmlText:d(A),htmlTextData:C,image:d(J),label:se,labelText:B,lineEnding:_,link:d(T),listItem:d(),listOrdered:d(),listUnordered:d(),paragraph:d(),referenceString:Y,resourceDestinationString:P,resourceTitleString:O,resource:I,setextHeading:d(M),setextHeadingLineSequence:N,setextHeadingText:y,strong:d(),thematicBreak:d()}};Ug(n,(e||{}).mdastExtensions||[]);const s={};return a;function a(ue){let Ee={type:"root",children:[]};const je={stack:[Ee],tokenStack:[],config:n,enter:c,exit:u,buffer:l,resume:m,data:s},xe=[];let Pe=-1;for(;++Pe<ue.length;)if(ue[Pe][1].type==="listOrdered"||ue[Pe][1].type==="listUnordered")if(ue[Pe][0]==="enter")xe.push(Pe);else{const ie=xe.pop();Pe=r(ue,ie,Pe)}for(Pe=-1;++Pe<ue.length;){const ie=n[ue[Pe][0]];zg.call(ie,ue[Pe][1].type)&&ie[ue[Pe][1].type].call(Object.assign({sliceSerialize:ue[Pe][2].sliceSerialize},je),ue[Pe][1])}if(je.tokenStack.length>0){const ie=je.tokenStack[je.tokenStack.length-1];(ie[1]||oh).call(je,void 0,ie[0])}for(Ee.position={start:Ui(ue.length>0?ue[0][1].start:{line:1,column:1,offset:0}),end:Ui(ue.length>0?ue[ue.length-2][1].end:{line:1,column:1,offset:0})},Pe=-1;++Pe<n.transforms.length;)Ee=n.transforms[Pe](Ee)||Ee;return Ee}function r(ue,Ee,je){let xe=Ee-1,Pe=-1,ie=!1,Me,We,mt,st;for(;++xe<=je;){const Ze=ue[xe];switch(Ze[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{Ze[0]==="enter"?Pe++:Pe--,st=void 0;break}case"lineEndingBlank":{Ze[0]==="enter"&&(Me&&!st&&!Pe&&!mt&&(mt=xe),st=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:st=void 0}if(!Pe&&Ze[0]==="enter"&&Ze[1].type==="listItemPrefix"||Pe===-1&&Ze[0]==="exit"&&(Ze[1].type==="listUnordered"||Ze[1].type==="listOrdered")){if(Me){let dt=xe;for(We=void 0;dt--;){const Ae=ue[dt];if(Ae[1].type==="lineEnding"||Ae[1].type==="lineEndingBlank"){if(Ae[0]==="exit")continue;We&&(ue[We][1].type="lineEndingBlank",ie=!0),Ae[1].type="lineEnding",We=dt}else if(!(Ae[1].type==="linePrefix"||Ae[1].type==="blockQuotePrefix"||Ae[1].type==="blockQuotePrefixWhitespace"||Ae[1].type==="blockQuoteMarker"||Ae[1].type==="listItemIndent"))break}mt&&(!We||mt<We)&&(Me._spread=!0),Me.end=Object.assign({},We?ue[We][1].start:Ze[1].end),ue.splice(We||xe,0,["exit",Me,Ze[2]]),xe++,je++}if(Ze[1].type==="listItemPrefix"){const dt={type:"listItem",_spread:!1,start:Object.assign({},Ze[1].start),end:void 0};Me=dt,ue.splice(xe,0,["enter",dt,Ze[2]]),xe++,je++,mt=void 0,st=!0}}}return ue[Ee][1]._spread=ie,je}function o(ue,Ee){return je;function je(xe){c.call(this,ue(xe),xe),Ee&&Ee.call(this,xe)}}function l(){this.stack.push({type:"fragment",children:[]})}function c(ue,Ee,je){this.stack[this.stack.length-1].children.push(ue),this.stack.push(ue),this.tokenStack.push([Ee,je||void 0]),ue.position={start:Ui(Ee.start),end:void 0}}function d(ue){return Ee;function Ee(je){ue&&ue.call(this,je),u.call(this,je)}}function u(ue,Ee){const je=this.stack.pop(),xe=this.tokenStack.pop();if(xe)xe[0].type!==ue.type&&(Ee?Ee.call(this,ue,xe[0]):(xe[1]||oh).call(this,ue,xe[0]));else throw new Error("Cannot close `"+ue.type+"` ("+Ur({start:ue.start,end:ue.end})+"): it’s not open");je.position.end=Ui(ue.end)}function m(){return hu(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function f(ue){if(this.data.expectingFirstListItemValue){const Ee=this.stack[this.stack.length-2];Ee.start=Number.parseInt(this.sliceSerialize(ue),10),this.data.expectingFirstListItemValue=void 0}}function p(){const ue=this.resume(),Ee=this.stack[this.stack.length-1];Ee.lang=ue}function g(){const ue=this.resume(),Ee=this.stack[this.stack.length-1];Ee.meta=ue}function x(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function v(){const ue=this.resume(),Ee=this.stack[this.stack.length-1];Ee.value=ue.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function b(){const ue=this.resume(),Ee=this.stack[this.stack.length-1];Ee.value=ue.replace(/(\r?\n|\r)$/g,"")}function k(ue){const Ee=this.resume(),je=this.stack[this.stack.length-1];je.label=Ee,je.identifier=hi(this.sliceSerialize(ue)).toLowerCase()}function S(){const ue=this.resume(),Ee=this.stack[this.stack.length-1];Ee.title=ue}function j(){const ue=this.resume(),Ee=this.stack[this.stack.length-1];Ee.url=ue}function E(ue){const Ee=this.stack[this.stack.length-1];if(!Ee.depth){const je=this.sliceSerialize(ue).length;Ee.depth=je}}function y(){this.data.setextHeadingSlurpLineEnding=!0}function N(ue){const Ee=this.stack[this.stack.length-1];Ee.depth=this.sliceSerialize(ue).codePointAt(0)===61?1:2}function M(){this.data.setextHeadingSlurpLineEnding=void 0}function D(ue){const je=this.stack[this.stack.length-1].children;let xe=je[je.length-1];(!xe||xe.type!=="text")&&(xe=$e(),xe.position={start:Ui(ue.start),end:void 0},je.push(xe)),this.stack.push(xe)}function C(ue){const Ee=this.stack.pop();Ee.value+=this.sliceSerialize(ue),Ee.position.end=Ui(ue.end)}function _(ue){const Ee=this.stack[this.stack.length-1];if(this.data.atHardBreak){const je=Ee.children[Ee.children.length-1];je.position.end=Ui(ue.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(Ee.type)&&(D.call(this,ue),C.call(this,ue))}function F(){this.data.atHardBreak=!0}function U(){const ue=this.resume(),Ee=this.stack[this.stack.length-1];Ee.value=ue}function A(){const ue=this.resume(),Ee=this.stack[this.stack.length-1];Ee.value=ue}function $(){const ue=this.resume(),Ee=this.stack[this.stack.length-1];Ee.value=ue}function T(){const ue=this.stack[this.stack.length-1];if(this.data.inReference){const Ee=this.data.referenceType||"shortcut";ue.type+="Reference",ue.referenceType=Ee,delete ue.url,delete ue.title}else delete ue.identifier,delete ue.label;this.data.referenceType=void 0}function J(){const ue=this.stack[this.stack.length-1];if(this.data.inReference){const Ee=this.data.referenceType||"shortcut";ue.type+="Reference",ue.referenceType=Ee,delete ue.url,delete ue.title}else delete ue.identifier,delete ue.label;this.data.referenceType=void 0}function B(ue){const Ee=this.sliceSerialize(ue),je=this.stack[this.stack.length-2];je.label=AE(Ee),je.identifier=hi(Ee).toLowerCase()}function se(){const ue=this.stack[this.stack.length-1],Ee=this.resume(),je=this.stack[this.stack.length-1];if(this.data.inReference=!0,je.type==="link"){const xe=ue.children;je.children=xe}else je.alt=Ee}function P(){const ue=this.resume(),Ee=this.stack[this.stack.length-1];Ee.url=ue}function O(){const ue=this.resume(),Ee=this.stack[this.stack.length-1];Ee.title=ue}function I(){this.data.inReference=void 0}function w(){this.data.referenceType="collapsed"}function Y(ue){const Ee=this.resume(),je=this.stack[this.stack.length-1];je.label=Ee,je.identifier=hi(this.sliceSerialize(ue)).toLowerCase(),this.data.referenceType="full"}function re(ue){this.data.characterReferenceType=ue.type}function le(ue){const Ee=this.sliceSerialize(ue),je=this.data.characterReferenceType;let xe;je?(xe=Ag(Ee,je==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):xe=pu(Ee);const Pe=this.stack[this.stack.length-1];Pe.value+=xe}function ve(ue){const Ee=this.stack.pop();Ee.position.end=Ui(ue.end)}function de(ue){C.call(this,ue);const Ee=this.stack[this.stack.length-1];Ee.url=this.sliceSerialize(ue)}function Fe(ue){C.call(this,ue);const Ee=this.stack[this.stack.length-1];Ee.url="mailto:"+this.sliceSerialize(ue)}function X(){return{type:"blockquote",children:[]}}function L(){return{type:"code",lang:null,meta:null,value:""}}function Q(){return{type:"inlineCode",value:""}}function ne(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function H(){return{type:"emphasis",children:[]}}function z(){return{type:"heading",depth:0,children:[]}}function W(){return{type:"break"}}function we(){return{type:"html",value:""}}function Z(){return{type:"image",title:null,url:"",alt:null}}function fe(){return{type:"link",title:null,url:"",children:[]}}function Oe(ue){return{type:"list",ordered:ue.type==="listOrdered",start:null,spread:ue._spread,children:[]}}function Ve(ue){return{type:"listItem",spread:ue._spread,checked:null,children:[]}}function He(){return{type:"paragraph",children:[]}}function Je(){return{type:"strong",children:[]}}function $e(){return{type:"text",value:""}}function he(){return{type:"thematicBreak"}}}function Ui(e){return{line:e.line,column:e.column,offset:e.offset}}function Ug(e,n){let s=-1;for(;++s<n.length;){const a=n[s];Array.isArray(a)?Ug(e,a):IE(e,a)}}function IE(e,n){let s;for(s in n)if(zg.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 oh(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+Ur({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+Ur({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+Ur({start:n.start,end:n.end})+") is still open")}function $E(e){const n=this;n.parser=s;function s(a){return RE(a,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function DE(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 LE(e,n){const s={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,s),[e.applyData(n,s),{type:"text",value:`
657
- `}]}function OE(e,n){const s=n.value?n.value+`
658
- `:"",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 FE(e,n){const s={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function zE(e,n){const s={type:"element",tagName:"em",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function UE(e,n){const s=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",a=String(n.identifier).toUpperCase(),r=or(a.toLowerCase()),o=e.footnoteOrder.indexOf(a);let l,c=e.footnoteCounts.get(a);c===void 0?(c=0,e.footnoteOrder.push(a),l=e.footnoteOrder.length):l=o+1,c+=1,e.footnoteCounts.set(a,c);const d={type:"element",tagName:"a",properties:{href:"#"+s+"fn-"+r,id:s+"fnref-"+r+(c>1?"-"+c:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(l)}]};e.patch(n,d);const u={type:"element",tagName:"sup",properties:{},children:[d]};return e.patch(n,u),e.applyData(n,u)}function BE(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 HE(e,n){if(e.options.allowDangerousHtml){const s={type:"raw",value:n.value};return e.patch(n,s),e.applyData(n,s)}}function Bg(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 qE(e,n){const s=String(n.identifier).toUpperCase(),a=e.definitionById.get(s);if(!a)return Bg(e,n);const r={src:or(a.url||""),alt:n.alt};a.title!==null&&a.title!==void 0&&(r.title=a.title);const o={type:"element",tagName:"img",properties:r,children:[]};return e.patch(n,o),e.applyData(n,o)}function VE(e,n){const s={src:or(n.url)};n.alt!==null&&n.alt!==void 0&&(s.alt=n.alt),n.title!==null&&n.title!==void 0&&(s.title=n.title);const a={type:"element",tagName:"img",properties:s,children:[]};return e.patch(n,a),e.applyData(n,a)}function WE(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 KE(e,n){const s=String(n.identifier).toUpperCase(),a=e.definitionById.get(s);if(!a)return Bg(e,n);const r={href:or(a.url||"")};a.title!==null&&a.title!==void 0&&(r.title=a.title);const o={type:"element",tagName:"a",properties:r,children:e.all(n)};return e.patch(n,o),e.applyData(n,o)}function GE(e,n){const s={href:or(n.url)};n.title!==null&&n.title!==void 0&&(s.title=n.title);const a={type:"element",tagName:"a",properties:s,children:e.all(n)};return e.patch(n,a),e.applyData(n,a)}function JE(e,n,s){const a=e.all(n),r=s?YE(s):Hg(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:`
659
- `}),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:`
660
- `});const u={type:"element",tagName:"li",properties:o,children:l};return e.patch(n,u),e.applyData(n,u)}function YE(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=Hg(s[a])}return n}function Hg(e){const n=e.spread;return n??e.children.length>1}function QE(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 XE(e,n){const s={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function ZE(e,n){const s={type:"root",children:e.wrap(e.all(n))};return e.patch(n,s),e.applyData(n,s)}function e_(e,n){const s={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function t_(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=cu(n.children[1]),d=kg(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 n_(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 s_(e,n){const s={type:"element",tagName:"td",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}const lh=9,ch=32;function i_(e){const n=String(e),s=/\r?\n|\r/g;let a=s.exec(n),r=0;const o=[];for(;a;)o.push(dh(n.slice(r,a.index),r>0,!0),a[0]),r=a.index+a[0].length,a=s.exec(n);return o.push(dh(n.slice(r),r>0,!1)),o.join("")}function dh(e,n,s){let a=0,r=e.length;if(n){let o=e.codePointAt(a);for(;o===lh||o===ch;)a++,o=e.codePointAt(a)}if(s){let o=e.codePointAt(r-1);for(;o===lh||o===ch;)r--,o=e.codePointAt(r-1)}return r>a?e.slice(a,r):""}function a_(e,n){const s={type:"text",value:i_(String(n.value))};return e.patch(n,s),e.applyData(n,s)}function r_(e,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,s),e.applyData(n,s)}const o_={blockquote:DE,break:LE,code:OE,delete:FE,emphasis:zE,footnoteReference:UE,heading:BE,html:HE,imageReference:qE,image:VE,inlineCode:WE,linkReference:KE,link:GE,listItem:JE,list:QE,paragraph:XE,root:ZE,strong:e_,table:t_,tableCell:s_,tableRow:n_,text:a_,thematicBreak:r_,toml:_o,yaml:_o,definition:_o,footnoteDefinition:_o};function _o(){}const qg=-1,ql=0,Hr=1,vl=2,gu=3,bu=4,xu=5,vu=6,Vg=7,Wg=8,uh=typeof self=="object"?self:globalThis,l_=(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 ql:case qg:return s(l,r);case Hr:{const c=s([],r);for(const d of l)c.push(a(d));return c}case vl:{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 bu:{const{source:c,flags:d}=l;return s(new RegExp(c,d),r)}case xu:{const c=s(new Map,r);for(const[d,u]of l)c.set(a(d),a(u));return c}case vu:{const c=s(new Set,r);for(const d of l)c.add(a(d));return c}case Vg:{const{name:c,message:d}=l;return s(new uh[c](d),r)}case Wg: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 uh[o](l),r)};return a},mh=e=>l_(new Map,e)(0),Aa="",{toString:c_}={},{keys:d_}=Object,yr=e=>{const n=typeof e;if(n!=="object"||!e)return[ql,n];const s=c_.call(e).slice(8,-1);switch(s){case"Array":return[Hr,Aa];case"Object":return[vl,Aa];case"Date":return[gu,Aa];case"RegExp":return[bu,Aa];case"Map":return[xu,Aa];case"Set":return[vu,Aa];case"DataView":return[Hr,s]}return s.includes("Array")?[Hr,s]:s.includes("Error")?[Vg,s]:[vl,s]},Mo=([e,n])=>e===ql&&(n==="function"||n==="symbol"),u_=(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]=yr(l);switch(c){case ql:{let m=l;switch(d){case"bigint":c=Wg,m=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+d);m=null;break;case"undefined":return r([qg],l)}return r([c,m],l)}case Hr:{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 vl:{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 d_(l))(e||!Mo(yr(l[f])))&&m.push([o(f),o(l[f])]);return h}case gu:return r([c,l.toISOString()],l);case bu:{const{source:m,flags:h}=l;return r([c,{source:m,flags:h}],l)}case xu:{const m=[],h=r([c,m],l);for(const[f,p]of l)(e||!(Mo(yr(f))||Mo(yr(p))))&&m.push([o(f),o(p)]);return h}case vu:{const m=[],h=r([c,m],l);for(const f of l)(e||!Mo(yr(f)))&&m.push(o(f));return h}}const{message:u}=l;return r([c,{name:d,message:u}],l)};return o},hh=(e,{json:n,lossy:s}={})=>{const a=[];return u_(!(n||s),!!n,new Map,a)(e),a},yl=typeof structuredClone=="function"?(e,n)=>n&&("json"in n||"lossy"in n)?mh(hh(e,n)):structuredClone(e):(e,n)=>mh(hh(e,n));function m_(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 h_(e,n){return"Back to reference "+(e+1)+(n>1?"-"+n:"")}function p_(e){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=e.options.footnoteBackContent||m_,a=e.options.footnoteBackLabel||h_,r=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",l=e.options.footnoteLabelProperties||{className:["sr-only"]},c=[];let d=-1;for(;++d<e.footnoteOrder.length;){const u=e.footnoteById.get(e.footnoteOrder[d]);if(!u)continue;const m=e.all(u),h=String(u.identifier).toUpperCase(),f=or(h.toLowerCase());let p=0;const g=[],x=e.footnoteCounts.get(h);for(;x!==void 0&&++p<=x;){g.length>0&&g.push({type:"text",value:" "});let k=typeof s=="string"?s:s(d,p);typeof k=="string"&&(k={type:"text",value:k}),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(k)?k:[k]})}const v=m[m.length-1];if(v&&v.type==="element"&&v.tagName==="p"){const k=v.children[v.children.length-1];k&&k.type==="text"?k.value+=" ":v.children.push({type:"text",value:" "}),v.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:{...yl(l),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
661
- `},{type:"element",tagName:"ol",properties:{},children:e.wrap(c,!0)},{type:"text",value:`
662
- `}]}}const Vl=(function(e){if(e==null)return x_;if(typeof e=="function")return Wl(e);if(typeof e=="object")return Array.isArray(e)?f_(e):g_(e);if(typeof e=="string")return b_(e);throw new Error("Expected function, string, or object as test")});function f_(e){const n=[];let s=-1;for(;++s<e.length;)n[s]=Vl(e[s]);return Wl(a);function a(...r){let o=-1;for(;++o<n.length;)if(n[o].apply(this,r))return!0;return!1}}function g_(e){const n=e;return Wl(s);function s(a){const r=a;let o;for(o in e)if(r[o]!==n[o])return!1;return!0}}function b_(e){return Wl(n);function n(s){return s&&s.type===e}}function Wl(e){return n;function n(s,a,r){return!!(v_(s)&&e.call(this,s,typeof a=="number"?a:void 0,r||void 0))}}function x_(){return!0}function v_(e){return e!==null&&typeof e=="object"&&"type"in e}const Kg=[],y_=!0,Id=!1,w_="skip";function Gg(e,n,s,a){let r;typeof n=="function"&&typeof s!="function"?(a=s,s=n):r=n;const o=Vl(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=Kg,g,x,v;if((!n||o(d,u,m[m.length-1]||void 0))&&(p=k_(s(d,m)),p[0]===Id))return p;if("children"in d&&d.children){const b=d;if(b.children&&p[0]!==w_)for(x=(a?b.children.length:-1)+l,v=m.concat(b);x>-1&&x<b.children.length;){const k=b.children[x];if(g=c(k,x,v)(),g[0]===Id)return g;x=typeof g[1]=="number"?g[1]:x+l}}return p}}}function k_(e){return Array.isArray(e)?e:typeof e=="number"?[y_,e]:e==null?Kg:[e]}function yu(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),Gg(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 $d={}.hasOwnProperty,j_={};function N_(e,n){const s=n||j_,a=new Map,r=new Map,o=new Map,l={...o_,...s.handlers},c={all:u,applyData:C_,definitionById:a,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:l,one:d,options:s,patch:S_,wrap:__};return yu(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($d.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,...v}=m,b=yl(v);return b.children=c.all(m),b}return yl(m)}return(c.options.unknownHandler||E_)(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=ph(g.value)),!Array.isArray(g)&&g.type==="element")){const x=g.children[0];x&&x.type==="text"&&(x.value=ph(x.value))}Array.isArray(g)?h.push(...g):h.push(g)}}}return h}}function S_(e,n){e.position&&(n.position=hC(e))}function C_(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,yl(o)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function E_(e,n){const s=n.data||{},a="value"in n&&!($d.call(s,"hProperties")||$d.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 __(e,n){const s=[];let a=-1;for(n&&s.push({type:"text",value:`
663
- `});++a<e.length;)a&&s.push({type:"text",value:`
664
- `}),s.push(e[a]);return n&&e.length>0&&s.push({type:"text",value:`
665
- `}),s}function ph(e){let n=0,s=e.charCodeAt(n);for(;s===9||s===32;)n++,s=e.charCodeAt(n);return e.slice(n)}function fh(e,n){const s=N_(e,n),a=s.one(e,void 0),r=p_(s),o=Array.isArray(a)?{type:"root",children:a}:a||{type:"root",children:[]};return r&&o.children.push({type:"text",value:`
666
- `},r),o}function M_(e,n){return e&&"run"in e?async function(s,a){const r=fh(s,{file:a,...n});await e.run(r,a)}:function(s,a){return fh(s,{file:a,...e||n})}}function gh(e){if(e)throw e}var wc,bh;function A_(){if(bh)return wc;bh=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 wc=function d(){var u,m,h,f,p,g,x=arguments[0],v=1,b=arguments.length,k=!1;for(typeof x=="boolean"&&(k=x,x=arguments[1]||{},v=2),(x==null||typeof x!="object"&&typeof x!="function")&&(x={});v<b;++v)if(u=arguments[v],u!=null)for(m in u)h=c(x,m),f=c(u,m),x!==f&&(k&&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(k,g,f)})):typeof f<"u"&&l(x,{name:m,newValue:f}));return x},wc}var P_=A_();const kc=bf(P_);function Dd(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 R_(){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?T_(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 T_(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 wi={basename:I_,dirname:$_,extname:D_,join:L_,sep:"/"};function I_(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');fo(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 $_(e){if(fo(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 D_(e){fo(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 L_(...e){let n=-1,s;for(;++n<e.length;)fo(e[n]),e[n]&&(s=s===void 0?e[n]:s+"/"+e[n]);return s===void 0?".":O_(s)}function O_(e){fo(e);const n=e.codePointAt(0)===47;let s=F_(e,!n);return s.length===0&&!n&&(s="."),s.length>0&&e.codePointAt(e.length-1)===47&&(s+="/"),n?"/"+s:s}function F_(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 fo(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const z_={cwd:U_};function U_(){return"/"}function Ld(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function B_(e){if(typeof e=="string")e=new URL(e);else if(!Ld(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 H_(e)}function H_(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 Jg{constructor(n){let s;n?Ld(n)?s={path:n}:typeof n=="string"||q_(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":z_.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"?wi.basename(this.path):void 0}set basename(n){Sc(n,"basename"),Nc(n,"basename"),this.path=wi.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?wi.dirname(this.path):void 0}set dirname(n){xh(this.basename,"dirname"),this.path=wi.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?wi.extname(this.path):void 0}set extname(n){if(Nc(n,"extname"),xh(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=wi.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){Ld(n)&&(n=B_(n)),Sc(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?wi.basename(this.path,this.extname):void 0}set stem(n){Sc(n,"stem"),Nc(n,"stem"),this.path=wi.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 Ts(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 Nc(e,n){if(e&&e.includes(wi.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+wi.sep+"`")}function Sc(e,n){if(!e)throw new Error("`"+n+"` cannot be empty")}function xh(e,n){if(!e)throw new Error("Setting `"+n+"` requires `path` to be set too")}function q_(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const V_=(function(e){const a=this.constructor.prototype,r=a[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,a),o}),W_={}.hasOwnProperty;class wu extends V_{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=R_()}copy(){const n=new wu;let s=-1;for(;++s<this.attachers.length;){const a=this.attachers[s];n.use(...a)}return n.data(kc(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(_c("data",this.frozen),this.namespace[n]=s,this):W_.call(this.namespace,n)&&this.namespace[n]||void 0:n?(_c("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=Ao(n),a=this.parser||this.Parser;return Cc("parse",a),a(String(s),s)}process(n,s){const a=this;return this.freeze(),Cc("process",this.parser||this.Parser),Ec("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(o,l){const c=Ao(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);J_(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(),Cc("processSync",this.parser||this.Parser),Ec("processSync",this.compiler||this.Compiler),this.process(n,r),yh("processSync","process",s),a;function r(o,l){s=!0,gh(o),a=l}}run(n,s,a){vh(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=Ao(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),yh("runSync","run",a),r;function o(l,c){gh(l),r=c,a=!0}}stringify(n,s){this.freeze();const a=Ao(s),r=this.compiler||this.Compiler;return Ec("stringify",r),vh(n),r(n,a)}use(n,...s){const a=this.attachers,r=this.namespace;if(_c("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=kc(!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];Dd(x)&&Dd(p)&&(p=kc(!0,x,p)),a[f]=[u,p,...g]}}}}const K_=new wu().freeze();function Cc(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Ec(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function _c(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 vh(e){if(!Dd(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function yh(e,n,s){if(!s)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function Ao(e){return G_(e)?e:new Jg(e)}function G_(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function J_(e){return typeof e=="string"||Y_(e)}function Y_(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const Q_="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",wh=[],kh={allowDangerousHtml:!0},X_=/^(https?|ircs?|mailto|xmpp)$/i,Z_=[{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 Ci(e){const n=eM(e),s=tM(e);return nM(n.runSync(n.parse(s),s),e)}function eM(e){const n=e.rehypePlugins||wh,s=e.remarkPlugins||wh,a=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...kh}:kh;return K_().use($E).use(s).use(M_,a).use(n)}function tM(e){const n=e.children||"",s=new Jg;return typeof n=="string"&&(s.value=n),s}function nM(e,n){const s=n.allowedElements,a=n.allowElement,r=n.components,o=n.disallowedElements,l=n.skipHtml,c=n.unwrapDisallowed,d=n.urlTransform||sM;for(const m of Z_)Object.hasOwn(n,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+Q_+m.id,void 0);return yu(e,u),xC(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 xc)if(Object.hasOwn(xc,p)&&Object.hasOwn(m.properties,p)){const g=m.properties[p],x=xc[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 sM(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||X_.test(e.slice(0,n))?e:""}function jh(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 iM(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function aM(e,n,s){const r=Vl((s||{}).ignore||[]),o=rM(n);let l=-1;for(;++l<o.length;)Gg(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 v=h.children.indexOf(u);let b=!1,k=[];f.lastIndex=0;let S=f.exec(u.value);for(;S;){const j=S.index,E={index:S.index,input:S.input,stack:[...m,u]};let y=p(...S,E);if(typeof y=="string"&&(y=y.length>0?{type:"text",value:y}:void 0),y===!1?f.lastIndex=j+1:(g!==j&&k.push({type:"text",value:u.value.slice(g,j)}),Array.isArray(y)?k.push(...y):y&&k.push(y),g=j+S[0].length,b=!0),!f.global)break;S=f.exec(u.value)}return b?(g<u.value.length&&k.push({type:"text",value:u.value.slice(g)}),h.children.splice(v,1,...k)):k=[u],v+k.length}}function rM(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([oM(r[0]),lM(r[1])])}return n}function oM(e){return typeof e=="string"?new RegExp(iM(e),"g"):e}function lM(e){return typeof e=="function"?e:function(){return e}}const Mc="phrasing",Ac=["autolink","link","image","label"];function cM(){return{transforms:[gM],enter:{literalAutolink:uM,literalAutolinkEmail:Pc,literalAutolinkHttp:Pc,literalAutolinkWww:Pc},exit:{literalAutolink:fM,literalAutolinkEmail:pM,literalAutolinkHttp:mM,literalAutolinkWww:hM}}}function dM(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Mc,notInConstruct:Ac},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Mc,notInConstruct:Ac},{character:":",before:"[ps]",after:"\\/",inConstruct:Mc,notInConstruct:Ac}]}}function uM(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Pc(e){this.config.enter.autolinkProtocol.call(this,e)}function mM(e){this.config.exit.autolinkProtocol.call(this,e)}function hM(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 pM(e){this.config.exit.autolinkEmail.call(this,e)}function fM(e){this.exit(e)}function gM(e){aM(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,bM],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,xM]],{ignore:["link","linkReference"]})}function bM(e,n,s,a,r){let o="";if(!Yg(r)||(/^w/i.test(n)&&(s=n+s,n="",o="http://"),!vM(s)))return!1;const l=yM(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 xM(e,n,s,a){return!Yg(a,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function vM(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 yM(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=jh(e,"(");let o=jh(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 Yg(e,n){const s=e.input.charCodeAt(e.index-1);return(e.index===0||ha(s)||Bl(s))&&(!n||s!==47)}Qg.peek=MM;function wM(){this.buffer()}function kM(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function jM(){this.buffer()}function NM(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function SM(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=hi(this.sliceSerialize(e)).toLowerCase(),s.label=n}function CM(e){this.exit(e)}function EM(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=hi(this.sliceSerialize(e)).toLowerCase(),s.label=n}function _M(e){this.exit(e)}function MM(){return"["}function Qg(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 AM(){return{enter:{gfmFootnoteCallString:wM,gfmFootnoteCall:kM,gfmFootnoteDefinitionLabelString:jM,gfmFootnoteDefinition:NM},exit:{gfmFootnoteCallString:SM,gfmFootnoteCall:CM,gfmFootnoteDefinitionLabelString:EM,gfmFootnoteDefinition:_M}}}function PM(e){let n=!1;return e&&e.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:Qg},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?`
667
- `:" ")+o.indentLines(o.containerFlow(a,c.current()),n?Xg:RM))),u(),d}}function RM(e,n,s){return n===0?e:Xg(e,n,s)}function Xg(e,n,s){return(s?"":" ")+e}const TM=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Zg.peek=OM;function IM(){return{canContainEols:["delete"],enter:{strikethrough:DM},exit:{strikethrough:LM}}}function $M(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:TM}],handlers:{delete:Zg}}}function DM(e){this.enter({type:"delete",children:[]},e)}function LM(e){this.exit(e)}function Zg(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 OM(){return"~"}function FM(e){return e.length}function zM(e,n){const s=n||{},a=(s.align||[]).concat(),r=s.stringLength||FM,o=[],l=[],c=[],d=[];let u=0,m=-1;for(;++m<e.length;){const x=[],v=[];let b=-1;for(e[m].length>u&&(u=e[m].length);++b<e[m].length;){const k=UM(e[m][b]);if(s.alignDelimiters!==!1){const S=r(k);v[b]=S,(d[b]===void 0||S>d[b])&&(d[b]=S)}x.push(k)}l[m]=x,c[m]=v}let h=-1;if(typeof a=="object"&&"length"in a)for(;++h<u;)o[h]=Nh(a[h]);else{const x=Nh(a);for(;++h<u;)o[h]=x}h=-1;const f=[],p=[];for(;++h<u;){const x=o[h];let v="",b="";x===99?(v=":",b=":"):x===108?v=":":x===114&&(b=":");let k=s.alignDelimiters===!1?1:Math.max(1,d[h]-v.length-b.length);const S=v+"-".repeat(k)+b;s.alignDelimiters!==!1&&(k=v.length+k+b.length,k>d[h]&&(d[h]=k),p[h]=k),f[h]=S}l.splice(1,0,f),c.splice(1,0,p),m=-1;const g=[];for(;++m<l.length;){const x=l[m],v=c[m];h=-1;const b=[];for(;++h<u;){const k=x[h]||"";let S="",j="";if(s.alignDelimiters!==!1){const E=d[h]-(v[h]||0),y=o[h];y===114?S=" ".repeat(E):y===99?E%2?(S=" ".repeat(E/2+.5),j=" ".repeat(E/2-.5)):(S=" ".repeat(E/2),j=S):j=" ".repeat(E)}s.delimiterStart!==!1&&!h&&b.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&k==="")&&(s.delimiterStart!==!1||h)&&b.push(" "),s.alignDelimiters!==!1&&b.push(S),b.push(k),s.alignDelimiters!==!1&&b.push(j),s.padding!==!1&&b.push(" "),(s.delimiterEnd!==!1||h!==u-1)&&b.push("|")}g.push(s.delimiterEnd===!1?b.join("").replace(/ +$/,""):b.join(""))}return g.join(`
668
- `)}function UM(e){return e==null?"":String(e)}function Nh(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 BM(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()),HM);return r(),l}function HM(e,n,s){return">"+(s?"":" ")+e}function qM(e,n){return Sh(e,n.inConstruct,!0)&&!Sh(e,n.notInConstruct,!1)}function Sh(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 Ch(e,n,s,a){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
669
- `&&qM(s.stack,s.unsafe[r]))return/[ \t]/.test(a.before)?"":" ";return`\\
670
- `}function VM(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 WM(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 KM(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 GM(e,n,s,a){const r=KM(s),o=e.value||"",l=r==="`"?"GraveAccent":"Tilde";if(WM(e,s)){const h=s.enter("codeIndented"),f=s.indentLines(o,JM);return h(),f}const c=s.createTracker(a),d=r.repeat(Math.max(VM(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:`
671
- `,encode:["`"],...c.current()})),h()}return m+=c.move(`
672
- `),o&&(m+=c.move(o+`
673
- `)),m+=c.move(d),u(),m}function JM(e,n,s){return(s?"":" ")+e}function ku(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 YM(e,n,s,a){const r=ku(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?" ":`
674
- `,...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 QM(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 Qr(e){return"&#x"+e.toString(16).toUpperCase()+";"}function wl(e,n,s){const a=Ya(e),r=Ya(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}}eb.peek=XM;function eb(e,n,s,a){const r=QM(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=wl(a.before.charCodeAt(a.before.length-1),u,r);m.inside&&(d=Qr(u)+d.slice(1));const h=d.charCodeAt(d.length-1),f=wl(a.after.charCodeAt(0),h,r);f.inside&&(d=d.slice(0,-1)+Qr(h));const p=l.move(r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+d+p}function XM(e,n,s){return s.options.emphasis||"*"}function ZM(e,n){let s=!1;return yu(e,function(a){if("value"in a&&/\r?\n|\r/.test(a.value)||a.type==="break")return s=!0,Id}),!!((!e.depth||e.depth<3)&&hu(e)&&(n.options.setext||s))}function eA(e,n,s,a){const r=Math.max(Math.min(6,e.depth||1),1),o=s.createTracker(a);if(ZM(e,s)){const m=s.enter("headingSetext"),h=s.enter("phrasing"),f=s.containerPhrasing(e,{...o.current(),before:`
675
- `,after:`
676
- `});return h(),m(),f+`
677
- `+(r===1?"=":"-").repeat(f.length-(Math.max(f.lastIndexOf("\r"),f.lastIndexOf(`
678
- `))+1))}const l="#".repeat(r),c=s.enter("headingAtx"),d=s.enter("phrasing");o.move(l+" ");let u=s.containerPhrasing(e,{before:"# ",after:`
679
- `,...o.current()});return/^[\t ]/.test(u)&&(u=Qr(u.charCodeAt(0))+u.slice(1)),u=u?l+" "+u:l,s.options.closeAtx&&(u+=" "+l),d(),c(),u}tb.peek=tA;function tb(e){return e.value||""}function tA(){return"<"}nb.peek=nA;function nb(e,n,s,a){const r=ku(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 nA(){return"!"}sb.peek=sA;function sb(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 sA(){return"!"}ib.peek=iA;function ib(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 iA(){return"`"}function ab(e,n){const s=hu(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))}rb.peek=aA;function rb(e,n,s,a){const r=ku(s),o=r==='"'?"Quote":"Apostrophe",l=s.createTracker(a);let c,d;if(ab(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 aA(e,n,s){return ab(e,s)?"<":"["}ob.peek=rA;function ob(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 rA(){return"["}function ju(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 oA(e){const n=ju(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 lA(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 lb(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 cA(e,n,s,a){const r=s.enter("list"),o=s.bulletCurrent;let l=e.ordered?lA(s):ju(s);const c=e.ordered?l==="."?")":".":oA(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),lb(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 dA(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 uA(e,n,s,a){const r=dA(s);let o=s.bulletCurrent||ju(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 mA(e,n,s,a){const r=s.enter("paragraph"),o=s.enter("phrasing"),l=s.containerPhrasing(e,a);return o(),r(),l}const hA=Vl(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function pA(e,n,s,a){return(e.children.some(function(l){return hA(l)})?s.containerPhrasing:s.containerFlow).call(s,e,a)}function fA(e){const n=e.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}cb.peek=gA;function cb(e,n,s,a){const r=fA(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=wl(a.before.charCodeAt(a.before.length-1),u,r);m.inside&&(d=Qr(u)+d.slice(1));const h=d.charCodeAt(d.length-1),f=wl(a.after.charCodeAt(0),h,r);f.inside&&(d=d.slice(0,-1)+Qr(h));const p=l.move(r+r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+d+p}function gA(e,n,s){return s.options.strong||"*"}function bA(e,n,s,a){return s.safe(e.value,a)}function xA(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 vA(e,n,s){const a=(lb(s)+(s.options.ruleSpaces?" ":"")).repeat(xA(s));return s.options.ruleSpaces?a.slice(0,-1):a}const db={blockquote:BM,break:Ch,code:GM,definition:YM,emphasis:eb,hardBreak:Ch,heading:eA,html:tb,image:nb,imageReference:sb,inlineCode:ib,link:rb,linkReference:ob,list:cA,listItem:uA,paragraph:mA,root:pA,strong:cb,text:bA,thematicBreak:vA};function yA(){return{enter:{table:wA,tableData:Eh,tableHeader:Eh,tableRow:jA},exit:{codeText:NA,table:kA,tableData:Rc,tableHeader:Rc,tableRow:Rc}}}function wA(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 kA(e){this.exit(e),this.data.inTable=void 0}function jA(e){this.enter({type:"tableRow",children:[]},e)}function Rc(e){this.exit(e)}function Eh(e){this.enter({type:"tableCell",children:[]},e)}function NA(e){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,SA));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(e)}function SA(e,n){return n==="|"?n:e}function CA(e){const n=e||{},s=n.tableCellPadding,a=n.tablePipeAlign,r=n.stringLength,o=s?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
680
- `,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,v){return u(m(p,x,v),p.align)}function c(p,g,x,v){const b=h(p,x,v),k=u([b]);return k.slice(0,k.indexOf(`
681
- `))}function d(p,g,x,v){const b=x.enter("tableCell"),k=x.enter("phrasing"),S=x.containerPhrasing(p,{...v,before:o,after:o});return k(),b(),S}function u(p,g){return zM(p,{align:g,alignDelimiters:a,padding:s,stringLength:r})}function m(p,g,x){const v=p.children;let b=-1;const k=[],S=g.enter("table");for(;++b<v.length;)k[b]=h(v[b],g,x);return S(),k}function h(p,g,x){const v=p.children;let b=-1;const k=[],S=g.enter("tableRow");for(;++b<v.length;)k[b]=d(v[b],p,g,x);return S(),k}function f(p,g,x){let v=db.inlineCode(p,g,x);return x.stack.includes("tableCell")&&(v=v.replace(/\|/g,"\\$&")),v}}function EA(){return{exit:{taskListCheckValueChecked:_h,taskListCheckValueUnchecked:_h,paragraph:MA}}}function _A(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:AA}}}function _h(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function MA(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 AA(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=db.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 PA(){return[cM(),AM(),IM(),yA(),EA()]}function RA(e){return{extensions:[dM(),PM(e),$M(),CA(e),_A()]}}const TA={tokenize:FA,partial:!0},ub={tokenize:zA,partial:!0},mb={tokenize:UA,partial:!0},hb={tokenize:BA,partial:!0},IA={tokenize:HA,partial:!0},pb={name:"wwwAutolink",tokenize:LA,previous:gb},fb={name:"protocolAutolink",tokenize:OA,previous:bb},zi={name:"emailAutolink",tokenize:DA,previous:xb},Ai={};function $A(){return{text:Ai}}let ia=48;for(;ia<123;)Ai[ia]=zi,ia++,ia===58?ia=65:ia===91&&(ia=97);Ai[43]=zi;Ai[45]=zi;Ai[46]=zi;Ai[95]=zi;Ai[72]=[zi,fb];Ai[104]=[zi,fb];Ai[87]=[zi,pb];Ai[119]=[zi,pb];function DA(e,n,s){const a=this;let r,o;return l;function l(h){return!Od(h)||!xb.call(a,a.previous)||Nu(a.events)?s(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(h))}function c(h){return Od(h)?(e.consume(h),c):h===64?(e.consume(h),d):s(h)}function d(h){return h===46?e.check(IA,m,u)(h):h===45||h===95||Ps(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&&Ls(a.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),n(h)):s(h)}}function LA(e,n,s){const a=this;return r;function r(l){return l!==87&&l!==119||!gb.call(a,a.previous)||Nu(a.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(TA,e.attempt(ub,e.attempt(mb,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function OA(e,n,s){const a=this;let r="",o=!1;return l;function l(h){return(h===72||h===104)&&bb.call(a,a.previous)&&!Nu(a.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),e.consume(h),c):s(h)}function c(h){if(Ls(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||xl(h)||Bn(h)||ha(h)||Bl(h)?s(h):e.attempt(ub,e.attempt(mb,m),s)(h)}function m(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(h)}}function FA(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 zA(e,n,s){let a,r,o;return l;function l(u){return u===46||u===95?e.check(hb,d,c)(u):u===null||Bn(u)||ha(u)||u!==45&&Bl(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 UA(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(hb,n,o)(l):l===null||Bn(l)||ha(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&a++,e.consume(l),r}}function BA(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)||ha(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||Bn(c)||ha(c)?n(c):a(c)}function o(c){return Ls(c)?l(c):s(c)}function l(c){return c===59?(e.consume(c),a):Ls(c)?(e.consume(c),l):s(c)}}function HA(e,n,s){return a;function a(o){return e.consume(o),r}function r(o){return Ps(o)?s(o):n(o)}}function gb(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||Bn(e)}function bb(e){return!Ls(e)}function xb(e){return!(e===47||Od(e))}function Od(e){return e===43||e===45||e===46||e===95||Ps(e)}function Nu(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 qA={tokenize:XA,partial:!0};function VA(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:JA,continuation:{tokenize:YA},exit:QA}},text:{91:{name:"gfmFootnoteCall",tokenize:GA},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:WA,resolveTo:KA}}}}function WA(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=hi(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 KA(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 GA(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(hi(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 JA(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=hi(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 YA(e,n,s){return e.check(po,n,e.attempt(qA,n,s))}function QA(e){e.exit("gfmFootnoteDefinition")}function XA(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 ZA(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&&Js(f,f.length,0,Hl(p,l.slice(u+1,d),c)),Js(f,f.length,0,[["exit",h,c],["enter",l[d][1],c],["exit",l[d][1],c],["exit",m,c]]),Js(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=Ya(u);if(g===126)return h>1?d(g):(l.consume(g),h++,p);if(h<2&&!s)return d(g);const v=l.exit("strikethroughSequenceTemporary"),b=Ya(g);return v._open=!b||b===2&&!!x,v._close=!x||x===2&&!!b,c(g)}}}class eP{constructor(){this.map=[]}add(n,s,a){tP(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 tP(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 nP(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 sP(){return{flow:{null:{name:"table",tokenize:iP,resolveAll:aP}}}}function iP(e,n,s){const a=this;let r=0,o=0,l;return c;function c(C){let _=a.events.length-1;for(;_>-1;){const A=a.events[_][1].type;if(A==="lineEnding"||A==="linePrefix")_--;else break}const F=_>-1?a.events[_][1].type:null,U=F==="tableHead"||F==="tableRow"?y:d;return U===y&&a.parser.lazy[a.now().line]?s(C):U(C)}function d(C){return e.enter("tableHead"),e.enter("tableRow"),u(C)}function u(C){return C===124||(l=!0,o+=1),m(C)}function m(C){return C===null?s(C):Ht(C)?o>1?(o=0,a.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),p):s(C):gn(C)?jn(e,m,"whitespace")(C):(o+=1,l&&(l=!1,r+=1),C===124?(e.enter("tableCellDivider"),e.consume(C),e.exit("tableCellDivider"),l=!0,m):(e.enter("data"),h(C)))}function h(C){return C===null||C===124||Bn(C)?(e.exit("data"),m(C)):(e.consume(C),C===92?f:h)}function f(C){return C===92||C===124?(e.consume(C),h):h(C)}function p(C){return a.interrupt=!1,a.parser.lazy[a.now().line]?s(C):(e.enter("tableDelimiterRow"),l=!1,gn(C)?jn(e,g,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(C):g(C))}function g(C){return C===45||C===58?v(C):C===124?(l=!0,e.enter("tableCellDivider"),e.consume(C),e.exit("tableCellDivider"),x):E(C)}function x(C){return gn(C)?jn(e,v,"whitespace")(C):v(C)}function v(C){return C===58?(o+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(C),e.exit("tableDelimiterMarker"),b):C===45?(o+=1,b(C)):C===null||Ht(C)?j(C):E(C)}function b(C){return C===45?(e.enter("tableDelimiterFiller"),k(C)):E(C)}function k(C){return C===45?(e.consume(C),k):C===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(C),e.exit("tableDelimiterMarker"),S):(e.exit("tableDelimiterFiller"),S(C))}function S(C){return gn(C)?jn(e,j,"whitespace")(C):j(C)}function j(C){return C===124?g(C):C===null||Ht(C)?!l||r!==o?E(C):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(C)):E(C)}function E(C){return s(C)}function y(C){return e.enter("tableRow"),N(C)}function N(C){return C===124?(e.enter("tableCellDivider"),e.consume(C),e.exit("tableCellDivider"),N):C===null||Ht(C)?(e.exit("tableRow"),n(C)):gn(C)?jn(e,N,"whitespace")(C):(e.enter("data"),M(C))}function M(C){return C===null||C===124||Bn(C)?(e.exit("data"),N(C)):(e.consume(C),C===92?D:M)}function D(C){return C===92||C===124?(e.consume(C),M):M(C)}}function aP(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 eP;for(;++s<e.length;){const p=e[s],g=p[1];p[0]==="enter"?g.type==="tableHead"?(c=!1,d!==0&&(Mh(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=Po(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=Po(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=Po(f,n,o,r,s,h)):l[1]!==0&&(h=Po(f,n,l,r,s,h)),r=0):r&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(l[3]=s)}for(d!==0&&Mh(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=nP(n.events,s))}return e}function Po(e,n,s,a,r,o){const l=a===1?"tableHeader":a===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},La(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const d=La(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=La(n.events,s[2]),m=La(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({},La(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function Mh(e,n,s,a,r){const o=[],l=La(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 La(e,n){const s=e[n],a=s[0]==="enter"?"start":"end";return s[1][a]}const rP={name:"tasklistCheck",tokenize:lP};function oP(){return{text:{91:rP}}}function lP(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 Ht(d)?n(d):gn(d)?e.check({tokenize:cP},n,s)(d):s(d)}}function cP(e,n,s){return jn(e,a,"whitespace");function a(r){return r===null?s(r):n(r)}}function dP(e){return Mg([$A(),VA(),ZA(e),sP(),oP()])}const uP={};function Ei(e){const n=this,s=e||uP,a=n.data(),r=a.micromarkExtensions||(a.micromarkExtensions=[]),o=a.fromMarkdownExtensions||(a.fromMarkdownExtensions=[]),l=a.toMarkdownExtensions||(a.toMarkdownExtensions=[]);r.push(dP(s)),o.push(PA()),l.push(RA(s))}const mP=45e3,hP=3e3,pP=2e3,fP=1500,Ah="fusion:sse-client-id";let Pa=null;const Vi=new Map;function Ph(){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 vb(){if(!(typeof window>"u")){if(Pa)return Pa;try{const e=window.sessionStorage.getItem(Ah);if(e)return Pa=e,e;const n=Ph();return window.sessionStorage.setItem(Ah,n),Pa=n,n}catch{return Pa=Ph(),Pa}}}function yb(e){if(!(typeof window>"u"))try{return{parsed:new URL(e,window.location.origin),preserveRelativePath:e.startsWith("/")}}catch{return}}function wb(e){return e.origin===window.location.origin&&e.pathname==="/api/events"}function gP(e){const n=vb();if(!n)return e;const s=yb(e);return!s||!wb(s.parsed)?e:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function Su(e,n){const s=vb();if(!s)return;const a=yb(e);if(!a||!wb(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),Ni(`${r.pathname}${r.search}${r.hash}`)}function bP(e){if(typeof window>"u")return;const n=Su(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 Kl(e){e.keepaliveTimer&&(clearInterval(e.keepaliveTimer),e.keepaliveTimer=null)}function Rh(e){if(typeof window>"u"||typeof window.fetch!="function")return;const n=Su(e.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,a=s?window.setTimeout(()=>s.abort(),fP):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{a!==null&&window.clearTimeout(a)})}function xP(e){Kl(e),Su(e.url,"keepalive")&&(Rh(e),e.keepaliveTimer=window.setInterval(()=>{Rh(e)},pP))}if(typeof window<"u"){const e=()=>{for(const s of Array.from(Vi.values()))if(!s.closed){if(Kl(s),bP(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(Vi.values()))a.subscribers.size!==0&&(a.closed=!1,Cu(a))};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("pageshow",n)}function Tr(e){e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),e.heartbeatTimer=setTimeout(()=>{kb(e)},mP)}function kb(e){if(e.heartbeatTimer&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=null),e.es&&(e.es.close(),e.es=null),Kl(e),e.nativeListeners.clear(),e.closed||e.subscribers.size===0||e.reconnectTimer)return;const n=Vi.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=Vi.get(e.url);s&&s===e&&e.subscribers.size>0&&Cu(e)},hP)}}function Cu(e){if(e.es||e.closed)return;e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);const n=new EventSource(Ni(gP(e.url)));e.es=n,xP(e),n.addEventListener("open",()=>{Tr(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);kb(e)}),n.addEventListener("message",()=>Tr(e)),n.addEventListener("heartbeat",()=>Tr(e)),jb(e),Tr(e)}function jb(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=>{Tr(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 vP(e){e.closed=!0,e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),Kl(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.es&&e.es.close(),e.es=null,e.nativeListeners.clear(),Vi.delete(e.url)}function gi(e,n={}){let s=Vi.get(e);s||(s={url:e,es:null,subscribers:new Set,nativeListeners:new Map,heartbeatTimer:null,keepaliveTimer:null,reconnectTimer:null,hasOpenedOnce:!1,closed:!1},Vi.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;Cu(s),jb(s),r&&queueMicrotask(()=>{s.subscribers.has(a)&&a.onOpen?.()});let o=!0;return()=>{if(!o)return;o=!1;const l=Vi.get(e);l&&(l.subscribers.delete(a),l.subscribers.size===0&&vP(l))}}const Th=100;function Nb(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),v=i.useRef(e),b=i.useRef(s),k=i.useRef(n),S=i.useRef(0);(v.current!==e||b.current!==s||k.current!==n)&&(v.current=e,b.current=s,k.current=n,x.current++,g.current=!0,r([]),l(!1),d(!1),m(null),f(!1),p.current&&(p.current(),p.current=null)),i.useEffect(()=>{if(!e||!n){p.current&&(p.current(),p.current=null);return}const N=x.current,M=++S.current;g.current=!1;const D=e,C=s;async function _(){if(!D)return;l(!0),f(!1);try{const U=await Uu(D,C,{limit:Th});if(g.current||x.current!==N||S.current!==M)return;r(U.entries),d(U.hasMore),m(U.total)}catch{if(g.current||x.current!==N||S.current!==M)return;r([]),d(!1),m(null)}finally{!g.current&&x.current===N&&S.current===M&&l(!1)}const F=C?`?projectId=${encodeURIComponent(C)}`:"";p.current=gi(`/api/tasks/${D}/logs/stream${F}`,{events:{"agent:log":U=>{if(!(g.current||x.current!==N))try{const A=JSON.parse(U.data);r($=>[...$,A]),m($=>$!==null?$+1:null)}catch{}}}})}return _(),()=>{g.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const E=i.useCallback(async()=>{if(!e||h)return;const N=x.current,M=a.length,D=e;f(!0);try{const C=await Uu(D,s,{limit:Th,offset:M});if(g.current||x.current!==N)return;r(_=>[...C.entries,..._]),d(C.hasMore),m(C.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 Ih="fn-agent-log-markdown",$h="fn-agent-log-tool-output";function Dh(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 Lh(e,n){if(!(typeof window>"u"))try{window.localStorage.setItem(e,n?"true":"false")}catch{}}function yP(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 Oh={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})},Sb=50,wP={triage:"Plan"};function Fh(e){return e.scrollHeight-(e.scrollTop+e.clientHeight)<=Sb}function Fd(e){return[e.taskId,e.timestamp,e.agent??"",e.type,e.text,e.detail??""].join("|")}function kP(e){const n=new Map;return e.map(s=>{const a=Fd(s),r=n.get(a)??0;return n.set(a,r+1),`${a}|${r}`})}function Cb(e){return e==="tool"||e==="tool_result"||e==="tool_error"}function Tc({detail:e}){const[n,s]=i.useState(!1),a=i.useId(),r=e.split(`
682
- `).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(Un,{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 jP(e,n){return e.agent?Cb(e.type)?!0:!n||n.agent!==e.agent||n.type!==e.type:!1}function NP(e,n){const s=[];for(let a=0;a<e.length;a+=1){const r=e[a],o=n[a]??`${Fd(r)}|fallback`,l=a>0?e[a-1]:void 0,c=jP(r,l);if(r.type==="text"||r.type==="thinking"){const d=[r];let u=a+1;for(;u<e.length;){const h=e[u];if(h.type!==r.type||h.agent!==r.agent)break;d.push(h),u+=1}const m=n[u-1]??`${Fd(e[u-1])}|fallback`;s.push({kind:r.type,entries:d,key:`${o}->${m}`,showBadge:c}),a=u-1;continue}s.push({kind:"single",entry:r,key:o,showBadge:c})}return s}function SP({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(()=>Dh(Ih,!0)),[v,b]=i.useState(()=>Dh($h,!0)),[k,S]=i.useState(!1),[j,E]=i.useState(!1),[y,N]=i.useState(!0);i.useEffect(()=>{Lh(Ih,g)},[g]),i.useEffect(()=>{Lh($h,v)},[v]);const M=i.useMemo(()=>v?e:e.filter(B=>!Cb(B.type)),[e,v]),D=i.useMemo(()=>kP(M),[M]),C=i.useMemo(()=>NP(M,D),[M,D]);i.useLayoutEffect(()=>{const B=u.current;if(!B)return;const se=e.length,P=m.current,O=h.current||B.scrollHeight,I=D[0]??null,w=D[D.length-1]??null,Y=f.current!==I,re=p.current!==w;if(se>P)if(P===0)B.scrollTop=B.scrollHeight;else{const le=O-(B.scrollTop+B.clientHeight)<=Sb,ve=re&&!Y,de=Y&&!re;if(ve&&le&&(B.scrollTop=B.scrollHeight),de){const Fe=B.scrollHeight-O;Fe>0&&(B.scrollTop+=Fe)}}m.current=se,h.current=B.scrollHeight,f.current=I,p.current=w,N(Fh(B))},[e,D]);const _=i.useCallback(()=>{const B=u.current;B&&N(Fh(B))},[]),F=i.useCallback(()=>{const B=u.current;B&&(B.scrollTop=B.scrollHeight,N(!0))},[]),U=i.useCallback(B=>{B.key==="Escape"&&k&&S(!1)},[k]);i.useEffect(()=>{if(k)return document.addEventListener("keydown",U),()=>{document.removeEventListener("keydown",U)}},[k,U]);const A=s?.provider&&s?.modelId,$=a?.provider&&a?.modelId,T=r?.provider&&r?.modelId,J=i.useMemo(()=>{const B=[];return A&&B.push({role:"Executor",provider:s.provider,modelId:s.modelId}),$&&B.push({role:"Reviewer",provider:a.provider,modelId:a.modelId}),T&&B.push({role:"Planning",provider:r.provider,modelId:r.modelId}),B},[A,s,$,a,T,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${k?" 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:[J.map(B=>t.jsx(Kn,{provider:B.provider,size:"sm"},`${B.role}-${B.provider}-${B.modelId??"default"}`)),t.jsx("button",{className:"agent-log-model-expand-btn",onClick:()=>E(B=>!B),"aria-label":j?"Collapse model details":"Expand model details","aria-expanded":j,"aria-controls":"agent-log-model-details","data-testid":"agent-log-model-expand",children:j?t.jsx(un,{size:14}):t.jsx(Un,{size:14})})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>x(B=>!B),"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(B=>!B),"aria-label":v?"Hide tool output":"Show tool output","aria-pressed":v,"data-testid":"agent-log-tool-output-toggle",title:v?"Hide tool calls and results":"Show tool calls and results",children:v?"Tools: On":"Tools: Off"}),t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>S(B=>!B),"aria-label":k?"Exit full screen":"Expand agent log to full screen","data-testid":"agent-log-fullscreen-toggle",title:k?"Exit full screen":"Expand agent log to full screen",children:k?t.jsx(io,{size:14}):t.jsx($l,{size:14})})]}),j&&t.jsxs("div",{id:"agent-log-model-details",className:"agent-log-model-details",children:[t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Executor:"}),A?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Kn,{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:"}),$?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Kn,{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:"}),T?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Kn,{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:_,children:[d!==null&&t.jsxs("div",{className:"agent-log-summary","data-testid":"agent-log-summary",children:["Showing ",M.length," of ",d," entries",!v&&e.length!==M.length?` (${e.length-M.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(bt,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})}),C.map(B=>{const se=B.kind==="single"?B.entry:B.entries[0],P=B.showBadge?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:yP(se.timestamp)}):null,O=B.showBadge?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",wP[se.agent]??se.agent,"]"]}),P]}):null;if(B.kind==="single"){const{entry:w}=B;if(w.type==="tool")return t.jsxs("div",{className:"agent-log-tool",children:[O,t.jsxs("div",{className:"agent-log-tool-title",children:["⚡ ",w.text]}),w.detail?t.jsx(Tc,{detail:w.detail,type:"tool"}):null]},B.key);if(w.type==="tool_result")return t.jsxs("div",{className:"agent-log-tool-result",children:[O,t.jsxs("div",{className:"agent-log-tool-title",children:["✓ ",w.text]}),w.detail?t.jsx(Tc,{detail:w.detail,type:"tool_result"}):null]},B.key);if(w.type==="tool_error")return t.jsxs("div",{className:"agent-log-tool-error",children:[O,t.jsxs("div",{className:"agent-log-tool-title",children:["✗ ",w.text]}),w.detail?t.jsx(Tc,{detail:w.detail,type:"tool_error"}):null]},B.key)}const I=B.kind==="single"?se.text:B.entries.map(w=>w.text).join("");return B.kind==="thinking"?t.jsxs("div",{className:"agent-log-thinking",children:[O,g?t.jsx("div",{className:"markdown-body",children:t.jsx(Ci,{remarkPlugins:[Ei],components:Oh,children:I})}):t.jsx("pre",{className:"agent-log-plain-block",children:I})]},B.key):t.jsxs("div",{className:"agent-log-text",children:[O,g?t.jsx("div",{className:"markdown-body",children:t.jsx(Ci,{remarkPlugins:[Ei],components:Oh,children:I})}):t.jsx("pre",{className:"agent-log-plain-block",children:I})]},B.key)}),!y&&t.jsxs("button",{type:"button",className:"agent-log-return-to-live",onClick:F,"data-testid":"agent-log-return-to-live",children:[t.jsx(un,{size:12}),t.jsx("span",{children:"Live"})]})]})]})}function Qa(e){return e??void 0}function Ro(e){return{provider:Qa(e.modelProvider),modelId:Qa(e.modelId)}}function To(e){return{provider:Qa(e.validatorModelProvider),modelId:Qa(e.validatorModelId)}}function Io(e){return{provider:Qa(e.planningModelProvider),modelId:Qa(e.planningModelId)}}function CP(e,n){return eg(e,n)}function EP(e,n){return tg(e,n)}function _P(e,n){return ng(e,n)}function Ic(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 $c(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function Dc(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function MP(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 AP({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(()=>Ro(e)),[v,b]=i.useState(()=>Ro(e)),[k,S]=i.useState(()=>To(e)),[j,E]=i.useState(()=>To(e)),[y,N]=i.useState(()=>Io(e)),[M,D]=i.useState(()=>Io(e)),[C,_]=i.useState(()=>e.thinkingLevel??null),[F,U]=i.useState(()=>e.thinkingLevel??null),[A,$]=i.useState(null),T=i.useRef(e.id);i.useEffect(()=>{h(!0),p(null),Os().then(H=>{o(H.models),c(H.favoriteProviders),u(H.favoriteModels)}).catch(H=>{p(H.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const J=i.useCallback(async H=>{const z=l,we=z.includes(H)?z.filter(Z=>Z!==H):[H,...z];c(we);try{await Dn({favoriteProviders:we,favoriteModels:d})}catch{c(z),n("Failed to update favorites","error")}},[l,d,n]),B=i.useCallback(async H=>{const z=d,we=z.includes(H)?z.filter(Z=>Z!==H):[H,...z];u(we);try{await Dn({favoriteProviders:l,favoriteModels:we})}catch{u(z),n("Failed to update model favorites","error")}},[d,l,n]);i.useEffect(()=>{T.current=e.id;const H=Ro(e),z=To(e),W=Io(e);x(H),b(H),S(z),E(z),N(W),D(W);const we=e.thinkingLevel??null;_(we),U(we),$(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const se=i.useMemo(()=>$c(g),[g]),P=i.useMemo(()=>$c(k),[k]),O=i.useMemo(()=>$c(y),[y]),I=i.useMemo(()=>CP(e,a),[e,a]),w=i.useMemo(()=>EP(e,a),[e,a]),Y=i.useMemo(()=>_P(e,a),[e,a]),re=A!==null,le=i.useCallback(async(H,z)=>{const W=e.id,we=v,Z=j,fe=M;$(H);try{const Oe=s?H==="executor"?{modelProvider:z.provider??null,modelId:z.modelId??null}:H==="validator"?{validatorModelProvider:z.provider??null,validatorModelId:z.modelId??null}:{planningModelProvider:z.provider??null,planningModelId:z.modelId??null}:{modelProvider:(H==="executor"?z:v).provider??null,modelId:(H==="executor"?z:v).modelId??null,validatorModelProvider:(H==="validator"?z:j).provider??null,validatorModelId:(H==="validator"?z:j).modelId??null,planningModelProvider:(H==="planning"?z:M).provider??null,planningModelId:(H==="planning"?z:M).modelId??null},Ve=await ki(W,Oe);if(T.current!==W)return;const He=Ro(Ve),Je=To(Ve),$e=Io(Ve);b(He),x(He),E(Je),S(Je),D($e),N($e),s?.(Ve),n(MP(H,{executor:He,validator:Je,planning:$e}[H]),"success")}catch(Oe){if(T.current!==W)return;H==="executor"?x(we):H==="validator"?S(Z):N(fe),n(_e(Oe)||"Failed to save model settings","error")}finally{T.current===W&&$(null)}},[e.id,v,j,M,n,s]),ve=i.useCallback(H=>{const z=Ic(H);x(z),!Dc(z,v)&&le("executor",z)},[v,le]),de=i.useCallback(H=>{const z=Ic(H);S(z),!Dc(z,j)&&le("validator",z)},[j,le]),Fe=i.useCallback(H=>{const z=Ic(H);N(z),!Dc(z,M)&&le("planning",z)},[M,le]),X=i.useCallback(async H=>{const z=e.id,W=F,we=H===""?null:H;_(we),$("thinking");try{const Z=await ki(z,{thinkingLevel:we});if(T.current!==z)return;const fe=Z.thinkingLevel??null;U(fe),_(fe),s?.(Z);const Oe=a?.defaultThinkingLevel??"off";n(fe===null?`Thinking level set to default (${Oe})`:`Thinking level set to ${fe}`,"success")}catch(Z){if(T.current!==z)return;_(W),n(_e(Z)||"Failed to save thinking level","error")}finally{T.current===z&&$(null)}},[e.id,F,a,n,s]),L=!v.provider&&!v.modelId,Q=!j.provider&&!j.modelId,ne=!M.provider&&!M.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),Os().then(H=>{o(H.models),c(H.favoriteProviders),u(H.favoriteModels)}).catch(H=>p(H.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:L?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",I.provider&&I.modelId?` (${I.provider}/${I.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[v.provider&&t.jsx(Kn,{provider:v.provider,size:"sm"}),v.provider,"/",v.modelId]})}),t.jsx(Ns,{id:"executorModel",label:"Executor Model",value:se,onChange:ve,models:r,disabled:re,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:J,favoriteModels:d,onToggleModelFavorite:B}),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:Q?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",w.provider&&w.modelId?` (${w.provider}/${w.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[j.provider&&t.jsx(Kn,{provider:j.provider,size:"sm"}),j.provider,"/",j.modelId]})}),t.jsx(Ns,{id:"validatorModel",label:"Reviewer Model",value:P,onChange:de,models:r,disabled:re,placeholder:"Select reviewer model…",favoriteProviders:l,onToggleFavorite:J,favoriteModels:d,onToggleModelFavorite:B}),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:ne?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",Y.provider&&Y.modelId?` (${Y.provider}/${Y.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[M.provider&&t.jsx(Kn,{provider:M.provider,size:"sm"}),M.provider,"/",M.modelId]})}),t.jsx(Ns,{id:"planningModel",label:"Planning Model",value:O,onChange:Fe,models:r,disabled:re,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:J,favoriteModels:d,onToggleModelFavorite:B}),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:F===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:F})}),t.jsxs("select",{id:"thinkingLevel",value:C??"",onChange:H=>X(H.target.value),disabled:re,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:L&&Q&&ne&&F===null?"Using project or global default models.":"Model settings are up to date."})]})]})}const PP={open:t.jsx(Ml,{size:16}),closed:t.jsx(no,{size:16}),merged:t.jsx(Cf,{size:16})};function RP({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(""),[v,b]=i.useState(!1),[k,S]=i.useState(!1),[j,E]=i.useState(null),y=i.useCallback(async()=>{if(f.trim()){b(!0);try{const C=await Dk(e,{title:f.trim(),body:g.trim()||void 0},n);c(C),h(!1),p(""),x(""),u(`Created PR #${C.number}`,"success")}catch(C){u(_e(C)||"Failed to create PR","error")}finally{b(!1)}}},[e,f,g,n,c,u]),N=i.useCallback(async()=>{if(s){S(!0);try{const C=await Lk(e,n);E(C),d(C.prInfo),u("PR status refreshed","success")}catch(C){u(_e(C)||"Failed to refresh PR","error")}finally{S(!1)}}},[e,s,n,d,u]);if(!s)return a==="creating-pr"?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Ks,{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(Ks,{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(Ks,{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:C=>p(C.target.value),disabled:v,className:"pr-input"}),t.jsx("textarea",{placeholder:"PR description (optional)",value:g,onChange:C=>x(C.target.value),disabled:v,className:"pr-textarea",rows:3}),t.jsxs("div",{className:"pr-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>h(!1),disabled:v,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:y,disabled:!f.trim()||v,children:v?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Ks,{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 M=PP[s.status]??t.jsx(Ml,{size:16}),D=j?.blockingReasons??[];return t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Ks,{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:M}),t.jsx("span",{className:`pr-status-badge pr-status-badge--${s.status}`,children:s.status}),t.jsxs("span",{className:"pr-number",children:["#",s.number]}),t.jsx("div",{className:"pr-spacer"}),t.jsx("button",{className:"btn btn-sm pr-refresh-btn",onClick:N,disabled:k,title:"Refresh PR status",children:t.jsx(us,{size:14,style:{verticalAlign:"middle",opacity:k?.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:D.length>0?`Waiting for: ${D.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(Di,{size:14}),s.commentCount]}),t.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[t.jsx(jf,{size:14}),"View on GitHub"]})]})]})]})}const zh=2e3;function TP(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function IP(e){return e==="agent"||e==="system"}function $P({task:e,onTaskUpdated:n,addToast:s,currentAuthor:a="user",projectId:r}){const[o,l]=i.useState(""),[c,d]=i.useState(null),[u,m]=i.useState(""),[h,f]=i.useState(!1),[p,g]=i.useState(null),x=i.useMemo(()=>[...e.comments||[]].sort((N,M)=>new Date(M.createdAt).getTime()-new Date(N.createdAt).getTime()),[e.comments]),v=o.length>zh;async function b(){const N=o.trim();if(N){f(!0);try{const M=await ik(e.id,N,r);l(""),n?.(M),s("Comment added","success")}catch(M){s(_e(M)||"Failed to add comment","error")}finally{f(!1)}}}async function k(N){const M=u.trim();if(M){f(!0);try{const D=await Zw(e.id,N,M,r);d(null),m(""),n?.(D),s("Comment updated","success")}catch(D){s(_e(D)||"Failed to update comment","error")}finally{f(!1)}}}async function S(N){g(N);try{const M=await ek(e.id,N,r);n?.(M),s("Comment deleted","success")}catch(M){s(_e(M)||"Failed to delete comment","error")}finally{g(null)}}function j(N){N.key==="Enter"&&(N.ctrlKey||N.metaKey)&&(N.preventDefault(),b())}return t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Comments"}),x.length===0?t.jsx("div",{className:"detail-log-empty",children:"No comments yet."}):t.jsx("div",{className:"detail-activity-list",children:x.map(N=>{const M=N.author===a,D=c===N.id,C=IP(N.author);return t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header comments-header-row",children:[t.jsxs("div",{className:"comments-author-row",children:[C?t.jsx("span",{className:"ai-guidance-badge","data-testid":"ai-guidance-badge",children:"AI Guidance"}):t.jsx("strong",{children:N.author}),t.jsx("span",{className:"detail-log-timestamp",children:TP(N)})]}),M&&!D?t.jsxs("div",{className:"comments-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{d(N.id),m(N.text)},children:"Edit"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void S(N.id),disabled:p===N.id,children:p===N.id?"Deleting…":"Delete"})]}):null]}),D?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:u,onChange:_=>m(_.target.value),rows:3,className:"comments-textarea"}),t.jsxs("div",{className:"comments-edit-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{d(null),m("")},disabled:h,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void k(N.id),disabled:h||!u.trim(),children:"Save"})]})]}):t.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:N.text})]},N.id)})}),t.jsxs("div",{className:"comments-compose-form",children:[t.jsx("textarea",{value:o,onChange:N=>l(N.target.value),onKeyDown:j,rows:3,placeholder:"Add a comment",className:"comments-textarea"}),t.jsxs("div",{className:"comments-footer-row",children:[t.jsxs("span",{className:`comments-char-count${v?" comments-char-count--over":""}`,children:[o.length," / ",zh]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void b(),disabled:h||!o.trim()||v,children:h?"Posting…":"Add Comment"})]})]})]})}function DP(e){return e?e.slice(0,7):"Unknown"}function LP({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:DP(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 Eb(e){return e.split(`
683
- `).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}
684
- `},a):t.jsx(rl.Fragment,{children:`${s}
685
- `},a)})}function OP(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function FP({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);_i(f,e,"fusion:changes-diff-modal-size");const p=Fi(l);i.useEffect(()=>{s.length>0&&d===null&&u(0)},[s,d]);const g=i.useCallback(()=>{u(k=>k!==null&&k>0?k-1:k)},[]),x=i.useCallback(()=>{u(k=>k!==null&&k<s.length-1?k+1:k)},[]);if(i.useEffect(()=>{if(!e)return;const k=S=>{if(S.key==="Escape"){l();return}S.key==="ArrowUp"&&(S.metaKey||S.ctrlKey)&&(S.preventDefault(),g()),S.key==="ArrowDown"&&(S.metaKey||S.ctrlKey)&&(S.preventDefault(),x())};return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[e,l,g,x]),!e)return null;const v=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(ui,{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(_l,{})}),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(Un,{})})]}),t.jsx("button",{className:`btn btn-sm ${m?"btn-primary":""}`,onClick:()=>h(k=>!k),title:m?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(cl,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx(us,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(en,{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(so,{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((k,S)=>t.jsxs("button",{className:`changes-diff-file-item ${d===S?"selected":""}`,onClick:()=>u(S),title:k.path,children:[t.jsx("span",{className:`changes-file-status changes-file-status--${k.status}`,children:OP(k.status)}),t.jsx("span",{className:"changes-diff-file-path",title:k.path,children:t.jsx("bdo",{dir:"ltr",children:k.path})}),t.jsxs("span",{className:"changes-diff-file-stat",children:["+",k.additions," -",k.deletions]})]},k.path))})]}),t.jsx("div",{className:"changes-diff-content",children:v?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:v.path}),t.jsxs("span",{className:"changes-diff-file-header-stats",children:["+",v.additions," -",v.deletions]})]}),v.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:Eb(v.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(ui,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function _b(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function Lc(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(so,{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(ui,{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:_b("unknown")}),t.jsx("span",{className:"changes-file-path",title:a,children:t.jsx("bdo",{dir:"ltr",children:a})})]})},a))})]})}function zP({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),[v,b]=i.useState(null),[k,S]=i.useState(!0),[j,E]=i.useState(!1),y=a==="done",N=y&&!!r?.commitSha,M=a==="in-progress"||a==="in-review"||N,D=i.useCallback(async()=>{if(!M){h(!1);return}try{h(!0),p(null);const A=await Bf(e,void 0,s),$=A.files.map(T=>({path:T.path,status:T.status,additions:T.additions,deletions:T.deletions,patch:T.patch}));c($),u(A.stats),$.length>0&&(x(new Set([$[0].path])),b(0))}catch(A){p(_e(A)||"Failed to load diff")}finally{h(!1)}},[e,s,M]);i.useEffect(()=>{D()},[D]);const C=A=>{x($=>{const T=new Set($);if(T.has(A))T.delete(A);else{T.add(A);const J=l.findIndex(B=>B.path===A);J!==-1&&b(J)}return T})},_=A=>{if(A<0||A>=l.length)return;const $=l[A].path;x(new Set([$])),b(A)},F=v!==null&&v>0,U=v!==null&&v<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(Rs,{size:16}),t.jsxs("span",{children:["Error loading changes: ",f]})]})});if(!y&&!n)return o&&o.length>0?Lc(o,!1):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(ui,{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&&!N){if(o&&o.length>0)return Lc(o,!0,r);const A=r?.filesChanged,$=r?.insertions,T=r?.deletions,J=A!=null||$!=null||T!=null;return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(ui,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:J?`Merge summary: ${A??0} file${(A??0)===1?"":"s"} changed, +${$??0} additions, -${T??0} deletions.`:"No merge commit was recorded for this task."})]})})}return l.length===0?o&&o.length>0?Lc(o,y,r):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(ui,{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(so,{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(ui,{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:()=>F&&_(v-1),disabled:!F,title:"Previous file","aria-label":"Previous file",children:t.jsx(_l,{})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:v!==null?`${v+1}/${l.length}`:`—/${l.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>U&&_(v+1),disabled:!U,title:"Next file","aria-label":"Next file",children:t.jsx(Un,{})})]}),t.jsx("button",{className:`btn btn-sm ${k?"btn-primary":""}`,onClick:()=>S(A=>!A),title:k?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(cl,{size:14})})]}),t.jsxs("div",{className:"changes-header-actions-secondary",children:[t.jsx("button",{className:"btn btn-sm",onClick:D,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($l,{})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map(A=>{const $=g.has(A.path);return t.jsxs("div",{className:`changes-file-item ${$?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>C(A.path),children:[t.jsx("span",{className:"changes-file-toggle",children:$?t.jsx(un,{size:14}):t.jsx(Un,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${A.status}`,title:A.status,children:_b(A.status)}),t.jsx("span",{className:"changes-file-path",title:A.path,children:t.jsx("bdo",{dir:"ltr",children:A.path})}),t.jsxs("span",{className:"changes-file-stat",title:`+${A.additions} -${A.deletions}`,children:["+",A.additions," -",A.deletions]})]}),$&&A.patch&&t.jsx("div",{className:"changes-file-content",children:t.jsx("pre",{className:`changes-diff-patch ${k?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:Eb(A.patch)})})})]},A.path)})}),t.jsx(FP,{isOpen:j,taskId:e,files:l,stats:d,mergeDetails:r,column:a,onClose:()=>E(!1),onRefresh:D})]})}function Uh(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function UP(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function ez(e,n){const s=UP(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 BP(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}const Bh=["image/png","image/jpeg","image/gif","image/webp"];function HP(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 Mb({mode:e,description:n,onDescriptionChange:s,title:a,onTitleChange:r,dependencies:o,onDependenciesChange:l,nodeId:c,onNodeIdChange:d,nodeOptions:u,nodeOverrideDisabled:m=!1,nodeOverrideDisabledReason:h,priority:f,onPriorityChange:p,executorModel:g,onExecutorModelChange:x,validatorModel:v,onValidatorModelChange:b,planningModel:k,onPlanningModelChange:S,thinkingLevel:j,onThinkingLevelChange:E,presetMode:y,onPresetModeChange:N,selectedPresetId:M,onSelectedPresetIdChange:D,selectedWorkflowSteps:C,onWorkflowStepsChange:_,onDefaultOnApplied:F,pendingImages:U,onImagesChange:A,tasks:$,projectId:T,disabled:J=!1,addToast:B,isActive:se=!0,onAutoSaveDescription:P,onPlanningMode:O,onSubtaskBreakdown:I,onClose:w,renderBelowPrimary:Y,renderBelowModelConfiguration:re,hideDependencies:le,autoExpandMoreOptionsOnSelection:ve=!0,reviewLevel:de,onReviewLevelChange:Fe,executionMode:X,onExecutionModeChange:L}){const Q=(le?!1:o.length>0)||U.length>0||C.length>0||y!=="default"||(f??Ds)!==Ds||g!==""||v!==""||(k||"")!==""||(j||"")!==""||de!==void 0||X==="fast"||(c||"")!=="",[ne,H]=i.useState(!1),[z,W]=i.useState(ve?Q:!1),[we,Z]=i.useState(""),[fe,Oe]=i.useState([]),[Ve,He]=i.useState([]),[Je,$e]=i.useState([]),[he,ue]=i.useState(!1),[Ee,je]=i.useState(null),[xe,Pe]=i.useState([]),[ie,Me]=i.useState("idle"),[We,mt]=i.useState(!1),[st,Ze]=i.useState(!1),[dt,Ae]=i.useState(!1),Ue=i.useRef(null),kt=i.useRef(null),De=i.useRef(null),be=i.useRef(null),pe=i.useRef(null),Re=i.useRef(null),Be=i.useRef(null),at=i.useRef(!1),me=i.useRef(Q),ft=i.useRef(n.trim()),Et=i.useRef(n.trim());i.useEffect(()=>{se&&(ue(!0),Os().then(ee=>{Oe(ee.models),He(ee.favoriteProviders),$e(ee.favoriteModels)}).catch(()=>{}).finally(()=>ue(!1)),Ll(T).then(ee=>je(ee)).catch(()=>je(null)),lo(T).then(ee=>Pe(ee.filter(Ie=>Ie.enabled))).catch(()=>Pe([])))},[se,T]);const jt=Ee?.modelPresets||[],$t=jt.find(ee=>ee.id===M),Ft=(le?!1:o.length>0)||U.length>0||C.length>0||y!=="default"||(f??Ds)!==Ds||g!==""||v!==""||(k||"")!==""||(j||"")!==""||de!==void 0||X==="fast"||(c||"")!=="";i.useEffect(()=>{if(e!=="create"||!se||!Ee?.autoSelectModelPreset)return;const ee=(Ee.defaultPresetBySize,void 0);if(ee){const Ie=Uh(ee);D(ee.id),N("preset"),x(Ie.executorValue),b(Ie.validatorValue)}},[se,Ee,jt,e]);const Rt=i.useRef(!1);i.useEffect(()=>{if(e!=="create"||!se||Rt.current||xe.length===0)return;const ee=xe.filter(St=>St.defaultOn);if(ee.length===0)return;Rt.current=!0;const Ie=ee.map(St=>St.id);_(Ie),F?.(Ie)},[e,se,xe]),i.useEffect(()=>{se||(Rt.current=!1)},[se]),i.useEffect(()=>{if(!ve){me.current=Ft;return}Ft&&!me.current&&W(!0),me.current=Ft},[Ft,ve]),i.useEffect(()=>{z||(H(!1),Z(""))},[z]),i.useEffect(()=>{e!=="edit"||!se||be.current&&(be.current.focus(),be.current.select())},[e,se]),i.useEffect(()=>{if(!ne)return;const ee=Ie=>{kt.current&&!kt.current.contains(Ie.target)&&H(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[ne]),i.useEffect(()=>{(e!=="edit"||J)&&Ae(!1)},[e,J]),i.useEffect(()=>{if(e!=="edit"){Me("idle");return}const ee=n.trim();ft.current=ee,Et.current=ee,Me("idle")},[e]),i.useEffect(()=>{if(e!=="edit"||!P||!se)return;const ee=n.trim(),Ie=ft.current;if(ee===Ie||ee===Et.current){Re.current&&(clearTimeout(Re.current),Re.current=null),at.current||Me("idle");return}return Re.current&&clearTimeout(Re.current),Re.current=setTimeout(async()=>{if(!at.current){at.current=!0,Me("saving");try{await P(ee),Et.current=ee,Me("saved"),Be.current&&clearTimeout(Be.current),Be.current=setTimeout(()=>{Me("idle"),Be.current=null},2e3)}catch{Me("idle")}finally{at.current=!1,Re.current=null}}},1500),()=>{Re.current&&(clearTimeout(Re.current),Re.current=null)}},[e,n,P,se]),i.useEffect(()=>()=>{Re.current&&clearTimeout(Re.current),Be.current&&clearTimeout(Be.current)},[]),i.useEffect(()=>{if(!We)return;const ee=Ie=>{Ue.current&&!Ue.current.contains(Ie.target)&&mt(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[We]);const It=i.useCallback(ee=>{const Ie=ee.clipboardData?.items;if(Ie)for(let St=0;St<Ie.length;St++){const pt=Ie[St];if(pt.type.startsWith("image/")){const Dt=pt.getAsFile();if(Dt&&Bh.includes(Dt.type)){ee.preventDefault(),A([...U,{file:Dt,previewUrl:URL.createObjectURL(Dt)}]);return}}}},[U,A]),Vt=i.useCallback(ee=>{ee.preventDefault();const Ie=ee.dataTransfer.files;for(let St=0;St<Ie.length;St++){const pt=Ie[St];if(Bh.includes(pt.type)){A([...U,{file:pt,previewUrl:URL.createObjectURL(pt)}]);return}}},[U,A]),Qt=i.useCallback(ee=>{const Ie=U[ee];Ie&&URL.revokeObjectURL(Ie.previewUrl),A(U.filter((St,pt)=>pt!==ee))},[U,A]),Jt=i.useCallback(ee=>{l(o.includes(ee)?o.filter(Ie=>Ie!==ee):[...o,ee])},[o,l]),on=(ee,Ie)=>ee.length>Ie?ee.slice(0,Ie)+"…":ee,Kt=i.useCallback(ee=>{s(ee.target.value);const Ie=ee.target;Ie.style.height="auto",Ie.style.height=Ie.scrollHeight+"px"},[s]),qt=i.useCallback(()=>{Ae(ee=>!ee)},[]),kn=i.useCallback(ee=>{!dt||ee.key!=="Escape"||(ee.preventDefault(),ee.stopPropagation(),Ae(!1))},[dt]),nn=i.useCallback(async ee=>{const Ie=n.trim();if(!(!Ie||st)){Ze(!0);try{const St=await Of(Ie,ee,T);s(St),mt(!1),B("Description refined with AI","success"),De.current&&(De.current.style.height="auto",De.current.style.height=De.current.scrollHeight+"px")}catch(St){const pt=Ff(St);B(pt,"error")}finally{Ze(!1)}}},[n,st,B,s,T]),Xt=i.useCallback(async ee=>{const Ie=Ve,pt=Ie.includes(ee)?Ie.filter(Dt=>Dt!==ee):[ee,...Ie];He(pt);try{await Dn({favoriteProviders:pt,favoriteModels:Je})}catch{He(Ie)}},[Ve,Je]),Gt=i.useCallback(async ee=>{const Ie=Je,pt=Ie.includes(ee)?Ie.filter(Dt=>Dt!==ee):[ee,...Ie];$e(pt);try{await Dn({favoriteProviders:Ve,favoriteModels:pt})}catch{$e(Ie)}},[Je,Ve]),ln=i.useCallback(ee=>{if(ee<=0)return;const Ie=[...C];[Ie[ee-1],Ie[ee]]=[Ie[ee],Ie[ee-1]],_(Ie)},[C,_]),ye=i.useCallback(ee=>{if(ee>=C.length-1)return;const Ie=[...C];[Ie[ee],Ie[ee+1]]=[Ie[ee+1],Ie[ee]],_(Ie)},[C,_]),Le=i.useCallback(ee=>{_(C.filter(Ie=>Ie!==ee))},[C,_]),ae=new Map;for(const ee of xe)ae.set(ee.id,{name:ee.name,description:ee.description});const Te=$.filter(ee=>!o.includes(ee.id)).sort((ee,Ie)=>{const St=Ie.createdAt.localeCompare(ee.createdAt);if(St!==0)return St;const pt=parseInt(ee.id.slice(ee.id.lastIndexOf("-")+1),10)||0;return(parseInt(Ie.id.slice(Ie.id.lastIndexOf("-")+1),10)||0)-pt}),Ne=we?Te.filter(ee=>ee.id.toLowerCase().includes(we.toLowerCase())||ee.title&&ee.title.toLowerCase().includes(we.toLowerCase())||ee.description&&ee.description.toLowerCase().includes(we.toLowerCase())):Te;return t.jsxs("div",{className:"task-form",onDrop:Vt,onDragOver:ee=>ee.preventDefault(),onPaste:It,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:be,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:a||"",onChange:ee=>r(ee.target.value),disabled:J})]}),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${dt?" description--fullscreen":""}`,ref:Ue,onKeyDown:kn,children:[dt&&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:qt,"aria-label":"Collapse description",title:"Collapse description",children:t.jsx(io,{size:14})})]}),t.jsx("textarea",{ref:De,autoFocus:e==="create",id:"task-form-description",value:n,onChange:Kt,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:J||st}),(()=>{const ee=!!n.trim()&&!J;return t.jsxs(t.Fragment,{children:[!dt&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${ee?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:qt,"aria-label":"Expand description",title:"Expand description",children:t.jsx($l,{size:14})}),ee&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${st?"refine-button--loading":""}`,onClick:()=>mt(Ie=>!Ie),disabled:st,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(ys,{size:12,style:{verticalAlign:"middle"}}),st?"Refining...":"Refine"]})]})})(),We&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:ee=>ee.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>nn("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:()=>nn("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:()=>nn("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:()=>nn("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"&&(O||I)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[O&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const ee=n.trim();if(!ee){B("Enter a description first","error");return}w?.(),O(ee)},disabled:J||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),I&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const ee=n.trim();if(!ee){B("Enter a description first","error");return}w?.(),I(ee)},disabled:J||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),Y,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>W(ee=>!ee),"aria-expanded":z,"aria-controls":"task-form-more-options",disabled:J,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),z?t.jsx(pi,{size:14}):t.jsx(un,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${z?"":" collapsed"}`,"aria-hidden":!z,hidden:!z,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Attachments"}),U.length>0&&t.jsx("div",{className:"inline-create-previews",children:U.map((ee,Ie)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:ee.previewUrl,alt:ee.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>Qt(Ie),disabled:J,title:"Remove image",children:"×"})]},ee.previewUrl))}),t.jsx("input",{ref:pe,type:"file",accept:"image/*",onChange:ee=>{const Ie=ee.target.files?.[0];Ie&&(A([...U,{file:Ie,previewUrl:URL.createObjectURL(Ie)}]),ee.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>pe.current?.click(),disabled:J,children:"Attach Screenshot"}),t.jsx("small",{children:"You can also paste images or drag & drop"})]}),d&&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:c??"",onChange:ee=>d(ee.target.value||void 0),disabled:J||m,children:[t.jsx("option",{value:"",children:"Use project default / local"}),(u??[]).map(ee=>t.jsxs("option",{value:ee.id,children:[ee.name," (",BP(ee.status),")"]},ee.id))]}),(()=>{const ee=(u??[]).find(Ie=>Ie.id===c);return ee?t.jsx("div",{className:"task-form-node-status",children:t.jsx(ua,{status:ee.status,showLabel:!0})}):null})(),t.jsx("small",{children:h??"Task override takes priority over project default node routing."})]}),!le&&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:kt,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>H(ee=>!ee),disabled:J,children:o.length>0?`${o.length} selected`:"Add dependencies"}),ne&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:we,onChange:ee=>Z(ee.target.value),onClick:ee=>ee.stopPropagation()}),Ne.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Ne.map(ee=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(ee.id)?" selected":""}`,onClick:()=>Jt(ee.id),onMouseDown:Ie=>Ie.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:ee.id}),t.jsx("span",{className:"dep-dropdown-title",children:on(ee.title||ee.description||ee.id,30)})]},ee.id))]})]}),o.length>0&&t.jsx("div",{className:"selected-deps",children:o.map(ee=>t.jsxs("span",{className:"dep-chip",children:[ee,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>Jt(ee),disabled:J,children:"×"})]},ee))})]})}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Model Configuration"}),p&&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:f??Ds,onChange:ee=>p(ee.target.value),disabled:J,children:mo.map(ee=>t.jsx("option",{value:ee,children:ee[0].toUpperCase()+ee.slice(1)},ee))})]}),L&&X!==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:X,onChange:ee=>L(ee.target.value),disabled:J,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),he?t.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):fe.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:y==="preset"?M:y,onChange:ee=>{const Ie=ee.target.value;if(Ie==="default"){N("default"),D(""),x(""),b("");return}if(Ie==="custom"){N("custom"),D("");return}const St=jt.find(Dt=>Dt.id===Ie),pt=Uh(St);N("preset"),D(Ie),x(pt.executorValue),b(pt.validatorValue)},disabled:J,children:[t.jsx("option",{value:"default",children:"Use default"}),jt.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,jt.map(ee=>t.jsx("option",{value:ee.id,children:ee.name},ee.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),y==="preset"&&$t?t.jsxs("small",{children:["Using preset: ",$t.name]}):null,y==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>N("custom"),disabled:J,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:g,onChange:ee=>{N("custom"),D(""),x(ee)},models:fe,disabled:J||y==="preset",favoriteProviders:Ve,onToggleFavorite:Xt,favoriteModels:Je,onToggleModelFavorite:Gt})]}),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:v,onChange:ee=>{N("custom"),D(""),b(ee)},models:fe,disabled:J||y==="preset",favoriteProviders:Ve,onToggleFavorite:Xt,favoriteModels:Je,onToggleModelFavorite:Gt})]}),S&&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:k||"",onChange:ee=>{N("custom"),D(""),S(ee)},models:fe,disabled:J||y==="preset",favoriteProviders:Ve,onToggleFavorite:Xt,favoriteModels:Je,onToggleModelFavorite:Gt})]}),E&&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:j||"",onChange:ee=>E(ee.target.value),disabled:J||y==="preset",children:[t.jsxs("option",{value:"",children:["Default (",Ee?.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"})]})]}),Fe&&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:de??"",onChange:ee=>Fe(ee.target.value===""?void 0:parseInt(ee.target.value,10)),disabled:J,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"})]})]})]})]}),re,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:xe.length>0&&xe.map(ee=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${ee.id}`,children:[t.jsx("input",{type:"checkbox",checked:C.includes(ee.id),onChange:Ie=>{_(Ie.target.checked?[...C,ee.id]:C.filter(St=>St!==ee.id))},disabled:J}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[ee.name,HP(ee.phase||"pre-merge",ee.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:ee.description})]})]},ee.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((ee,Ie)=>{const St=ae.get(ee);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${ee}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:Ie+1}),t.jsx("span",{className:"workflow-step-order-name",children:St?.name||ee}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>ln(Ie),disabled:J||Ie===0,"data-testid":`workflow-step-move-up-${ee}`,title:"Move up",children:t.jsx(pi,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>ye(Ie),disabled:J||Ie===C.length-1,"data-testid":`workflow-step-move-down-${ee}`,title:"Move down",children:t.jsx(un,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Le(ee),disabled:J,"data-testid":`workflow-step-remove-${ee}`,title:"Remove",children:t.jsx(en,{})})]})]},ee)})]})]})]})]})}const Hh={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 qP(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function VP(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 WP(e){return e?new Date(e).toLocaleString():null}function KP(e){const n=e.split(`
686
- `);return n.length<=1?e:`${n.length} lines`}function $o(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 GP({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 JP({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([]),[v,b]=i.useState(!1),k=n.some(w=>w.status==="pending"),{entries:S}=Nb(e,!!l&&k,o);i.useEffect(()=>{let w=!1;return lo(o).then(Y=>{w||x(Y.filter(re=>re.enabled))}).catch(()=>{w||x([])}),()=>{w=!0}},[o]);const j=a??[],E=i.useMemo(()=>g.map(w=>({id:w.id,name:w.name,description:w.description,phase:w.phase||"pre-merge"})),[g]),y=i.useMemo(()=>new Map(E.map(w=>[w.id,w])),[E]),N=w=>{u(Y=>({...Y,[w]:!Y[w]}))},M=w=>{h(Y=>{const re=Y[w]??"markdown";return{...Y,[w]:re==="markdown"?"plain":"markdown"}})},D=w=>{p(w)},C=()=>{p(null)};i.useEffect(()=>{if(!f)return;const w=Y=>{Y.key==="Escape"&&C()};return document.addEventListener("keydown",w),()=>{document.removeEventListener("keydown",w)}},[f]);const _=i.useCallback((w,Y)=>{if(c){if(Y){if(j.includes(w)){c(j);return}c([...j,w]);return}c(j.filter(re=>re!==w))}},[c,j]),F=i.useCallback(w=>{if(!c||w<=0)return;const Y=[...j];[Y[w-1],Y[w]]=[Y[w],Y[w-1]],c(Y)},[c,j]),U=i.useCallback(w=>{if(!c||w>=j.length-1)return;const Y=[...j];[Y[w],Y[w+1]]=[Y[w+1],Y[w]],c(Y)},[c,j]),A=i.useCallback(w=>{c&&c(j.filter(Y=>Y!==w))},[c,j]),$=n.length>0,T=j.length>0;i.useEffect(()=>{r||b(!1)},[r]);const J=i.useMemo(()=>j.map(w=>{const Y=y.get(w);return{id:w,name:Y?.name||w,description:Y?.description||"Step definition not found.",phase:Y?.phase||"pre-merge"}}),[j,y]),B=()=>!r||!v||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(w=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${w.id}`,children:[t.jsx("input",{type:"checkbox",checked:j.includes(w.id),onChange:Y=>_(w.id,Y.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[w.name,$o(w.phase,w.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:w.description})]})]},w.id))})]}),j.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),j.map((w,Y)=>{const re=y.get(w);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${w}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:Y+1}),t.jsx("span",{className:"workflow-step-order-name",children:re?.name||w}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>F(Y),disabled:Y===0,"data-testid":`workflow-step-move-up-${w}`,title:"Move up",children:t.jsx(pi,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>U(Y),disabled:Y===j.length-1,"data-testid":`workflow-step-move-down-${w}`,title:"Move down",children:t.jsx(un,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>A(w),"data-testid":`workflow-step-remove-${w}`,title:"Remove",children:t.jsx(en,{})})]})]},w)})]})]}),se=()=>{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 w=n.filter(de=>de.status==="passed").length,Y=n.filter(de=>de.status==="failed").length,re=n.filter(de=>de.status==="skipped").length,le=n.filter(de=>de.status==="pending").length,ve=[`${n.length} step${n.length!==1?"s":""}`];return w>0&&ve.push(`${w} passed`),Y>0&&ve.push(`${Y} failed`),re>0&&ve.push(`${re} skipped`),le>0&&ve.push(`${le} 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:ve.join(" · ")}),n.map((de,Fe)=>{const X=de.phase||"pre-merge",L=d[de.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${de.status}`,"data-testid":`workflow-result-item-${de.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[de.workflowStepName,$o(X,de.workflowStepId,"workflow-result-phase")]}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${de.status}`,"data-testid":`workflow-result-badge-${de.workflowStepId}`,children:qP(de.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[de.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",WP(de.startedAt)]}),de.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:VP(de.startedAt,de.completedAt)})]}),de.status==="pending"&&de.startedAt?t.jsx(GP,{entries:S,startedAt:de.startedAt,stepId:de.workflowStepId}):de.output?t.jsxs("div",{className:"workflow-result-output-section",children:[t.jsxs("div",{className:"workflow-result-output-header",children:[t.jsx("span",{className:"workflow-result-output-label",children:"Output:"}),t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-toggle",onClick:()=>N(de.workflowStepId),"data-testid":`workflow-result-toggle-${de.workflowStepId}`,children:L?"Hide output":"Show output"}),!L&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${de.workflowStepId}`,children:KP(de.output)}),L&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-mode-toggle",onClick:()=>M(de.workflowStepId),"data-testid":`workflow-result-mode-toggle-${de.workflowStepId}`,title:(m[de.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(m[de.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm workflow-result-expand-toggle",onClick:()=>D(de.workflowStepId),"data-testid":`workflow-result-expand-${de.workflowStepId}`,title:"Expand output",children:t.jsx($l,{size:12})})]})]}),L&&t.jsx("div",{className:`workflow-result-output${(m[de.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${de.workflowStepId}`,children:(m[de.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(Ci,{remarkPlugins:[Ei],components:Hh,children:de.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:de.output})})]}):null]},`${de.workflowStepId}-${Fe}`)})]})},P=r?t.jsx("button",{type:"button",className:"modal-edit-btn workflow-results-edit-toggle",onClick:()=>b(w=>!w),"data-testid":"workflow-steps-edit-toggle","aria-label":v?"Done editing workflow steps":"Edit workflow steps",title:v?"Done":"Edit",children:v?t.jsxs(t.Fragment,{children:[t.jsx(ts,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(Cs,{size:14}),"Edit"]})}):null,O=!s&&!$&&T,I=r&&$;return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[O?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:[J.length," step",J.length===1?"":"s"]})]}),P]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:J.map(w=>t.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${w.id}`,children:[t.jsxs("div",{className:"workflow-configured-name",children:[w.name,$o(w.phase,w.id,"workflow-configured-phase")]}),t.jsx("p",{className:"workflow-configured-description",children:w.description})]},w.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."}),B()]}):t.jsxs(t.Fragment,{children:[I&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:"Workflow Steps"}),P]}),se(),B()]}),f&&(()=>{const w=n.find(le=>le.workflowStepId===f);if(!w)return null;const Y=m[w.workflowStepId]??"markdown",re=w.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:le=>{le.target===le.currentTarget&&C()},"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:w.workflowStepName}),$o(re,w.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:()=>M(w.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:Y==="markdown"?"Switch to plain text":"Switch to markdown",children:Y==="markdown"?"Markdown":"Plain"}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm workflow-output-modal-close",onClick:C,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:t.jsx(en,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${Y==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:Y==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(Ci,{remarkPlugins:[Ei],components:Hh,children:w.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:w.output})})})]})})})()]})}function YP(e){return e==="block"?"Block execution":e==="fallback-local"?"Fall back to local":"Not configured"}const QP=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function XP(e){return e!==void 0&&e!=="online"}function ZP({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),pl().then(C=>{o(C)}).catch(C=>{u(_e(C)||"Failed to load nodes")}).finally(()=>{c(!1)})},[]);const x=i.useMemo(()=>new Map(r.map(C=>[C.id,C])),[r]),v=i.useMemo(()=>[...r].sort((C,_)=>C.name.localeCompare(_.name)),[r]),b=n,k=e.nodeId??b?.defaultNodeId??null,S=e.nodeId?"Per-task override":b?.defaultNodeId?"Project default":"No routing",j=k?x.get(k):void 0,E=j?`${j.name} (${j.type})`:k?`${k} (node unavailable or unknown)`:"Local (no routing configured)",y=e.column==="in-progress"||QP.has(e.status),N=y||f||l,M=i.useCallback(async C=>{if(C===m)return;const _=e.id,F=m;h(C),p(!0);try{const U=await ki(_,{nodeId:C||null});if(g.current!==_)return;h(U.nodeId??""),a?.(U),s(C?"Node override updated":"Node override cleared","success")}catch(U){if(g.current!==_)return;h(F),s(_e(U)||"Failed to update node override","error")}finally{g.current===_&&p(!1)}},[s,a,m,e.id]),D=i.useCallback(()=>{M("")},[M]);return t.jsxs("div",{className:"routing-tab",children:[t.jsx("h4",{children:"Task Routing"}),t.jsx("p",{className:"routing-tab__intro",children:"View the effective execution node and control per-task node override."}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Routing Summary"}),t.jsxs("div",{className:"routing-summary-grid",role:"list",children:[t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Effective node"}),t.jsxs("span",{className:"routing-summary-value",children:[j?t.jsx(ua,{status:j.status,compact:!0}):null,E,XP(j?.status)?t.jsx("span",{className:"routing-summary-warning",children:"Unhealthy"}):null]})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Routing source"}),t.jsx("span",{className:"routing-summary-value",children:S})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Unavailable-node policy"}),t.jsx("span",{className:"routing-summary-value",children:YP(b?.unavailableNodePolicy)})]})]}),y&&k?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:N,onChange:C=>{M(C.target.value)},children:[t.jsx("option",{value:"",children:"Use project default"}),v.map(C=>t.jsxs("option",{value:C.id,title:`Status: ${C.status}`,children:[C.name," (",C.type,") — ",C.status]},C.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:D,children:"Clear override"})]}):null]})]})}const eR=/^[a-zA-Z0-9_-]{1,64}$/,tR=200;function qh(e){return e?new Date(e).toLocaleString():""}function nR(e,n=tR){return e.length<=n?e:e.substring(0,n)+"…"}function sR({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,v]=i.useState(""),[b,k]=i.useState(null),[S,j]=i.useState([]),[E,y]=i.useState(!1),[N,M]=i.useState(!1),[D,C]=i.useState(""),[_,F]=i.useState(""),[U,A]=i.useState(!1),[$,T]=i.useState(null),[J,B]=i.useState(null),[se,P]=i.useState(!1),O=i.useCallback(async()=>{try{const X=await tk(e,a);l(X)}catch(X){n(_e(X)||"Failed to load documents","error")}finally{d(!1)}},[e,a,n]);i.useEffect(()=>{O()},[O]);async function I(X){u===X.key?(m(null),f(""),g(null),v(""),k(null),j([]),P(!1)):(m(X.key),f(X.content),g(null),v(""),k(null),j([]),P(!1))}async function w(X){if(b===X)k(null),j([]);else{k(X),y(!0);try{const L=await nk(e,X,a);j(L)}catch(L){n(_e(L)||"Failed to load revisions","error")}finally{y(!1)}}}function Y(){u&&(g(u),v(h))}function re(){g(null),v("")}async function le(){if(!(!p||!x.trim())){A(!0);try{await Bu(e,p,x,{},a),g(null),v(""),await O();const X=o.find(L=>L.key===p);X&&f(X.content),n("Document saved","success")}catch(X){n(_e(X)||"Failed to save document","error")}finally{A(!1)}}}async function ve(){const X=D.trim(),L=_.trim();if(!X){n("Document key is required","error");return}if(!eR.test(X)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!L){n("Content is required","error");return}A(!0);try{await Bu(e,X,L,{},a),M(!1),C(""),F(""),await O(),n("Document created","success")}catch(Q){n(_e(Q)||"Failed to create document","error")}finally{A(!1)}}async function de(X){T(X);try{await sk(e,X,a),B(null),T(null),u===X&&(m(null),f("")),b===X&&(k(null),j([])),await O(),n("Document deleted","success")}catch(L){n(_e(L)||"Failed to delete document","error")}finally{T(null)}}function Fe(X){f(X.content),g(null),v("")}return c?t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),t.jsx("div",{className:"detail-log-empty",children:"Loading documents…"})]}):t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),N&&t.jsxs("div",{className:"task-document-create-form",children:[t.jsx("h5",{children:"New Document"}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-key",children:"Key"}),t.jsx("input",{id:"doc-key",type:"text",className:"task-document-key-input",value:D,onChange:X=>C(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:_,onChange:X=>F(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:()=>{M(!1),C(""),F("")},disabled:U,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void ve(),disabled:U||!D.trim()||!_.trim(),children:U?"Creating…":"Create"})]})]}),o.length===0&&!N?t.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):t.jsx("div",{className:"task-documents-list",children:o.map(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(Ki,{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:qh(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:()=>P(L=>!L),"aria-label":se?"Switch to plain text":"Switch to markdown","aria-pressed":se,title:se?"Switch to plain text":"Switch to markdown",children:se?"Markdown":"Plain"})}),t.jsx("div",{className:"task-document-content",children:se?t.jsx("div",{className:"task-document-content-markdown",children:t.jsx("div",{className:"markdown-body",children:t.jsx(Ci,{remarkPlugins:[Ei],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…"}):S.length<=1?t.jsx("div",{className:"detail-log-empty",children:"No previous revisions."}):t.jsx("div",{className:"task-document-revision-list",children:S.filter(L=>L.revision<X.revision).sort((L,Q)=>Q.revision-L.revision).map(L=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>Fe(L),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",L.revision]}),t.jsx("span",{className:"revision-author",children:L.author}),t.jsx("span",{className:"revision-timestamp",children:qh(L.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:nR(L.content,100)})]},L.id))})]})]}),p===X.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:x,onChange:L=>v(L.target.value),rows:10,disabled:U}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:re,disabled:U,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void le(),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 I(X),children:u===X.key?t.jsxs(t.Fragment,{children:[t.jsx(pi,{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 w(X.key),children:[t.jsx(Vr,{size:14})," History"]}),r&&p!==X.key&&t.jsx("button",{className:"btn btn-sm",onClick:Y,children:"Edit"}),r&&(J===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 de(X.key),disabled:$===X.key,children:$===X.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>B(null),disabled:$===X.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>B(X.key),children:t.jsx(Sn,{size:14})}))]})]})]},X.key))}),r&&!N&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>M(!0),children:[t.jsx(Cn,{size:14})," New Document"]})]})}function Do(e){return e.toLocaleString()}function Oc(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 iR(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=s.reduce((o,l)=>o+l.durationMs,0),r=s.reduce((o,l)=>!o||l.durationMs>o.durationMs?l:o,void 0);return{timedStepCount:s.length,totalDurationMs:a,longestStep:r}}function aR({tokenUsage:e,loading:n,task:s}){const a=lg(s?.log??[]),r=a.filter(m=>typeof m.durationMs=="number"),o=r.reduce((m,h)=>m+(h.durationMs??0),0),l=Math.max(o,s?.timedExecutionMs??0),c=r.reduce((m,h)=>!m||(h.durationMs??0)>(m.durationMs??0)?h:m,void 0),d=iR(s?.workflowStepResults??[]),u=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:a.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(l)})]}),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:d.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(d.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(l+d.totalDurationMs)})]})]}),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:c?.durationMs?`${c.summary} (${wr(c.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:d.longestStep?`${d.longestStep.name} (${wr(d.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:u>0?`${Math.min((s?.currentStep??0)+1,u)} / ${u}`:"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 ${Oc(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:Do(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:Do(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:Do(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:Do(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:Oc(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:Oc(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}const rR=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function oR(e,n){return eg(e,n)}function lR(e,n){return tg(e,n)}function cR(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 dR(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const a=cR(n);return a||ng(e,s)}function uR(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 mR(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 hR(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function pR(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}function Vh(e,n){return e.length>n?e.slice(0,n)+"…":e}function Wh(e=[],n=[]){return e.length===n.length&&e.every((s,a)=>s===n[a])}function Fc(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function zc(e){return e.trim()}function fR(e){const n=e.trim();return n.length>0?n:void 0}function Ti(e){return typeof e=="string"&&mo.includes(e)?e:Ds}function kr(e){return e==="fast"?"fast":"standard"}function gR(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function bR(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 xR=i.lazy(()=>Rn(()=>import("./AgentDetailView-BKKpbp1S.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(e=>({default:e.AgentDetailView})));function vR(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:gR(e.sourceMetadata)};case"research":return{label:"Research",contextInfo:bR(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 Uc=200,yR=new Set(["triage","todo"]);function Ab({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:v}){const[b,k]=i.useState(p),[S,j]=i.useState(()=>"prompt"in e?e:null),[E,y]=i.useState(()=>!("prompt"in e));i.useEffect(()=>{if("prompt"in e){j(e),y(!1);return}let te=!1;return y(!0),j(null),Wa(e.id,n).then(ze=>{te||(j(ze),y(!1))}).catch(()=>{te||y(!1)}),()=>{te=!0}},[e.id,n]);const N=S?{...S,...e,prompt:S.prompt,log:S.log}:{...e,prompt:""},M=e.status==="failed"||e.status==="stuck-killed"||e.status==="planning"||e.status==="needs-replan"||(e.stuckKillCount??0)>0||(e.recoveryRetryCount??0)>0||!!e.nextRecoveryAt,[D,C]=i.useState(null),[_,F]=i.useState(null),U=vR(N,{sourceAgentName:D?.name});i.useEffect(()=>{k(p)},[p]),i.useEffect(()=>{J(!1)},[e.id]);const[A,$]=i.useState("activity"),[T,J]=i.useState(!1),[B,se]=i.useState(e.attachments||[]),[P,O]=i.useState(!1),[I,w]=i.useState(e.dependencies||[]),[Y,re]=i.useState(!1),[le,ve]=i.useState(""),[de,Fe]=i.useState(null),[X,L]=i.useState([]),[Q,ne]=i.useState(!1),[H,z]=i.useState(!1),[W,we]=i.useState(!1),[Z,fe]=i.useState(!1),[Oe,Ve]=i.useState(!1),[He,Je]=i.useState(N.prompt||""),[$e,he]=i.useState(""),[ue,Ee]=i.useState(!1),[je,xe]=i.useState(""),[Pe,ie]=i.useState(!1),[Me,We]=i.useState(!1),[mt,st]=i.useState(e.title||""),[Ze,dt]=i.useState(e.description||""),[Ae,Ue]=i.useState(e.dependencies||[]),[kt,De]=i.useState(""),[be,pe]=i.useState(""),[Re,Be]=i.useState(""),[at,me]=i.useState(""),[ft,Et]=i.useState("default"),[jt,$t]=i.useState(void 0),[Ft,Rt]=i.useState(Ds),[It,Vt]=i.useState(e.nodeId),[Qt,Jt]=i.useState(kr(e.executionMode)),[on,Kt]=i.useState(""),[qt,kn]=i.useState(e.enabledWorkflowSteps||[]),[nn,Xt]=i.useState(e.sourceIssue?.provider??""),[Gt,ln]=i.useState(e.sourceIssue?.repository??""),[ye,Le]=i.useState(e.sourceIssue?.externalIssueId??""),[ae,Te]=i.useState(e.sourceIssue?.url??""),[Ne,ee]=i.useState([]),[Ie,St]=i.useState(!1),[pt,Dt]=i.useState(Ti(e.priority)),[Ut,Ce]=i.useState(!1),et=i.useRef(!1),[tt,Lt]=i.useState(!1),[Zt,sn]=i.useState(!1),[At,cn]=i.useState(!1),Tn=i.useRef(null),En=i.useRef(null),bn=i.useRef(null),{getSlotsForId:In}=Gf(n),ut=In("task-detail-tab").map((te,ze)=>({entry:te,tabId:`plugin-${te.pluginId}-${ze}`})),xn=typeof b=="string"&&b.startsWith("plugin-")?ut.find(te=>te.tabId===b)??null:null;i.useEffect(()=>(et.current=!0,()=>{et.current=!1}),[]);const[oe,ct]=i.useState(void 0),[rt,wt]=i.useState([]),[ot,vt]=i.useState(!1),[Wt,an]=i.useState(e.enabledWorkflowSteps||[]),pn=e.column==="in-progress"||rR.has(e.status);i.useEffect(()=>{st(e.title||""),dt(e.description||""),Xt(e.sourceIssue?.provider??""),ln(e.sourceIssue?.repository??""),Le(e.sourceIssue?.externalIssueId??""),Te(e.sourceIssue?.url??""),Jt(kr(e.executionMode)),cn(!1),We(!1)},[e.id,e.title,e.description,e.sourceIssue,e.executionMode]),i.useEffect(()=>{an(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),i.useEffect(()=>{Dt(Ti(e.priority))},[e.id,e.priority]),i.useEffect(()=>{let te=!1;return Ll(n).then(ze=>{te||ct(ze)}).catch(()=>{}),()=>{te=!0}},[n]),i.useEffect(()=>{if(b!=="workflow")return;let te=!1;return vt(!0),Fj(e.id,n).then(ze=>{te||wt(ze)}).catch(ze=>{te||h(`Failed to load workflow results: ${_e(ze)}`,"error")}).finally(()=>{te||vt(!1)}),()=>{te=!0}},[b,e.id,n,h]),i.useEffect(()=>{if(b!=="workflow")return;const te=n?`?projectId=${encodeURIComponent(n)}`:"",ze=yt=>{try{const Bt=JSON.parse(yt.data);Bt.id===e.id&&Array.isArray(Bt.workflowStepResults)&&wt(Bt.workflowStepResults)}catch{}};return gi(`/api/events${te}`,{events:{"task:updated":ze}})},[b,e.id,n]),i.useEffect(()=>{Y||ve("")},[Y]),i.useEffect(()=>{if(!e.assignedAgentId){Fe(null);return}const te=X.find(yt=>yt.id===e.assignedAgentId);if(te){Fe(te);return}let ze=!1;return kd(e.assignedAgentId,n).then(yt=>{ze||Fe(yt)}).catch(()=>{ze||Fe(null)}),()=>{ze=!0}},[e.assignedAgentId,n,X]),i.useEffect(()=>{if(!e.sourceAgentId){C(null);return}const te=X.find(yt=>yt.id===e.sourceAgentId);if(te){C(te);return}let ze=!1;return Promise.resolve(kd(e.sourceAgentId,n)).then(yt=>{ze||C(yt??null)}).catch(()=>{ze||C(null)}),()=>{ze=!0}},[e.sourceAgentId,n,X]),i.useEffect(()=>{ne(!1)},[e.id]),i.useEffect(()=>{if(!(tt||Zt))return;const ze=yt=>{const Bt=yt.target,Yn=Tn.current?.contains(Bt),Zs=bn.current?.contains(Bt);!Yn&&tt&&Lt(!1),!Zs&&Zt&&sn(!1)};return document.addEventListener("mousedown",ze),()=>document.removeEventListener("mousedown",ze)},[tt,Zt]),i.useEffect(()=>{if(!(tt||Zt))return;const ze=yt=>{yt.key==="Escape"&&(yt.stopPropagation(),tt&&Lt(!1),Zt&&sn(!1))};return document.addEventListener("keydown",ze),()=>document.removeEventListener("keydown",ze)},[tt,Zt]),i.useEffect(()=>{Ve(!1),Je(N.prompt||""),he("")},[e.id,N.prompt]);const Hn=yR.has(e.column)&&!Ie,Mn=i.useCallback(()=>{if(!Hn)return;We(!0),st(e.title||""),dt(e.description||""),Ue(e.dependencies||[]);const te=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",ze=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",yt=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";De(te),pe(ze),Be(yt),me(e.thinkingLevel??""),Vt(e.nodeId),Et(te||ze||yt?"custom":"default"),Kt(""),kn(e.enabledWorkflowSteps||[]),Jt(kr(e.executionMode)),Xt(e.sourceIssue?.provider??""),ln(e.sourceIssue?.repository??""),Le(e.sourceIssue?.externalIssueId??""),Te(e.sourceIssue?.url??""),ee([]),$t(e.reviewLevel),Rt(Ti(e.priority))},[Hn,e]),Qn=i.useCallback(()=>{We(!1),st(e.title||""),dt(e.description||""),Ue(e.dependencies||[]),Vt(e.nodeId),Xt(e.sourceIssue?.provider??""),ln(e.sourceIssue?.repository??""),Le(e.sourceIssue?.externalIssueId??""),Te(e.sourceIssue?.url??""),Rt(Ti(e.priority)),Jt(kr(e.executionMode)),Ne.forEach(te=>URL.revokeObjectURL(te.previewUrl)),ee([])},[e.title,e.description,e.dependencies,e.nodeId,e.priority,e.executionMode,Ne]),[ms,Xn]=i.useState("idle"),mn=i.useRef(null),Pt=i.useRef(0),is=i.useCallback(te=>{const ze={},yt=mt.trim(),Bt=Ze.trim();yt&&yt!==(e.title??"")&&(ze.title=yt),te&&Bt&&Bt!==(e.description??"")&&(ze.description=Bt),Wh(Ae,e.dependencies??[])||(ze.dependencies=Ae),Wh(qt,e.enabledWorkflowSteps??[])||(ze.enabledWorkflowSteps=qt);const Yn=Fc(kt),Zs=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";kt!==Zs&&(ze.modelProvider=Yn?.provider??null,ze.modelId=Yn?.modelId??null);const hr=Fc(be),q=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";be!==q&&(ze.validatorModelProvider=hr?.provider??null,ze.validatorModelId=hr?.modelId??null);const ke=Fc(Re),qe=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";Re!==qe&&(ze.planningModelProvider=ke?.provider??null,ze.planningModelId=ke?.modelId??null);const Mt=e.thinkingLevel??"";at!==Mt&&(ze.thinkingLevel=at!==""?at:null),(e.nodeId??void 0)!==It&&(ze.nodeId=It??null),jt!==e.reviewLevel&&(ze.reviewLevel=jt),Ft!==Ti(e.priority)&&(ze.priority=Ft),Qt!==kr(e.executionMode)&&(ze.executionMode=Qt==="fast"?"fast":null);const dn=zc(nn),Yt=zc(Gt),Nn=zc(ye),Xe=fR(ae);if(dn.length===0&&Yt.length===0&&Nn.length===0&&!Xe)e.sourceIssue&&(ze.sourceIssue=null);else{if(!dn||!Yt||!Nn)return{updates:null,error:"Source issue provider, repository, and issue identifier are required"};const Ot=Number.parseInt(Nn,10),_n=e.sourceIssue?.issueNumber??Ot;if(!Number.isFinite(_n)||_n<=0)return{updates:null,error:"Source issue identifier must be numeric for new metadata"};const Ss={provider:dn,repository:Yt,externalIssueId:Nn,issueNumber:_n,...Xe?{url:Xe}:{}},$s=e.sourceIssue;(!$s||$s.provider!==Ss.provider||$s.repository!==Ss.repository||$s.externalIssueId!==Ss.externalIssueId||$s.issueNumber!==Ss.issueNumber||($s.url??void 0)!==Ss.url)&&(ze.sourceIssue=Ss)}return{updates:ze,error:null}},[Ae,Ze,Qt,kt,It,Re,Ft,jt,qt,ye,nn,Gt,ae,at,mt,be,e]),Gn=i.useCallback(async te=>{const{updates:ze,error:yt}=is(te);if(!ze)return Xn("error"),yt&&h(`Failed to update ${e.id}: ${yt}`,"error"),!1;if(Object.keys(ze).length===0)return!0;const Bt=++Pt.current;St(!0),Xn("saving");try{const Yn=await ki(e.id,ze,n);return Bt!==Pt.current?void 0:(m?.(Yn),Xn("saved"),!0)}catch(Yn){return Bt===Pt.current&&(Xn("error"),h(`Failed to update ${e.id}: ${_e(Yn)}`,"error")),!1}finally{et.current&&Bt===Pt.current&&St(!1)}},[h,is,m,n,e.id]),K=i.useCallback(async te=>{await Gn(!0)},[Gn]),Ke=i.useCallback(async()=>{await Gn(!0)&&(h(`Updated ${e.id}`,"success"),et.current&&We(!1))},[h,Gn,e.id]);i.useEffect(()=>{if(Me)return mn.current&&clearTimeout(mn.current),mn.current=setTimeout(()=>{Gn(!1)},700),()=>{mn.current&&(clearTimeout(mn.current),mn.current=null)}},[Me,mt,Ae,kt,be,Re,at,It,jt,Ft,Qt,qt,nn,Gt,ye,ae,Gn]);const Ye=i.useCallback(async te=>{const ze=Ti(te),yt=Ti(e.priority);if(ze===yt){Dt(yt);return}const Bt=pt;Dt(ze),Ce(!0);try{const Yn=await ki(e.id,{priority:ze},n);Dt(Ti(Yn.priority)),m?.(Yn),h(`Priority updated to ${Ti(Yn.priority)}`,"success")}catch(Yn){Dt(Bt),h(`Failed to update ${e.id}: ${_e(Yn)}`,"error")}finally{et.current&&Ce(!1)}},[e.id,e.priority,n,pt,m,h]),ht=i.useCallback(te=>{Me&&(te.key==="Escape"?(te.preventDefault(),Qn()):te.key==="Enter"&&(te.ctrlKey||te.metaKey)&&(te.preventDefault(),Ke()))},[Me,Qn,Ke]);i.useEffect(()=>{if(Me)return document.addEventListener("keydown",ht),()=>document.removeEventListener("keydown",ht)},[Me,ht]);const Nt=i.useRef(null),{nodes:_t}=Ul(),{confirm:zt}=Qs(),{entries:Jn,loading:as,loadMore:ce,hasMore:Ge,total:lt,loadingMore:tn}=Nb(e.id,b==="logs"&&A==="agent-log",n),G=i.useCallback(()=>{v?.()},[v]);i.useEffect(()=>{if(x)return;const te=ze=>{ze.key==="Escape"&&!Me&&G()};return document.addEventListener("keydown",te),()=>document.removeEventListener("keydown",te)},[x,G,Me]);const Se=i.useCallback(async te=>{try{const ze=e.steps.some(Yn=>Yn.status!=="pending"),yt=(te==="todo"||te==="triage")&&ze;let Bt;if(yt){if(await zt({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Bt={preserveProgress:!0};else if(!await zt({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,te,Bt),G(),h(`Moved to ${cs[te]}`,"success")}catch(ze){h(_e(ze),"error")}},[e.id,e.steps,r,G,h,zt]),it=i.useCallback(async()=>{if(await zt({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0}))try{await o(e.id),G(),h(`Deleted ${e.id}`,"info")}catch(ze){const yt=pR(ze);if(!yt||yt.dependentIds.length===0){h(_e(ze),"error");return}const Bt=yt.dependentIds.join(", ");if(!await zt({title:"Force Delete Task",message:`${e.id} is a dependency of ${Bt}.
687
-
688
- Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await o(e.id,{removeDependencyReferences:!0}),G(),h(`Deleted ${e.id} after removing dependency references`,"info")}catch(Zs){h(_e(Zs),"error")}}},[e.id,o,G,h,zt]),Ct=i.useCallback(async()=>{await zt({title:"Merge Task",message:`Merge ${e.id} into the current branch?`})&&(G(),h(`Merging ${e.id}...`,"info"),l(e.id).then(ze=>{const yt=ze.merged?`Merged ${e.id} (branch: ${ze.branch})`:`Closed ${e.id} (${ze.error||"no branch to merge"})`;h(yt,"success")}).catch(ze=>{h(_e(ze),"error")}))},[e.id,l,G,h,zt]),Tt=i.useCallback(()=>{c&&(G(),c(e.id).then(()=>{h(`Retried ${e.id}`,"success")}).catch(te=>{h(_e(te),"error")}))},[e.id,c,G,h]),An=i.useCallback(()=>{d&&window.confirm(`This will erase all progress for ${e.id} and start the task from scratch. Continue?`)&&(G(),d(e.id).then(()=>{h(`Reset ${e.id} — fresh run will be allocated`,"success")}).catch(te=>{h(_e(te),"error")}))},[e.id,d,G,h]),vn=i.useCallback(async()=>{if(!(!u||!await zt({title:"Duplicate Task",message:`Duplicate ${e.id}? This will create a new task in Triage with the same description and prompt.`})))try{const ze=await u(e.id);G(),h(`Duplicated ${e.id} → ${ze.id}`,"success")}catch(ze){h(_e(ze),"error")}},[e.id,u,G,h,zt]),yn=i.useCallback(async()=>{try{e.paused?(await qw(e.id,n),h(`Unpaused ${e.id}`,"success")):(await If(e.id,n),h(`Paused ${e.id}`,"success")),G()}catch(te){h(_e(te),"error")}},[e.id,e.paused,G,h]),fn=i.useCallback(async()=>{try{await Gw(e.id,n),h(`Plan approved — ${e.id} moved to Todo`,"success"),G()}catch(te){h(_e(te),"error")}},[e.id,G,h]),Ln=i.useCallback(async()=>{if(await zt({title:"Reject Plan",message:"Reject this plan? The specification will be discarded and regenerated.",danger:!0}))try{await Jw(e.id,n),h(`Plan rejected — ${e.id} returned to Planning for replanning`,"info"),G()}catch(ze){h(_e(ze),"error")}},[e.id,G,h,zt]),Zn=i.useCallback(async()=>{if(await zt({title:"Rebuild Plan",message:"Rebuild the plan for this task? The task will move to planning for replanning."}))try{await rk(e.id,n),G(),h(`Replanning ${e.id}...`,"info")}catch(ze){h(_e(ze),"error")}},[e.id,n,G,h,zt]),hs=i.useCallback(()=>{Ee(!0),xe("")},[]),On=i.useCallback(()=>{Lt(!1),sn(!1)},[]),$n=i.useCallback(te=>{On(),Se(te)},[On]),Pn=i.useCallback(te=>{On(),te()},[On]),ps=i.useCallback(()=>{On(),Ct()},[On,Ct]),qn=i.useCallback(()=>{Ee(!1),xe(""),ie(!1)},[]),es=i.useCallback(async()=>{if(!je.trim()){h("Please enter feedback describing what needs refinement","error");return}if(je.length>2e3){h("Feedback must be 2000 characters or less","error");return}ie(!0);try{const te=await ok(e.id,je.trim(),n);h(`Refinement task created: ${te.id}`,"success"),G()}catch(te){h(_e(te),"error")}finally{ie(!1)}},[e.id,je,h,G]),Fn=i.useCallback(async te=>{O(!0);try{const ze=await Ol(e.id,te,n);se(yt=>[...yt,ze]),h("Screenshot attached","success")}catch(ze){h(_e(ze),"error")}finally{O(!1)}},[e.id,h]),rs=i.useCallback(async te=>{const ze=te.target.files?.[0];ze&&(await Fn(ze),Nt.current&&(Nt.current.value=""))},[Fn]);i.useEffect(()=>{const te=ze=>{const yt=ze.clipboardData?.items;if(yt)for(let Bt=0;Bt<yt.length;Bt++){const Yn=yt[Bt];if(Yn.type.startsWith("image/")){const Zs=Yn.getAsFile();if(Zs){ze.preventDefault(),Fn(Zs);return}}}};return document.addEventListener("paste",te),()=>document.removeEventListener("paste",te)},[Fn]);const ks=i.useCallback(te=>{te.preventDefault()},[]),os=i.useCallback(te=>{te.preventDefault();const ze=te.dataTransfer.files;for(let yt=0;yt<ze.length;yt++){const Bt=ze[yt];if(Bt.type.startsWith("image/")){Fn(Bt);return}}},[Fn]),xs=i.useCallback(async te=>{try{await Xw(e.id,te,n),se(ze=>ze.filter(yt=>yt.filename!==te)),h("Attachment deleted","info")}catch(ze){h(_e(ze),"error")}},[e.id,h]),qs=i.useCallback(async te=>{const ze=Wt;an(te);try{const yt=await ki(e.id,{enabledWorkflowSteps:te},n);h("Workflow steps updated","success"),m?.(yt)}catch(yt){an(ze),h(`Failed to update workflow steps: ${_e(yt)}`,"error")}},[e.id,n,Wt,m,h]),Fs=i.useCallback(async()=>{z(!0);try{const te=await ba(void 0,n);L(te),ne(!0)}catch(te){h(`Failed to load agents: ${_e(te)}`,"error"),ne(!1)}finally{z(!1)}},[n,h]),wa=i.useCallback(async te=>{try{const ze=await em(e.id,te,n),yt=X.find(Bt=>Bt.id===te)??null;Fe(yt||(Bt=>Bt?.id===te?Bt:null)),ne(!1),m?.(ze),h("Assigned agent updated","success")}catch(ze){h(`Failed to assign agent: ${_e(ze)}`,"error")}},[e.id,n,X,m,h]),ka=i.useCallback(async()=>{try{const te=await em(e.id,null,n);Fe(null),ne(!1),m?.(te),h("Agent unassigned","success")}catch(te){h(`Failed to unassign agent: ${_e(te)}`,"error")}},[e.id,n,m,h]),cr=i.useCallback(async te=>{const ze=[...I,te];w(ze);try{await ki(e.id,{dependencies:ze},n)}catch(yt){w(I),h(_e(yt),"error")}},[e.id,I,h]),Qi=i.useCallback(async(te,ze)=>{te.stopPropagation();const yt=I.filter(Bt=>Bt!==ze);w(yt);try{await ki(e.id,{dependencies:yt},n)}catch(Bt){w(I),h(_e(Bt),"error")}},[e.id,I,h]),Xi=i.useCallback(async te=>{try{const ze=await Wa(te,n);a(ze)}catch{h(`Failed to load dependency ${te}`,"error")}},[a,h]),Xs=i.useCallback(async te=>{we(!0);try{await ki(N.id,{prompt:te},n),h("Spec updated","success"),S&&(S.prompt=te)}catch(ze){throw h(_e(ze),"error"),ze}finally{we(!1)}},[N,S,h]),li=i.useCallback(async te=>{fe(!0);try{await ak(e.id,te,n),h("AI revision requested. Task moved to planning.","success"),G()}catch(ze){const yt=_e(ze);yt.includes("done")||yt.includes("archived")?h("Cannot request revision: Task must be in 'triage', 'todo', 'in-progress', or 'in-review' column.","error"):h(yt,"error")}finally{fe(!1)}},[e.id,h,G]),Pi=i.useCallback(()=>{Ve(!0),Je(N.prompt||""),he("")},[N.prompt]),bi=i.useCallback(()=>{Ve(!1),Je(N.prompt||""),he("")},[N.prompt]),gt=i.useCallback(async()=>{if(He===(N.prompt||"")){bi();return}Ve(!1);try{await Xs(He)}catch(te){throw Ve(!0),te}},[He,N.prompt,Xs,bi]),hn=i.useCallback(async()=>{$e.trim()&&await li($e.trim())},[$e,li]),Vs=i.useCallback(te=>{te.key==="Escape"?(te.preventDefault(),bi()):te.key==="Enter"&&(te.ctrlKey||te.metaKey)&&(te.preventDefault(),gt())},[bi,gt]),dr=s.filter(te=>te.id!==e.id&&!I.includes(te.id)).sort((te,ze)=>{const yt=ze.createdAt.localeCompare(te.createdAt);if(yt!==0)return yt;const Bt=parseInt(te.id.slice(te.id.lastIndexOf("-")+1),10)||0;return(parseInt(ze.id.slice(ze.id.lastIndexOf("-")+1),10)||0)-Bt}),ur=de?.name??e.assignedAgentId??null,go=i.useMemo(()=>{const te=[];return N.modelProvider&&te.push(N.modelProvider),N.validatorModelProvider&&!te.includes(N.validatorModelProvider)&&te.push(N.validatorModelProvider),N.planningModelProvider&&!te.includes(N.planningModelProvider)&&te.push(N.planningModelProvider),te},[N.modelProvider,N.validatorModelProvider,N.planningModelProvider]),bo=jd[e.column]||[],Jl=["todo","in-progress"],ja=e.column==="in-review"?Jl:bo,ls=ja[0],Na=ja.slice(1),Is=Na.length>0,Zi=i.useCallback(()=>{Lt(!1),En.current?.focus()},[]),xo=i.useCallback(te=>{if(!Is){ls&&$n(ls);return}const ze=te.currentTarget.querySelector(".detail-move-btn__arrow");if(!!(te.target instanceof Element&&te.target.closest(".detail-move-btn__arrow")||ze&&te.clientX>0&&te.clientX>=ze.getBoundingClientRect().left)){Lt(Bt=>!Bt),sn(!1);return}ls&&$n(ls)},[Is,ls,$n]),vo=i.useCallback(te=>{!Is||!(te.key==="ArrowDown"||te.altKey&&te.key==="ArrowDown")||(te.preventDefault(),Lt(!0),sn(!1))},[Is]),Sa=i.useCallback(te=>{te.key==="Escape"&&(te.preventDefault(),te.stopPropagation(),Zi())},[Zi]);i.useEffect(()=>{if(!tt)return;Tn.current?.querySelector(".detail-move-menu-item")?.focus()},[tt]);const mr={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…","merging-fix":"Merging fixes…"},Ca=e.status?mr[e.status]:void 0,yo=oe?.mergeStrategy??"direct",wo=oe?.autoMerge??!1,ko=yo==="pull-request"&&!wo;let ea="Merge & Close";return ko&&!Ca&&(e.prInfo?e.prInfo.status==="open"?ea="Check PR Status":e.prInfo.status==="merged"&&(ea="Finish & Close"):ea="Start PR Review"),t.jsxs("div",{className:x?"task-detail-content task-detail-content--embedded":"task-detail-content",onDragOver:ks,onDrop:os,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:[!Me&&Hn&&t.jsx("button",{className:"modal-edit-btn",onClick:Mn,title:"Edit task","aria-label":"Edit task",children:t.jsx(Cs,{size:14})}),!x&&g==="back"&&t.jsxs("button",{className:"modal-close task-detail-mobile-back",onClick:G,"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:G,"aria-label":"Close",type:"button",children:"×"})]})]}),t.jsxs("div",{className:`detail-body${b==="logs"&&A==="agent-log"&&!Me?" detail-body--agent-log":""}`,children:[Me?t.jsx("div",{className:"modal-edit-form",children:t.jsx(Mb,{mode:"edit",title:mt,onTitleChange:st,description:Ze,onDescriptionChange:dt,dependencies:Ae,onDependenciesChange:Ue,executorModel:kt,onExecutorModelChange:De,validatorModel:be,onValidatorModelChange:pe,planningModel:Re,onPlanningModelChange:Be,thinkingLevel:at,onThinkingLevelChange:me,presetMode:ft,onPresetModeChange:Et,selectedPresetId:on,onSelectedPresetIdChange:Kt,selectedWorkflowSteps:qt,onWorkflowStepsChange:kn,pendingImages:Ne,onImagesChange:ee,tasks:s.filter(te=>te.id!==e.id),projectId:n,disabled:Ie,addToast:h,isActive:Me,onAutoSaveDescription:K,reviewLevel:jt,onReviewLevelChange:$t,priority:Ft,onPriorityChange:Rt,nodeId:It,onNodeIdChange:Vt,nodeOptions:_t,nodeOverrideDisabled:pn,nodeOverrideDisabledReason:pn?"Execution node override is locked while a task is active/in progress.":void 0,executionMode:Qt,onExecutionModeChange:Jt,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:nn,onChange:te=>Xt(te.target.value),disabled:Ie,"data-testid":"task-source-provider-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Repository (e.g. owner/repo)",value:Gt,onChange:te=>ln(te.target.value),disabled:Ie,"data-testid":"task-source-repository-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:ye,onChange:te=>Le(te.target.value),disabled:Ie,"data-testid":"task-source-external-id-input"}),t.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:ae,onChange:te=>Te(te.target.value),disabled:Ie,"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 te=e.title||e.description||e.id,ze=!T&&te.length>Uc;return t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"detail-title",children:ze?te.slice(0,Uc)+"…":te}),te.length>Uc&&t.jsx("button",{className:"detail-description-toggle",onClick:()=>J(!T),children:T?"Show less":"Show more"})]})})(),t.jsxs("div",{className:"detail-meta",children:["Created ",new Date(e.createdAt).toLocaleDateString()," · Updated"," ",new Date(e.updatedAt).toLocaleDateString()," ·",t.jsxs("label",{className:`card-priority-badge card-priority-badge--${pt} detail-priority-chip ${Ut?"detail-priority-chip--saving":""}`,children:[t.jsx("span",{children:"Priority:"}),t.jsx("select",{className:"detail-priority-select",value:pt,onChange:te=>{Ye(te.target.value)},disabled:Ut,"aria-label":"Task priority",children:mo.map(te=>t.jsx("option",{value:te,children:te},te))})]}),U&&t.jsxs("div",{className:"detail-provenance",children:[t.jsx(Bs,{"aria-hidden":"true"}),t.jsxs("span",{children:[N.sourceType==="agent_heartbeat"?t.jsxs(t.Fragment,{children:["Created by"," ",U.sourceAgentId?t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>F(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:()=>Xi(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(Bs,{"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]})]})]})]})]}),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})]})]}),!Me&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"detail-tabs",children:[t.jsx("button",{className:`detail-tab${b==="definition"?" detail-tab-active":""}`,onClick:()=>k("definition"),children:"Definition"}),t.jsx("button",{className:`detail-tab${b==="logs"?" detail-tab-active":""}`,onClick:()=>k("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:()=>k("changes"),children:"Changes"}),t.jsx("button",{className:`detail-tab${b==="comments"?" detail-tab-active":""}`,onClick:()=>k("comments"),children:"Comments"}),t.jsx("button",{className:`detail-tab${b==="documents"?" detail-tab-active":""}`,onClick:()=>k("documents"),children:"Documents"}),t.jsx("button",{className:`detail-tab${b==="model"?" detail-tab-active":""}`,onClick:()=>k("model"),children:"Model"}),t.jsx("button",{className:`detail-tab${b==="workflow"?" detail-tab-active":""}`,onClick:()=>k("workflow"),children:"Workflow"}),t.jsx("button",{className:`detail-tab${b==="stats"?" detail-tab-active":""}`,onClick:()=>k("stats"),children:"Stats"}),t.jsx("button",{className:`detail-tab${b==="routing"?" detail-tab-active":""}`,onClick:()=>k("routing"),children:"Routing"}),ut.map(({entry:te,tabId:ze})=>t.jsx("button",{className:`detail-tab${b===ze?" detail-tab-active":""}`,onClick:()=>k(ze),children:te.slot.label},`plugin-tab-${te.pluginId}-${ze}`))]}),b==="workflow"?t.jsx("div",{className:"detail-section",children:t.jsx(JP,{taskId:e.id,results:rt,loading:ot,enabledWorkflowSteps:Wt,canEdit:Hn,projectId:n,isTaskInProgress:e.column==="in-progress"&&e.status!=="paused",onWorkflowStepsChange:qs})}):b==="model"?t.jsx("div",{className:"detail-section",children:t.jsx(AP,{task:e,addToast:h,onTaskUpdated:m,settings:oe})}):b==="logs"?t.jsxs("div",{className:`detail-section${A==="agent-log"?" detail-section--agent-log":""}`,children:[t.jsxs("div",{className:"log-subview-toggle",children:[t.jsx("button",{className:`log-subview-btn${A==="activity"?" log-subview-btn-active":""}`,onClick:()=>$("activity"),children:"Activity"}),t.jsx("button",{className:`log-subview-btn${A==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>$("agent-log"),children:"Agent Log"})]}),A==="agent-log"?t.jsx(SP,{entries:Jn,loading:as,executorModel:oR(e,oe),validatorModel:lR(e,oe),planningModel:dR(e,Jn,oe),hasMore:Ge,onLoadMore:ce,loadingMore:tn,totalCount:lt}):t.jsxs("div",{className:"detail-activity",children:[t.jsx("h4",{children:"Activity"}),N.activityLogTruncatedCount?t.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",N.log.length," activity entries."]}):null,N.log&&N.log.length>0?t.jsx("div",{className:"detail-activity-list",children:[...N.log].reverse().map((te,ze)=>t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-timestamp",children:mR(te.timestamp)}),t.jsx("span",{className:"detail-log-action",children:te.action})]}),te.outcome&&t.jsx("div",{className:"detail-log-outcome",children:te.outcome})]},ze))}):t.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):b==="changes"?t.jsx(zP,{taskId:e.id,worktree:e.worktree,projectId:n,column:e.column,mergeDetails:e.mergeDetails,modifiedFiles:e.modifiedFiles}):b==="comments"?t.jsx($P,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):b==="documents"?t.jsx(sR,{taskId:e.id,addToast:h,projectId:n,onTaskUpdated:m,canEdit:Hn}):xn?t.jsx("div",{className:"detail-section",children:t.jsx(qi,{slotId:"task-detail-tab",projectId:n,pluginIds:[xn.entry.pluginId]})}):b==="stats"?t.jsx("div",{className:"detail-section",children:t.jsx(aR,{tokenUsage:N.tokenUsage,loading:E,task:N})}):b==="routing"?t.jsx("div",{className:"detail-section",children:t.jsx(ZP,{task:e,settings:oe,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(Ci,{remarkPlugins:[Ei],children:e.summary})})]}),t.jsx(LP,{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(Bs,{"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":At,"aria-label":At?"Collapse source issue details":"Expand source issue details",onClick:()=>cn(te=>!te),children:t.jsx(Un,{size:16,className:At?"detail-source-chevron--expanded":void 0})})]}),At&&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)"})})]})]})]}),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:[go.length>0&&t.jsx("span",{className:"detail-provider-icons","data-testid":"detail-provider-icons",children:go.map(te=>t.jsx(Kn,{provider:te,size:"sm"},te))}),t.jsxs("span",{className:"detail-meta-label",children:[t.jsx(zn,{size:14,className:"detail-meta-label-icon"}),"Agent"]})]}),t.jsxs("div",{className:"detail-agent-actions",children:[ur?t.jsxs("span",{className:"detail-agent-chip",children:[t.jsx(zn,{size:14}),ur,t.jsx("button",{className:"detail-agent-clear",onClick:()=>void ka(),title:"Unassign agent",children:t.jsx(en,{size:12})})]}):t.jsx("button",{className:"btn btn-sm",onClick:()=>{Q?ne(!1):Fs()},children:"Assign Agent"}),Q&&t.jsxs("div",{className:"agent-picker-dropdown",children:[H&&t.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!H&&X.map(te=>t.jsxs("button",{className:`agent-picker-item${e.assignedAgentId===te.id?" selected":""}`,onClick:()=>void wa(te.id),children:[t.jsx(zn,{size:14}),t.jsx("span",{className:"agent-picker-name",children:te.name}),t.jsx("span",{className:"agent-picker-role",children:te.role})]},te.id)),!H&&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"}),N.steps&&N.steps.length>0?t.jsxs("div",{className:"step-progress-wrapper",children:[t.jsx("div",{className:"step-progress-bar",children:N.steps.map((te,ze)=>t.jsx("div",{className:`step-progress-segment step-progress-segment--${te.status}`,"data-tooltip":`${te.name} (${te.status})`,style:{backgroundColor:uR(te.status)}},ze))}),t.jsxs("span",{className:"step-progress-label",children:[N.steps.filter(te=>te.status==="done").length,"/",N.steps.length," step",N.steps.length===1?"":"s"]})]}):t.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),t.jsxs("div",{className:"detail-section",children:[!Oe&&t.jsx("div",{className:"detail-spec-edit-trigger",children:t.jsx("button",{className:"btn btn-sm",onClick:Pi,children:"Edit"})}),Oe?t.jsxs("div",{className:"spec-editor-edit-mode",children:[t.jsx("textarea",{className:"spec-editor-textarea",value:He,onChange:te=>Je(te.target.value),onKeyDown:Vs,disabled:W,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:bi,disabled:W,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void gt(),disabled:He===(N.prompt||"")||W,children:W?"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:$e,onChange:te=>he(te.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:Z,rows:4,maxLength:2e3}),t.jsxs("div",{className:"spec-editor-revision-actions",children:[t.jsxs("span",{className:"spec-editor-char-count",children:[$e.length,"/2000"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void hn(),disabled:!$e.trim()||Z,children:Z?"Requesting…":"Request AI Revision"})]})]})]}):E?t.jsx("div",{className:"spec-loading",children:"Loading specification…"}):N.prompt?t.jsx("div",{className:"markdown-body",children:t.jsx(Ci,{remarkPlugins:[Ei],children:N.prompt.replace(/^#\s+[^\n]*\n+/,"")})}):t.jsx("div",{className:"detail-prompt",children:"(no prompt)"})]}),t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Attachments"}),B.length>0?t.jsx("div",{className:"detail-attachments-grid",children:B.map(te=>{const ze=Ni(`/api/tasks/${e.id}/attachments/${te.filename}`);return t.jsxs("div",{className:"detail-attachment-card",children:[t.jsx("a",{className:"detail-attachment-link",href:ze,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{src:ze,alt:te.originalName,className:"detail-attachment-image"})}),t.jsxs("div",{className:"detail-attachment-meta",children:[te.originalName," (",hR(te.size),")"]}),t.jsx("button",{className:"detail-attachment-delete",onClick:()=>xs(te.filename),title:"Delete attachment",children:"×"})]},te.filename)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no attachments)"}),t.jsx("input",{className:"detail-hidden-file-input",ref:Nt,type:"file",accept:"image/*",onChange:rs}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Nt.current?.click(),disabled:P,children:P?"Uploading…":"Attach Screenshot"})]}),t.jsxs("div",{className:"detail-deps",children:[t.jsx("h4",{children:"Dependencies"}),I.length>0?t.jsx("ul",{className:"detail-dep-list",children:I.map(te=>{const ze=s.find(Bt=>Bt.id===te),yt=ze?.title||ze?.description||te;return t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>Xi(te),onKeyDown:Bt=>{(Bt.key==="Enter"||Bt.key===" ")&&(Bt.preventDefault(),Xi(te))},role:"link",tabIndex:0,title:`Click to view ${te}`,children:[t.jsx("span",{className:"detail-dep-id",children:te}),t.jsx("span",{className:"detail-dep-label",children:Vh(yt,40)})]}),t.jsx("button",{className:"dep-remove-btn",onClick:Bt=>Qi(Bt,te),title:`Remove dependency ${te}`,children:"×"})]},te)})}):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:()=>{Y&&ve(""),re(te=>!te)},children:"Add Dependency"}),Y&&(()=>{const te=le.toLowerCase(),ze=te?dr.filter(yt=>yt.id.toLowerCase().includes(te)||yt.title&&yt.title.toLowerCase().includes(te)||yt.description&&yt.description.toLowerCase().includes(te)):dr;return t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:le,onChange:yt=>ve(yt.target.value),onClick:yt=>yt.stopPropagation()}),ze.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):ze.map(yt=>t.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{cr(yt.id),re(!1)},children:[t.jsx("span",{className:"dep-dropdown-id",children:yt.id}),t.jsx("span",{className:"dep-dropdown-title",children:Vh(yt.title||yt.description||yt.id,30)})]},yt.id))]})})()]})]}),e.column==="in-review"&&t.jsx("div",{className:"detail-section detail-pr-section",children:t.jsx(RP,{taskId:e.id,projectId:n,prInfo:e.prInfo,automationStatus:e.status??null,autoMerge:oe?.autoMerge??!1,isManualPrFlow:ko,prAuthAvailable:f??!1,onPrCreated:te=>{e.prInfo=te},onPrUpdated:te=>{e.prInfo=te},addToast:h})})]})]})]}),t.jsx("div",{className:"modal-actions",children:Me?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"modal-edit-hint",children:ms==="saving"?"Autosaving…":ms==="saved"?"Saved":ms==="error"?"Save failed":"Changes autosave as you edit"}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("button",{className:"btn btn-sm",onClick:Qn,disabled:Ie,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Ke(),disabled:Ie,children:Ie?"Saving…":"Save"})]}):t.jsxs(t.Fragment,{children:[e.column==="triage"&&e.status==="awaiting-approval"&&N.prompt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:fn,children:"Approve Plan"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:Ln,children:"Reject Plan"})]}),e.column==="triage"&&e.status!=="awaiting-approval"&&!M&&t.jsx("button",{className:"btn btn-sm btn-danger",onClick:it,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(e.column!=="triage"||e.status==="awaiting-approval"||M||e.paused)&&t.jsxs("div",{className:"detail-actions-dropdown",ref:bn,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{sn(te=>!te),Lt(!1)},"aria-haspopup":"menu","aria-expanded":Zt,children:["Actions",t.jsx(un,{size:12})]}),Zt&&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:()=>Pn(it),children:"Delete"}),u&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Pn(vn),children:"Duplicate"}),(e.column==="done"||e.column==="in-review")&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Pn(hs),children:"Refine"}),t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Pn(Zn),children:"Respecify"}),M&&c&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Pn(Tt),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:()=>Pn(An),children:"Reset"}),e.column!=="done"&&!e.assignedAgentId&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Pn(yn),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:Tn,children:e.column==="in-review"?t.jsxs("div",{className:"detail-move-actions-in-review",children:[t.jsxs("div",{children:[t.jsxs("button",{ref:En,className:"btn btn-primary btn-sm detail-move-btn",onClick:xo,onKeyDown:vo,disabled:!ls,"aria-label":ls?`Move to ${cs[ls]}`:void 0,"aria-haspopup":Is?"menu":void 0,"aria-expanded":Is?tt:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",ls?cs[ls]:""]}),Is&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(un,{size:12})})]}),tt&&Is&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:Sa,children:Na.map(te=>t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>$n(te),onKeyDown:Sa,children:te==="in-progress"?"Back to In Progress":`Move to ${cs[te]}`},te))})]}),Ca?t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:Ca}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:ps,children:ea})]}):t.jsxs("div",{children:[t.jsxs("button",{ref:En,className:"btn btn-primary btn-sm detail-move-btn",onClick:xo,onKeyDown:vo,disabled:!ls,"aria-label":ls?`Move to ${cs[ls]}`:void 0,"aria-haspopup":Is?"menu":void 0,"aria-expanded":Is?tt:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",ls?cs[ls]:""]}),Is&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(un,{size:12})})]}),tt&&Is&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:Sa,children:Na.map(te=>t.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>$n(te),onKeyDown:Sa,children:["Move to ",cs[te]]},te))})]})})]})}),ue&&t.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:qn,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal detail-refine-modal",onClick:te=>te.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:qn,"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:je,onChange:te=>xe(te.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:[je.length,"/2000 characters"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:es,disabled:!je.trim()||Pe,children:Pe?"Creating...":"Create Refinement Task"})]})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:qn,disabled:Pe,children:"Cancel"})})]})}),_&&t.jsx(i.Suspense,{fallback:null,children:t.jsx(xR,{agentId:_,projectId:n,onClose:()=>F(null),addToast:h})})]})}function wR({onClose:e,...n}){const s=i.useRef(null);_i(s,!0,"task-detail-modal-size"),Mi(!0);const a=Fi(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(Ab,{...n,onRequestClose:e})})})}const Lo={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},Kh=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function Gh(e){return e==="merging-fix"?"Merging fixes…":e}const Pb=["title","status","column","dependencies","progress"],kR=["title","status","column"];function jR(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function NR(e){return e==="online"?"●":e==="connecting"?"◐":e==="error"?"✕":"○"}function Jh(e){try{const n=ss("kb-dashboard-list-columns",e);if(n){const a=JSON.parse(n).filter(r=>Pb.includes(r));if(a.length>0)return new Set(a)}}catch{}return new Set(kR)}function Yh(e){try{const n=ss("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function Qh(e){try{const n=ss("kb-dashboard-list-collapsed",e);if(n){const a=JSON.parse(n).filter(r=>la.includes(r));if(a.length>0)return new Set(a)}}catch{}return new Set}function Xh(e){try{const n=ss("kb-dashboard-selected-tasks",e);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function Zh(e){try{const n=ss("kb-dashboard-list-selected-task",e);if(typeof n=="string"&&n.trim().length>0)return n}catch{}return null}function ep(e){try{const s=ss("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 kl=280,zd=.65,Oo=16;function Ud(e){return Math.max(kl,e*zd)}function Fo(e,n){const s=Ud(n);return Math.min(Math.max(e,kl),s)}function SR(e){return e.status==="executing"||e.column==="in-progress"}function tp(e){const n=og(e);return n.total===0||!SR(e)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function CR({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:v,onPlanningMode:b,onSubtaskBreakdown:k,onTasksUpdated:S,projectId:j,projectName:E,taskStuckTimeoutMs:y,searchQuery:N="",lastFetchTimeMs:M,prAuthAvailable:D}){const[C,_]=i.useState("id"),[F,U]=i.useState("desc"),[A,$]=i.useState(null),[T,J]=i.useState(null),[B,se]=i.useState(null),O=oi()==="mobile",{confirm:I}=Qs(),[w,Y]=i.useState(()=>Jh(j)),[re,le]=i.useState(()=>Yh(j)),[ve,de]=i.useState(()=>Qh(j));i.useEffect(()=>{typeof window<"u"&&vs("kb-dashboard-list-columns",JSON.stringify([...w]),j)},[j,w]),i.useEffect(()=>{typeof window<"u"&&vs("kb-dashboard-hide-done",re.toString(),j)},[re,j]),i.useEffect(()=>{typeof window<"u"&&vs("kb-dashboard-list-collapsed",JSON.stringify([...ve]),j)},[ve,j]);const[Fe,X]=i.useState(!1),[L,Q]=i.useState(!1),[ne,H]=i.useState(()=>Xh(j)),[z,W]=i.useState(()=>Zh(j)),[we,Z]=i.useState(null),[fe,Oe]=i.useState(()=>ep(j)),Ve=i.useRef(null),He=i.useRef(null);i.useEffect(()=>{Y(Jh(j)),le(Yh(j)),de(Qh(j)),H(Xh(j));const ye=Zh(j);W(ye),Z(ye?e.find(Le=>Le.id===ye)??null:null),Oe(ep(j))},[j,e]),i.useEffect(()=>{typeof window<"u"&&vs("kb-dashboard-selected-tasks",JSON.stringify([...ne]),j)},[j,ne]),i.useEffect(()=>{if(!(typeof window>"u")){if(z){vs("kb-dashboard-list-selected-task",z,j);return}Ja("kb-dashboard-list-selected-task",j)}},[j,z]),i.useEffect(()=>{if(!z){Z(null);return}const ye=e.find(Le=>Le.id===z);ye&&Z(Le=>!Le||Le.id!==z?ye:{...Le,...ye})},[z,e]),i.useEffect(()=>{if(O||typeof ResizeObserver>"u")return;const ye=Ve.current;if(!ye)return;const Le=()=>{const Te=Fo(fe,ye.clientWidth);Te!==fe&&Oe(Te)};Le();const ae=new ResizeObserver(Le);return ae.observe(ye),()=>ae.disconnect()},[O,fe]),i.useEffect(()=>{if(O||typeof ResizeObserver>"u")return;const ye=He.current,Le=Ve.current;if(!ye||!Le)return;let ae=null,Te=ye.offsetWidth;const Ne=new ResizeObserver(()=>{const ee=Fo(ye.offsetWidth,Le.clientWidth);ee!==Te&&(Te=ee,ae&&clearTimeout(ae),ae=setTimeout(()=>{try{vs("kb-dashboard-list-sidebar-width",String(ee),j)}catch{}},200))});return Ne.observe(ye),()=>{Ne.disconnect(),ae&&clearTimeout(ae)}},[O,j]);const Je=i.useCallback(()=>{Q(ye=>(ye&&H(new Set),!ye))},[]),$e=i.useCallback(ye=>{H(Le=>{const ae=new Set(Le);return ae.has(ye)?ae.delete(ye):ae.add(ye),ae})},[]),he=i.useCallback(()=>{H(new Set)},[]),ue=i.useCallback(ye=>{Y(Le=>{const ae=new Set(Le);return ae.has(ye)?ae.size>1&&ae.delete(ye):ae.add(ye),ae})},[]),Ee={title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},je=i.useCallback(ye=>{C===ye?U(Le=>Le==="asc"?"desc":"asc"):(_(ye),U("asc"))},[C]),xe=i.useCallback(ye=>{se(Le=>Le===ye?null:ye)},[]),Pe=i.useCallback(ye=>{de(Le=>{const ae=new Set(Le);return ae.has(ye)?ae.delete(ye):ae.add(ye),ae})},[]),ie=i.useCallback(()=>{se(null)},[]),Me=i.useMemo(()=>{let ye=N?e.filter(Ne=>Ne.id.toLowerCase().includes(N.toLowerCase())||Ne.title&&Ne.title.toLowerCase().includes(N.toLowerCase())||Ne.description.toLowerCase().includes(N.toLowerCase())):[...e];re&&!B&&(ye=ye.filter(Ne=>Ne.column!=="done"&&Ne.column!=="archived"));const ae=[...B?ye.filter(Ne=>Ne.column===B):ye].sort((Ne,ee)=>{let Ie=0;switch(C){case"id":Ie=Ne.id.localeCompare(ee.id);break;case"title":Ie=(Ne.title||Ne.description).localeCompare(ee.title||ee.description);break;case"status":Ie=(Ne.status||"").localeCompare(ee.status||"");break;case"column":Ie=Ne.column.localeCompare(ee.column);break}return F==="asc"?Ie:-Ie}),Te={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};return ae.forEach(Ne=>Te[Ne.column].push(Ne)),Te},[e,N,C,F,re,B]),We=i.useMemo(()=>Object.values(Me).reduce((ye,Le)=>ye+Le.length,0),[Me]),mt=i.useMemo(()=>e.filter(ye=>ye.column==="done"||ye.column==="archived").length,[e]),st=i.useMemo(()=>re?mt:0,[re,mt]),Ze=i.useCallback(()=>{const ye=Object.values(Me).flat().filter(Le=>Le.column!=="archived").map(Le=>Le.id);H(Le=>{if(ye.every(Te=>Le.has(Te))){const Te=new Set(Le);return ye.forEach(Ne=>Te.delete(Ne)),Te}else return new Set([...Le,...ye])})},[Me]),dt=i.useMemo(()=>{const ye=Object.values(Me).flat().filter(Le=>Le.column!=="archived");return ye.length===0?!1:ye.every(Le=>ne.has(Le.id))},[Me,ne]),Ae=i.useMemo(()=>{const ye=Object.values(Me).flat().filter(ae=>ae.column!=="archived");if(ye.length===0)return!1;const Le=ye.filter(ae=>ne.has(ae.id)).length;return Le>0&&Le<ye.length},[Me,ne]),[Ue,kt]=i.useState("__no_change__"),[De,be]=i.useState("__no_change__"),[pe,Re]=i.useState("__no_change__"),[Be,at]=i.useState([]),[me,ft]=i.useState(!1),Et=i.useMemo(()=>pe&&pe!=="__no_change__"?Be.find(ye=>ye.id===pe):void 0,[Be,pe]),[jt,$t]=i.useState(!1);i.useEffect(()=>{if(ne.size===0)return;let ye=!1;return(async()=>{ft(!0);try{const ae=await pl();ye||at(ae)}catch(ae){console.error("Failed to fetch nodes for bulk edit",ae),ye||at([])}finally{ye||ft(!1)}})(),()=>{ye=!0}},[ne.size]);const Ft=i.useCallback(async()=>{if(ne.size===0)return;const ye=Array.from(ne).filter(ae=>{const Te=e.find(Ne=>Ne.id===ae);return Te&&Te.column!=="archived"});if(ye.length===0){d("No valid tasks to update (archived tasks cannot be modified)","error");return}const Le={taskIds:ye};if(Ue!=="__no_change__")if(Ue==="")Le.modelProvider=null,Le.modelId=null;else{const ae=Ue.indexOf("/");ae!==-1&&(Le.modelProvider=Ue.slice(0,ae),Le.modelId=Ue.slice(ae+1))}if(De!=="__no_change__")if(De==="")Le.validatorModelProvider=null,Le.validatorModelId=null;else{const ae=De.indexOf("/");ae!==-1&&(Le.validatorModelProvider=De.slice(0,ae),Le.validatorModelId=De.slice(ae+1))}if(pe!=="__no_change__"&&(pe===""?Le.nodeId=null:Le.nodeId=pe),Object.keys(Le).length===1){d("No changes to apply","info");return}$t(!0);try{const ae=await Lw(Le.taskIds,Le.modelProvider,Le.modelId,Le.validatorModelProvider,Le.validatorModelId,void 0,void 0,Le.nodeId,j);S&&S(ae.updated),d(`Updated ${ye.length} task${ye.length===1?"":"s"}`,"success"),he(),kt("__no_change__"),be("__no_change__"),Re("__no_change__")}catch(ae){d(_e(ae)||"Failed to update models","error")}finally{$t(!1)}},[ne,e,Ue,De,pe,j,d,he,S]),Rt=i.useCallback(ye=>{if(O){c(ye,{origin:"list-mobile"});return}W(ye.id),Z(ye)},[O,c]),It=i.useRef(null),Vt=i.useRef(null);i.useEffect(()=>()=>{It.current&&clearTimeout(It.current)},[]);const Qt=i.useCallback(ye=>{if(W(ye.id),Z(ye),"prompt"in ye){Vt.current=null,It.current&&(clearTimeout(It.current),It.current=null);return}Vt.current=ye.id,It.current&&clearTimeout(It.current),It.current=setTimeout(()=>{It.current=null,Vt.current===ye.id&&Wa(ye.id,j).then(ae=>{Vt.current===ae.id&&Z(Te=>!Te||Te.id!==ae.id?Te:{...Te,...ae})}).catch(()=>{})},200)},[j]),Jt=i.useCallback((ye,Le)=>{if(Le.paused){ye.preventDefault();return}ye.dataTransfer.setData("text/plain",Le.id),ye.dataTransfer.effectAllowed="move",$(Le.id)},[]),on=i.useCallback(()=>{$(null),J(null)},[]),Kt=i.useCallback(ye=>{if(O)return;ye.preventDefault();const Le=Ve.current;if(!Le)return;const ae=Le.getBoundingClientRect(),Te=ee=>{const Ie=ee.clientX-ae.left;Oe(Fo(Ie,ae.width))},Ne=()=>{window.removeEventListener("mousemove",Te),window.removeEventListener("mouseup",Ne)};window.addEventListener("mousemove",Te),window.addEventListener("mouseup",Ne)},[O]),qt=i.useCallback(ye=>{if(O)return;const Le=Ve.current?.clientWidth??0,ae=fe/zd+Oo,Te=Math.max(Le,ae),Ne=Ud(Te);if(ye.key==="ArrowLeft"||ye.key==="ArrowRight"){ye.preventDefault();const ee=ye.key==="ArrowLeft"?-Oo:Oo;Oe(Ie=>Fo(Ie+ee,Te));return}if(ye.key==="Home"){ye.preventDefault(),Oe(kl);return}ye.key==="End"&&(ye.preventDefault(),Oe(Ne))},[O,fe]),kn=i.useCallback((ye,Le)=>{ye.preventDefault(),ye.dataTransfer.dropEffect="move",J(Le)},[]),nn=i.useCallback(()=>{J(null)},[]),Xt=i.useCallback(async(ye,Le)=>{ye.preventDefault(),J(null);const ae=ye.dataTransfer.getData("text/plain");if(ae){if(Le==="archived"){d("Tasks can only be archived via the archive button","error");return}try{const Ne=e.find(St=>St.id===ae)?.steps.some(St=>St.status!=="pending")??!1,ee=(Le==="todo"||Le==="triage")&&Ne;let Ie;if(ee){if(await I({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Ie={preserveProgress:!0};else if(!await I({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await n(ae,Le,Ie)}catch(Te){d(_e(Te),"error")}}},[n,d,e,I]),Gt=ye=>C!==ye?t.jsx(vf,{size:14,className:"sort-icon"}):F==="asc"?t.jsx(oa,{size:14,className:"sort-icon active"}):t.jsx(eo,{size:14,className:"sort-icon active"}),ln=ye=>t.jsxs("div",{id:ye,className:"list-view-options-panel",children:[t.jsx("div",{className:"list-view-options-columns",children:Pb.map(Le=>{const ae=w.has(Le),Te=ae&&w.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${Te?" disabled":""}`,title:Te?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:ae,onChange:()=>ue(Le),disabled:Te}),t.jsx("span",{children:Ee[Le]})]},Le)})}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>le(Le=>!Le),"aria-pressed":re,title:re?"Show done tasks":"Hide done tasks",children:[re?t.jsx(sr,{size:14}):t.jsx(Qd,{size:14}),re?"Show Done":"Hide Done"]}),t.jsx("div",{className:"list-drop-zones list-drop-zones--sidebar",children:la.map(Le=>{const ae=e.filter(Ie=>Ie.column===Le).length,Te=Le==="done"||Le==="archived",Ne=re&&Te?0:ae,ee=re&&Te&&ae>0;return t.jsxs("div",{className:`list-drop-zone${T===Le?" drag-over":""}${B===Le?" active":""}`,onClick:()=>xe(Le),onDragOver:Ie=>kn(Ie,Le),onDragLeave:nn,onDrop:Ie=>Xt(Ie,Le),"data-column":Le,children:[t.jsx("span",{className:`list-section-dot dot-${Le}`}),t.jsx("span",{className:"drop-zone-label",children:cs[Le]}),t.jsx("span",{className:"drop-zone-count",children:ee?`${Ne} of ${ae}`:ae})]},Le)})})]});return t.jsxs("div",{className:"list-view",children:[O&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"list-toolbar",children:[t.jsx("button",{className:"btn btn-sm",onClick:Je,"aria-pressed":L,children:L?"Done Editing":"Bulk Edit"}),t.jsxs("button",{className:"btn btn-sm list-view-options-toggle",onClick:()=>X(ye=>!ye),"aria-expanded":Fe,"aria-controls":"list-view-options-panel-mobile",children:[t.jsx(Pu,{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:B?`${We} of ${e.length} tasks in ${cs[B]}`:`${We} of ${e.length} tasks`})]}),Fe?t.jsx("div",{className:"list-toolbar-mobile-options",children:ln("list-view-options-panel-mobile")}):null]}),t.jsx("div",{className:"list-table-container",children:t.jsxs("div",{className:O?"":"list-split-layout","data-testid":O?void 0:"list-split-layout",ref:Ve,children:[t.jsxs("div",{className:O?"":"list-split-sidebar","data-testid":O?void 0:"list-split-sidebar",ref:He,style:O?void 0:{width:`${fe}px`},children:[!O&&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:[B?`${We} of ${e.length} tasks in ${cs[B]}`:`${We} of ${e.length} tasks`,st>0&&!B&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",st," hidden)"]})]}),t.jsxs("div",{className:"list-sidebar-controls__actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Je,"aria-pressed":L,children:L?"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:[B?t.jsx("button",{className:"btn btn-sm",onClick:ie,"aria-label":"Clear column filter",children:`Filter: ${cs[B]}`}):null,re?t.jsx("span",{className:"list-sidebar-chip",children:"Done hidden"}):null,L?t.jsx("span",{className:"list-sidebar-chip",children:"Bulk edit"}):null,L&&ne.size>0?t.jsx("button",{className:"btn btn-sm",onClick:he,children:`${ne.size} selected`}):null]})]}),t.jsxs("button",{className:"btn btn-sm list-view-options-toggle",onClick:()=>X(ye=>!ye),"aria-expanded":Fe,"aria-controls":"list-view-options-panel",children:[t.jsx(Pu,{size:14}),"View options"]}),Fe&&ln("list-view-options-panel"),L&&ne.size>0&&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:Ue,onChange:kt,label:"Executor Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:p,onToggleFavorite:x,favoriteModels:g,onToggleModelFavorite:v})}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(Ns,{models:f,value:De,onChange:be,label:"Reviewer Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:p,onToggleFavorite:x,favoriteModels:g,onToggleModelFavorite:v})}),t.jsxs("div",{className:"bulk-edit-dropdown bulk-edit-node-wrap",children:[t.jsxs("select",{className:"select bulk-node-select",value:pe,onChange:ye=>Re(ye.target.value),"aria-label":"Node Override",disabled:me,children:[t.jsx("option",{value:"__no_change__",children:"No change"}),t.jsx("option",{value:"",children:"Use project default"}),Be.map(ye=>t.jsx("option",{value:ye.id,children:`${NR(ye.status)} ${ye.name||ye.id} (${jR(ye.status)})`},ye.id))]}),Et?t.jsx(ua,{status:Et.status,showLabel:!0}):null]}),t.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:Ft,disabled:jt||Ue==="__no_change__"&&De==="__no_change__"&&pe==="__no_change__",children:jt?"Applying...":"Apply"})]})]}),t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx(mg,{onCreate:h??(async()=>d("Task creation not available","error")),addToast:d,tasks:e,availableModels:f,onPlanningMode:b,onSubtaskBreakdown:k,projectId:j,autoExpand:!1,favoriteProviders:p,favoriteModels:g,onToggleFavorite:x,onToggleModelFavorite:v})}),We===0?t.jsx("div",{className:"list-empty",children:N?"No tasks match your filter":"No tasks yet"}):O?t.jsx("div",{className:"list-cards",children:la.map(ye=>{if(B&&ye!==B||re&&(ye==="done"||ye==="archived")&&!B)return null;const Le=Me[ye],ae=Le.length===0;if(N&&ae)return null;const Te=ve.has(ye);return t.jsxs(i.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${Te?" list-section-header--collapsed":""}`,onClick:()=>Pe(ye),"aria-expanded":!Te,role:"button",tabIndex:0,onKeyDown:Ne=>{(Ne.key==="Enter"||Ne.key===" ")&&(Ne.preventDefault(),Pe(ye))},children:[t.jsx(Un,{size:14,className:`list-section-chevron${Te?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${ye}`}),t.jsx("span",{className:"list-section-title",children:cs[ye]}),t.jsx("span",{className:"list-section-count",children:Le.length})]}),!Te&&t.jsx(t.Fragment,{children:ae?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):Le.map(Ne=>{const ee=Ne.status==="failed",Ie=Ne.paused===!0,St=bl(Ne,y,M),pt=!u&&!ee&&!Ie&&!St&&(Ne.column==="in-progress"||Kh.has(Ne.status)),Dt=typeof Ne.status=="string"&&Ne.status.trim().length>0,Ut=!!(Ne.dependencies&&Ne.dependencies.length>0),Ce=tp(Ne),et=Ce.hasProgress,tt=L;return t.jsxs("div",{className:`list-card${pt?" agent-active":""}${tt?" list-card--selectable":""}`,onClick:()=>Rt(Ne),"data-id":Ne.id,children:[tt&&t.jsx("label",{className:"list-card-checkbox",onClick:Lt=>Lt.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:ne.has(Ne.id),onChange:Lt=>{Lt.stopPropagation(),$e(Ne.id)},onClick:Lt=>Lt.stopPropagation(),disabled:Ne.column==="archived","aria-label":`Select ${Ne.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:Ne.id}),Ne.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(ds,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),t.jsx("span",{className:"list-card-spacer"}),Ie&&Ne.pausedByAgentId?t.jsx("span",{className:"list-status-badge paused",children:"paused by agent"}):St?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):Dt?t.jsx("span",{className:`list-status-badge list-status-badge--${Ne.column}${ee?" failed":""}${pt?" pulsing":""}`,children:Gh(Ne.status??"")}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:Ne.title||Ne.description})}),(Ut||et)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[Ut&&t.jsxs("span",{className:"list-dep-badge",title:Ne.dependencies.join(", "),children:[t.jsx(Ha,{size:12})," ",Ne.dependencies.length]}),et&&t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${Ce.percent}%`,backgroundColor:Lo[Ne.column]}})}),t.jsx("span",{className:"list-progress-label",children:Ce.label})]})]})]},Ne.id)})})]},ye)})}):t.jsxs("table",{className:"list-table",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[L&&t.jsx("th",{className:"list-header-cell list-header-checkbox",children:t.jsx("input",{type:"checkbox",checked:dt,ref:ye=>{ye&&(ye.indeterminate=Ae)},onChange:Ze,"aria-label":"Select all visible tasks"})}),w.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>je("title"),children:["Title ",Gt("title")]}),w.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>je("status"),children:["Status ",Gt("status")]}),w.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>je("column"),children:["Column ",Gt("column")]}),w.has("dependencies")&&t.jsx("th",{className:"list-header-cell",children:"Dependencies"}),w.has("progress")&&t.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),t.jsx("tbody",{children:la.map(ye=>{if(B&&ye!==B||re&&(ye==="done"||ye==="archived")&&!B)return null;const Le=Me[ye],ae=Le.length===0;if(N&&ae)return null;const Te=ve.has(ye);return t.jsxs(i.Fragment,{children:[t.jsx("tr",{className:`list-section-header${Te?" list-section-header--collapsed":""}`,onClick:()=>Pe(ye),"aria-expanded":!Te,children:t.jsxs("th",{colSpan:w.size+(L?1:0),className:"list-section-cell",children:[t.jsx(Un,{size:14,className:`list-section-chevron${Te?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${ye}`}),t.jsx("span",{className:"list-section-title",children:cs[ye]}),t.jsx("span",{className:"list-section-count",children:Le.length})]})}),!Te&&t.jsx(t.Fragment,{children:ae?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:w.size+(L?1:0),className:"list-empty-cell",children:"No tasks"})}):Le.map(Ne=>{const ee=Ne.status==="failed",Ie=Ne.paused===!0,St=bl(Ne,y,M),pt=!u&&!ee&&!Ie&&!St&&(Ne.column==="in-progress"||Kh.has(Ne.status)),Dt=A===Ne.id;return t.jsxs("tr",{className:`list-row${ee?" failed":""}${Ie?" paused":""}${St?" stuck":""}${pt?" agent-active":""}${Dt?" dragging":""}${z===Ne.id?" list-row--selected":""}`,onClick:()=>Rt(Ne),draggable:!Ie,onDragStart:Ut=>Jt(Ut,Ne),onDragEnd:on,"data-id":Ne.id,children:[L&&t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:ne.has(Ne.id),onChange:Ut=>{Ut.stopPropagation(),$e(Ne.id)},onClick:Ut=>Ut.stopPropagation(),disabled:Ne.column==="archived","aria-label":`Select ${Ne.id}`})}),w.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:Ne.id}),t.jsxs("div",{className:"list-title-row",children:[Ne.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(ds,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),t.jsx("span",{className:"list-title-text",children:Ne.title||Ne.description})]})]})}),w.has("status")&&t.jsx("td",{className:"list-cell",children:Ie&&Ne.pausedByAgentId?t.jsx("span",{className:"list-status-badge paused",children:"paused by agent"}):St?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):Ne.status?t.jsx("span",{className:`list-status-badge list-status-badge--${Ne.column}${ee?" failed":""}${pt?" pulsing":""}`,children:Gh(Ne.status??"")}):t.jsx("span",{className:"list-status-badge",children:"-"})}),w.has("column")&&t.jsx("td",{className:"list-cell",children:t.jsx("span",{className:"list-column-badge",style:{background:`${Lo[Ne.column]}20`,color:Lo[Ne.column]},children:cs[Ne.column]})}),w.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:Ne.dependencies&&Ne.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:Ne.dependencies.join(", "),children:[t.jsx(Ha,{size:12})," ",Ne.dependencies.length]}):"-"}),w.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const Ut=tp(Ne);return Ut.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:`${Ut.percent}%`,backgroundColor:Lo[Ne.column]}})}),t.jsx("span",{className:"list-progress-label",children:Ut.label})]}):"-"})()})]},Ne.id)})})]},ye)})})]})]}),!O&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"list-split-resize-handle","data-testid":"list-split-resize-handle",onMouseDown:Kt,onKeyDown:qt,role:"separator",tabIndex:0,"aria-orientation":"vertical","aria-label":"Resize task list sidebar","aria-valuemin":kl,"aria-valuemax":Math.round(Ud(Ve.current?.clientWidth??fe/zd+Oo)),"aria-valuenow":Math.round(fe)}),t.jsx("div",{className:"list-split-detail","data-testid":"list-split-detail",children:we?t.jsx("div",{className:"list-split-detail-content","data-testid":"list-split-detail-content",children:t.jsx(Ab,{task:we,projectId:j,tasks:e,embedded:!0,onOpenDetail:Qt,onMoveTask:n,onDeleteTask:a,onMergeTask:r,onRetryTask:s,onResetTask:o,onDuplicateTask:l,onTaskUpdated:ye=>{Z(Le=>!Le||Le.id!==ye.id?Le:{...Le,...ye})},addToast:d,prAuthAvailable:D})}):t.jsx("div",{className:"list-split-detail-empty",children:t.jsx("p",{children:"Select a task to view details"})})})]})]})})]})}const ER={active:{label:"Active",color:"var(--success)",icon:ns},paused:{label:"Paused",color:"var(--warning)",icon:mi},errored:{label:"Error",color:"var(--color-error)",icon:Rs},initializing:{label:"Initializing",color:"var(--info)",icon:bt}};function _R(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 MR(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 AR(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.node,o=n.node;return!r&&!o?e.nodeNameFallback===n.nodeNameFallback:!r||!o?!1:r.id===o.id&&r.name===o.name&&r.status===o.status&&r.type===o.type}function PR({project:e,health:n,onSelect:s,onPause:a,onResume:r,onRemove:o,node:l,nodeNameFallback:c,isLoading:d=!1}){const[u,m]=i.useState(!1),h=ER[e.status],f=h.icon,p=i.useCallback(()=>{s(e)},[s,e]),g=i.useCallback(j=>{j.stopPropagation(),a(e)},[a,e]),x=i.useCallback(j=>{j.stopPropagation(),r(e)},[r,e]),v=i.useCallback(j=>{if(j.stopPropagation(),!u){m(!0);return}o(e),m(!1)},[u,o,e]),b=e.status==="paused",k=e.status==="errored",S=e.status==="initializing";return t.jsxs("div",{className:`project-card ${d?"project-card-loading":""} ${k?"project-card-errored":""}`,onClick:p,"data-project-id":e.id,role:"button",tabIndex:0,onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),p())},children:[t.jsxs("div",{className:"project-card-header",children:[t.jsx("div",{className:"project-card-icon",children:t.jsx(ws,{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||c)&&t.jsxs("span",{className:"node-badge",title:`Assigned node: ${l?.name??c}`,children:["on: ",l?.name??c]}),t.jsx("span",{className:"project-card-path",title:e.path,children:MR(e.path)})]}),t.jsxs("div",{className:"project-card-status-badge",style:{color:h.color,borderColor:h.color},children:[t.jsx(f,{size:12,className:S?"animate-spin":""}),t.jsx("span",{children:h.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:_R(e.lastActivityAt||n?.lastActivityAt)})]}),t.jsxs("div",{className:"project-card-actions",children:[b?t.jsxs("button",{className:"project-card-action project-card-action-resume",onClick:x,disabled:d,title:"Resume project","aria-label":"Resume project",children:[t.jsx(ns,{size:14}),t.jsx("span",{children:"Resume"})]}):t.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:g,disabled:d||S,title:S?"Cannot pause while initializing":"Pause project","aria-label":"Pause project",children:[t.jsx(mi,{size:14}),t.jsx("span",{children:"Pause"})]}),t.jsxs("button",{className:"project-card-action project-card-action-open",onClick:p,disabled:d,title:"Open project","aria-label":"Open project",children:[t.jsx(to,{size:14}),t.jsx("span",{children:"Open"})]}),t.jsxs("button",{className:`project-card-action project-card-action-remove ${u?"is-armed":""}`,onClick:v,disabled:d,title:u?"Confirm remove":"Remove project","aria-label":u?"Confirm remove project":"Remove project",children:[t.jsx(Sn,{size:14}),t.jsx("span",{children:u?"Confirm":""})]})]})]})]})}const RR=i.memo(PR,AR);function TR(){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(ws,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(Gs,{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(Rs,{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 IR=1e4,np=5;function $R(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+=np){const x=e.slice(g,g+np),v=await Promise.allSettled(x.map(async b=>{try{return await nm(b)}catch{return null}}));if(x.forEach((b,k)=>{const S=v[k];p[b]=S.status==="fulfilled"?S.value:null}),d.current?.signal.aborted)return}s(p),u.current=!0}catch(p){if(p instanceof Error&&p.name==="AbortError")return;l(p instanceof Error?p.message:"Failed to fetch health data"),u.current=!0}finally{r(!1)}},[e]),h=i.useCallback(async f=>{try{const p=await nm(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()},IR),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[m,e.length]),{healthMap:n,loading:a,error:o,refresh:m,refreshProject:h}}function DR({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 A=JSON.parse(U);b(A)}catch{}},[]);const[v,b]=i.useState([]),k=i.useMemo(()=>e.map(U=>U.id),[e]),{healthMap:S,loading:j}=$R(k),E=i.useMemo(()=>e.map(U=>({project:U,health:S[U.id]||null})),[e,S]),y=i.useMemo(()=>{let U=[...E];return d!=="all"&&(U=U.filter(({project:A})=>A.status===d)),m!==null&&(U=U.filter(({project:A})=>A.nodeId===m)),U},[E,d,m]),N=i.useMemo(()=>{const U=[...y];return U.sort((A,$)=>{let T=0;switch(f){case"name":T=A.project.name.localeCompare($.project.name);break;case"activity":{const J=A.project.lastActivityAt||A.health?.lastActivityAt||A.project.updatedAt,B=$.project.lastActivityAt||$.health?.lastActivityAt||$.project.updatedAt;T=new Date(B).getTime()-new Date(J).getTime();break}case"status":{const J={errored:0,initializing:1,paused:2,active:3};T=J[A.project.status]-J[$.project.status];break}}return g==="asc"?T:-T}),U},[y,f,g]),M=i.useMemo(()=>{const U=e.length,A=e.filter(O=>O.status==="active").length,$=e.filter(O=>O.status==="errored").length,T=new Set;e.forEach(O=>{O.nodeId&&T.add(O.nodeId)});const J=T.size||(U>0?1:0);let B=0,se=0,P=0;return Object.values(S).forEach(O=>{O&&(B+=O.activeTaskCount,se+=O.totalTasksCompleted,P+=O.inFlightAgentCount)}),{totalProjects:U,activeProjects:A,erroredProjects:$,totalNodes:J,totalActiveTasks:B,totalCompletedTasks:se,totalInFlightAgents:P}},[e,S]),D=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]),C=i.useMemo(()=>{const U=new Map;return e.forEach(A=>{const $=A.nodeId,T=U.get($);if(T)T.count++;else{const B=c.find(se=>se.id===$)?.name??A._sourceNodeName??"Local";U.set($,{name:B,count:1})}}),Array.from(U.entries()).map(([A,{name:$,count:T}])=>({nodeId:A??null,name:$,count:T}))},[e,c]),_=i.useCallback(U=>{const A=[U.id,...v.filter($=>$!==U.id)].slice(0,3);b(A),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify(A)),s(U)},[s,v]);return n||j&&e.length>0&&Object.keys(S).length===0?t.jsx(TR,{}):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(Ar,{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(Gi,{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(ws,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:M.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(Gs,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:M.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:M.totalCompletedTasks}),t.jsx("span",{className:"project-stat__label",children:"Completed"})]})]}),M.erroredProjects>0&&t.jsxs("div",{className:"project-stat project-stat--error",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Rs,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:M.erroredProjects}),t.jsx("span",{className:"project-stat__label",children:"Errored"})]})]}),M.totalNodes>1&&t.jsxs("div",{className:"project-stat project-stat--nodes",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Wr,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:M.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:D.all})]}),t.jsxs("button",{className:`project-filter-tab ${d==="active"?"active":""}`,onClick:()=>u("active"),children:["Active",t.jsx("span",{className:"project-filter-count",children:D.active})]}),t.jsxs("button",{className:`project-filter-tab ${d==="paused"?"active":""}`,onClick:()=>u("paused"),children:["Paused",t.jsx("span",{className:"project-filter-count",children:D.paused})]}),t.jsxs("button",{className:`project-filter-tab ${d==="errored"?"active":""} ${D.errored>0?"has-errors":""}`,onClick:()=>u("errored"),children:["Errored",t.jsx("span",{className:"project-filter-count",children:D.errored})]})]}),C.length>1&&t.jsxs("div",{className:"project-node-filter",children:[t.jsx(Wr,{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"}),C.map(({nodeId:U,name:A,count:$})=>t.jsxs("option",{value:U??"",children:[A," (",$,")"]},U??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(ol,{size:14}),t.jsxs("select",{value:`${f}-${g}`,onChange:U=>{const[A,$]=U.target.value.split("-");p(A),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(vf,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:N.map(({project:U,health:A})=>{const $=c.find(J=>J.id===U.nodeId),T=$?void 0:U._sourceNodeName;return t.jsx(RR,{project:U,health:A,node:$,nodeNameFallback:T,onSelect:_,onPause:r,onResume:o,onRemove:l},U.id)})}),N.length===0&&t.jsxs("div",{className:"project-overview__no-results",children:[t.jsx(ol,{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 Eu="kb-planning-last-description",_u="kb-subtask-last-description",Mu="kb-mission-last-goal";function LR(e,n){vs(Eu,e,n)}function OR(e){return ss(Eu,e)||""}function Ra(e){Ja(Eu,e)}function FR(e,n){vs(_u,e,n)}function zR(e){return ss(_u,e)||""}function Bc(e){Ja(_u,e)}function UR(e,n){vs(Mu,e,n)}function BR(e){return ss(Mu,e)||""}function Bi(e){Ja(Mu,e)}function HR(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 qR(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 VR(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 ri({entries:e,defaultShowThinking:n=!1}){const[s,a]=i.useState({}),r=VR(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?HR(o):void 0,h=o.question&&m!==void 0?qR(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 sp="fusion-tab-id";function WR(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function va(){if(typeof window>"u")return"server-tab";const e=window.sessionStorage.getItem(sp);if(e)return e;const n=WR();return window.sessionStorage.setItem(sp,n),n}function Gl(e){const n=i.useMemo(()=>va(),[]),[s,a]=i.useState(!1),[r,o]=i.useState(null),[l,c]=i.useState(!1);i.useEffect(()=>{if(!e){a(!1),o(null),c(!1);return}let u=!0;return c(!0),Promise.resolve(y1(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=w1(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=Ni(`/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:gi("/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(k1(e,n)),a(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:d,isLoading:l}}const KR="fusion:ai-session-sync",ip="fusion:ai-session-sync",GR=3e4,JR=6e4;function vi(){return Date.now()}function YR(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function ap(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 QR{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=YR(),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:vi()})}broadcastUpdate(n){const s=n.timestamp??vi();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??vi();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=vi();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=vi();this.releaseTabOwnership(n,s,a),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:a})}broadcastHeartbeat(n){const s=vi();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(KR),this.channel.onmessage=s=>{const a=ap(s.data);a&&this.handleIncomingMessage(a)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==ip||!s.newValue))try{const a=JSON.parse(s.newValue),r=ap(a.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=vi();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},GR)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,a]of this.ownedSessions.entries()){const r=vi();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(ip,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:vi()});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=vi(),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>JR;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 yi=new QR;function lr(){const e=i.useSyncExternalStore(c=>yi.subscribe(c),()=>yi.getSnapshot(),()=>yi.getSnapshot());i.useEffect(()=>{yi.requestSync()},[]);const n=i.useCallback(c=>{yi.broadcastUpdate(c)},[]),s=i.useCallback(c=>{yi.broadcastCompleted(c)},[]),a=i.useCallback((c,d)=>{yi.broadcastLock(c,d)},[]),r=i.useCallback((c,d)=>{yi.broadcastUnlock(c,d)},[]),o=i.useCallback(c=>{yi.broadcastHeartbeat(c)},[]),l=i.useCallback(()=>{yi.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:a,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function XR(e,n){return e&&n?`${e}/${n}`:""}function ZR(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 eT=["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 tT({isOpen:e,onClose:n,onMissionCreated:s,projectId:a,initialGoal:r,resumeSessionId:o}){Mi(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([]),[v,b]=i.useState(null),[k,S]=i.useState(!1),j=i.useRef(!1),[E,y]=i.useState(""),[N,M]=i.useState(!0),[D,C]=i.useState(!1),[_,F]=i.useState(!1),[U,A]=i.useState(!1),$=i.useRef(null),T=i.useRef(null),J=i.useRef(null),B=i.useRef(null),[se,P]=i.useState(o??null),O=i.useMemo(()=>va(),[]),{isLockedByOther:I,takeControl:w,isLoading:Y}=Gl(e?se:null),{activeTabMap:re,broadcastUpdate:le,broadcastCompleted:ve,broadcastLock:de,broadcastUnlock:Fe,broadcastHeartbeat:X}=lr(),{confirm:L}=Qs(),[Q,ne]=i.useState(void 0),[H,z]=i.useState(void 0),[W,we]=i.useState([]),[Z,fe]=i.useState(!0),[Oe,Ve]=i.useState(null),[He,Je]=i.useState([]),[$e,he]=i.useState([]),ue=XR(Q,H);i.useEffect(()=>{(async()=>{try{fe(!0);const Re=await Os();we(Re.models),Je(Re.favoriteProviders),he(Re.favoriteModels)}catch(Re){Ve(_e(Re)||"Failed to load models")}finally{fe(!1)}})()},[]);const Ee=i.useCallback(pe=>{Je(Re=>{const Be=Re,me=Be.includes(pe)?Be.filter(ft=>ft!==pe):[pe,...Be];return Dn({favoriteProviders:me,favoriteModels:$e}).catch(()=>{Je(Be)}),me})},[$e]),je=i.useCallback(pe=>{he(Re=>{const Be=Re,me=Be.includes(pe)?Be.filter(ft=>ft!==pe):[pe,...Be];return Dn({favoriteProviders:He,favoriteModels:me}).catch(()=>{he(Be)}),me})},[He]),xe=i.useCallback((pe,Re)=>{if(!pe||!Re)return"Using default";const Be=W.find(at=>at.provider===pe&&at.id===Re);return Be?`${Be.provider}/${Be.id}`:`${pe}/${Re}`},[W]),Pe=i.useCallback(pe=>{T.current?.close();const Re=XN(pe,a,{onThinking:Be=>{y(at=>at+Be),le({sessionId:pe,status:"generating",needsInput:!1,owningTabId:O,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onQuestion:Be=>{C(!1),F(!1),Bi(a),u({type:"question",sessionId:pe,question:Be}),y(""),S(!0),le({sessionId:pe,status:"awaiting_input",needsInput:!0,owningTabId:O,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onSummary:Be=>{C(!1),F(!1),Bi(a),u({type:"summary",sessionId:pe,summary:Be}),b(Be),y(""),S(!0),le({sessionId:pe,status:"complete",needsInput:!1,owningTabId:O,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onError:Be=>{const at=Be||"Session failed while contacting the AI.";C(!1),F(!1),h(null),u({type:"error",sessionId:pe,errorMessage:at}),y(""),S(!0),J.current=pe,le({sessionId:pe,status:"error",needsInput:!1,owningTabId:O,type:"mission_interview",title:l.trim()||void 0,projectId:a??null}),ve({sessionId:pe,status:"error"})},onComplete:()=>{C(!1),F(!1),J.current=null,ve({sessionId:pe,status:"complete"})},onConnectionStateChange:Be=>{C(Be==="reconnecting")}});T.current=Re},[ve,le,l,a,O]),ie=i.useCallback(async pe=>{const Re=pe??l;if(Re.trim()){h(null),y(""),p([]),x([]),C(!1),u({type:"loading"});try{const{sessionId:Be}=await GN(Re.trim(),a,Q&&H?{modelProvider:Q,modelId:H}:void 0);J.current=Be,P(Be),Bi(a),Pe(Be),p([])}catch(Be){C(!1),h(_e(Be)||"Failed to start interview session"),u({type:"initial"}),J.current=null,P(null)}}},[Pe,l,Q,H,a]);i.useEffect(()=>{e&&d.type==="initial"&&$.current?.focus()},[e,d.type]),i.useEffect(()=>{if(e&&!r&&!o&&!j.current&&d.type==="initial"){const pe=BR(a);pe&&c(pe)}},[e]),i.useEffect(()=>{if(e&&r&&!j.current&&d.type==="initial"){c(r);const pe=setTimeout(()=>{j.current=!0,ie(r)},0);return()=>clearTimeout(pe)}},[e,r,d.type,ie]),i.useEffect(()=>{e||(j.current=!1,C(!1),F(!1),P(null))},[e]),i.useEffect(()=>{if(!e||!o||d.type!=="initial")return;let pe=!1;return ji(o).then(Re=>{if(pe||!Re)return;const Be=Ga(Re.conversationHistory);if(x(Be),P(Re.id),p(Be.map(at=>at.response).filter(at=>!!(at&&typeof at=="object"&&!Array.isArray(at)))),Re.status==="awaiting_input"&&Re.currentQuestion)try{Bi(a);const at=JSON.parse(Re.currentQuestion);J.current=Re.id,S(!0),u({type:"question",sessionId:Re.id,question:at})}catch{h("Failed to restore session question.")}else if(Re.status==="complete"&&Re.result)try{Bi(a);const at=JSON.parse(Re.result);J.current=Re.id,S(!0),b(at),u({type:"summary",sessionId:Re.id,summary:at})}catch{h("Failed to restore session result.")}else Re.status==="generating"?(J.current=Re.id,S(!0),Re.thinkingOutput&&y(Re.thinkingOutput),u({type:"loading"}),Pe(Re.id)):Re.status==="error"&&(J.current=Re.id,S(!0),h(null),u({type:"error",sessionId:Re.id,errorMessage:Re.error??"The session encountered an error."}))}).catch(()=>{pe||h("Failed to resume session.")}),()=>{pe=!0}},[Pe,e,o,d.type,a]),i.useEffect(()=>{if(!e){B.current&&(Fe(B.current,O),B.current=null);return}if(se&&B.current!==se){B.current&&Fe(B.current,O),de(se,O),B.current=se;return}!se&&B.current&&(Fe(B.current,O),B.current=null)},[de,Fe,e,se,O]),i.useEffect(()=>{if(!e||!se||B.current!==se)return;X(O);const pe=setInterval(()=>{X(O)},3e4);return()=>{clearInterval(pe)}},[X,e,se,O]),i.useEffect(()=>()=>{T.current?.close(),T.current=null,B.current&&(Fe(B.current,O),B.current=null)},[Fe,O]),i.useEffect(()=>{if(!e)return;const pe=Re=>{(d.type==="question"||d.type==="summary")&&(Re.preventDefault(),Re.returnValue=""),T.current?.close()};return window.addEventListener("beforeunload",pe),()=>window.removeEventListener("beforeunload",pe)},[e,d]);const Me=i.useCallback(()=>{T.current?.close(),T.current=null,n()},[n]),We=i.useCallback(async()=>{if(l&&UR(l,a),!(k&&!await L({title:"Close Interview",message:"Are you sure you want to close? Your interview progress will be lost.",danger:!0}))){if(T.current?.close(),T.current=null,d.type==="question"||d.type==="summary"||d.type==="error")try{await qf(d.sessionId,a,O)}catch{}c(""),u({type:"initial"}),h(null),p([]),x([]),b(null),y(""),C(!1),F(!1),S(!1),A(!1),ne(void 0),z(void 0),J.current=null,P(null),n()}},[l,k,d,n,a,O,L]);i.useEffect(()=>{if(!e)return;const pe=Re=>{Re.key==="Escape"&&We()};return document.addEventListener("keydown",pe),()=>document.removeEventListener("keydown",pe)},[e,We]);const mt=i.useCallback(async pe=>{if(d.type!=="question")return;const{sessionId:Re}=d;h(null),p(Be=>[...Be,pe]),x(Be=>[...Be,{question:d.question,response:pe}]),u({type:"loading"}),y("");try{Pe(Re),await JN(Re,pe,a,O),S(!0)}catch(Be){T.current?.close(),T.current=null,h(_e(Be)||"Failed to submit response"),u({type:"question",sessionId:Re,question:d.question})}},[d,a,O,Pe]),st=i.useCallback(async()=>{if(d.type!=="error")return;const pe=d.sessionId;h(null),F(!0),y(""),u({type:"loading"}),Pe(pe);try{J.current=pe,P(pe),await YN(pe,a,O)}catch(Re){let Be=Re;if((_e(Re)||"").includes("not in an error state"))try{const me=await ji(pe);if(!me)throw new Error("Failed to refresh interview session.");const ft=Ga(me.conversationHistory);if(x(ft),p(ft.map(Et=>Et.response).filter(Et=>!!(Et&&typeof Et=="object"&&!Array.isArray(Et)))),J.current=me.id,P(me.id),S(!0),me.status==="generating")y(me.thinkingOutput??""),u({type:"loading"}),T.current?.isConnected()||Pe(me.id);else if(me.status==="awaiting_input"){if(!me.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");Bi(a);const Et=JSON.parse(me.currentQuestion);u({type:"question",sessionId:me.id,question:Et}),T.current?.isConnected()||Pe(me.id)}else if(me.status==="complete"){if(!me.result)throw new Error("Interview session is complete but has no result.");Bi(a);const Et=JSON.parse(me.result);b(Et),u({type:"summary",sessionId:me.id,summary:Et})}else me.status==="error"&&u({type:"error",sessionId:me.id,errorMessage:me.error??"Retry failed. Please try again."});C(!1);return}catch(me){Be=me}T.current?.close(),T.current=null,u({type:"error",sessionId:pe,errorMessage:_e(Be)||"Retry failed. Please try again."}),C(!1)}finally{F(!1)}},[Pe,a,O,d]),Ze=i.useCallback(async()=>{if(d.type==="summary"){h(null),A(!0);try{const pe=await QN(d.sessionId,v||void 0,a);s(pe),Bi(a),T.current?.close(),T.current=null,c(""),u({type:"initial"}),h(null),p([]),x([]),b(null),y(""),C(!1),F(!1),S(!1),A(!1),J.current=null,P(null),n()}catch(pe){h(_e(pe)||"Failed to create mission"),A(!1)}}},[d,v,s,n,a]),dt=()=>d.type==="question"?Math.min(f.length+1,6):6,Ae=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",Ue=se?re.get(se):null,kt=Ue&&Ue.tabId!==O,De=!!(kt&&!Ue.stale),be=I&&(!kt||Ue.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:pe=>pe.target===pe.currentTarget&&We(),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(As,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Plan Mission with AI"})]}),t.jsxs("div",{className:"modal-header-actions",children:[Ae&&t.jsx("button",{className:"modal-send-to-background",onClick:Me,title:"Send to background","aria-label":"Send to background",children:t.jsx(io,{size:16})}),t.jsx("button",{className:"modal-close",onClick:We,"aria-label":"Close",children:t.jsx(en,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[m&&t.jsx("div",{className:"form-error planning-error",children:m}),D&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),De&&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(ys,{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:pe=>c(pe.target.value),onKeyDown:pe=>{pe.key==="Enter"&&!pe.shiftKey&&l.trim()&&(pe.preventDefault(),ie())}})]}),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:eT.map((pe,Re)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c(pe),children:pe.length>45?pe.slice(0,45)+"...":pe},Re))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",Z&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(Ns,{id:"mission-interview-modal-model",label:"Planning Model",value:ue,onChange:pe=>{const{provider:Re,modelId:Be}=ZR(pe);ne(Re),z(Be)},models:W,disabled:Z,favoriteProviders:He,onToggleFavorite:Ee,favoriteModels:$e,onToggleModelFavorite:je}),Oe&&t.jsxs("div",{className:"form-hint form-hint-error",children:[Oe," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{fe(!0);const pe=await Os();we(pe.models),Je(pe.favoriteProviders),he(pe.favoriteModels),Ve(null)}catch(pe){Ve(_e(pe)||"Failed to load models")}finally{fe(!1)}})()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${Q&&H?"model-badge-custom":"model-badge-default"}`,children:xe(Q,H)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>ie(),disabled:!l.trim(),children:[t.jsx(As,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),d.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(bt,{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:()=>M(!N),type:"button",children:N?"Hide thinking":"Show thinking"}),N&&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(ri,{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 st(),disabled:_,children:[_?t.jsx(bt,{size:14,className:"spin"}):t.jsx(us,{size:14}),t.jsx("span",{className:"icon-ml-6",children:_?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:We,disabled:_,children:"Cancel"})]})]})]})}),d.type==="question"&&t.jsx(nT,{question:d.question,progress:dt(),historyEntries:g,onSubmit:mt}),d.type==="summary"&&v&&t.jsx(sT,{summary:v,historyEntries:g,onSummaryChange:b,onApprove:Ze,onStartOver:()=>{u({type:"initial"}),S(!1),b(null),p([]),x([]),P(null),T.current?.close(),T.current=null},isCreating:U}),I&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Il,{size:16}),t.jsx("span",{children:be?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),be&&t.jsx("button",{type:"button",onClick:()=>{w()},disabled:Y,className:"btn btn-primary session-lock-take-control",children:Y?"Taking control...":"Take Control"})]})})]})]})}):null}function nT({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(ri,{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(v=>v!==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(en,{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(to,{size:16,className:"icon-ml-4"})]})})]})}function sT({summary:e,historyEntries:n,onSummaryChange:s,onApprove:a,onStartOver:r,isCreating:o}){const[l,c]=i.useState(()=>new Set(e.milestones.map((j,E)=>E))),[d,u]=i.useState(()=>{const j=new Set;return e.milestones.forEach((E,y)=>{E.slices.forEach((N,M)=>j.add(`${y}-${M}`))}),j}),m=j=>{c(E=>{const y=new Set(E);return y.has(j)?y.delete(j):y.add(j),y})},h=j=>{u(E=>{const y=new Set(E);return y.has(j)?y.delete(j):y.add(j),y})},f=(j,E)=>{const y=[...e.milestones];y[j]={...y[j],...E},s({...e,milestones:y})},p=(j,E,y)=>{const N=[...e.milestones],M=[...N[j].slices];M[E]={...M[E],...y},N[j]={...N[j],slices:M},s({...e,milestones:N})},g=(j,E,y,N)=>{const M=[...e.milestones],D=[...M[j].slices],C=[...D[E].features];C[y]={...C[y],...N},D[E]={...D[E],features:C},M[j]={...M[j],slices:D},s({...e,milestones:M})},x=j=>{const E=e.milestones.filter((y,N)=>N!==j);s({...e,milestones:E})},v=(j,E)=>{const y=[...e.milestones];y[j]={...y[j],slices:y[j].slices.filter((N,M)=>M!==E)},s({...e,milestones:y})},b=(j,E,y)=>{const N=[...e.milestones],M=[...N[j].slices];M[E]={...M[E],features:M[E].features.filter((D,C)=>C!==y)},N[j]={...N[j],slices:M},s({...e,milestones:N})},k=(j,E)=>{const y=[...e.milestones],N=[...y[j].slices];N[E]={...N[E],features:[...N[E].features,{title:"New feature",description:""}]},y[j]={...y[j],slices:N},s({...e,milestones:y})},S=e.milestones.reduce((j,E)=>j+E.slices.reduce((y,N)=>y+N.features.length,0),0);return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(ri,{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, ",S," features. Review and edit before approving."]})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Title"}),t.jsx("input",{type:"text",className:"form-input",value:e.missionTitle||"",onChange:j=>s({...e,missionTitle:j.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Description"}),t.jsx("textarea",{className:"planning-textarea",rows:3,value:e.missionDescription||"",onChange:j=>s({...e,missionDescription:j.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Roadmap"}),t.jsx("div",{className:"roadmap-list",children:e.milestones.map((j,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(Un,{size:16,className:"icon-text-secondary"}),t.jsx(ca,{size:16,className:"icon-milestone"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:j.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:j.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:j.verification||"",onChange:y=>f(E,{verification:y.target.value})})]}),j.slices.map((y,N)=>{const M=`${E}-${N}`;return t.jsxs("div",{className:"roadmap-slice-card",children:[t.jsxs("div",{className:"roadmap-slice-header",onClick:()=>h(M),children:[d.has(M)?t.jsx(un,{size:14,className:"icon-text-secondary"}):t.jsx(Un,{size:14,className:"icon-text-secondary"}),t.jsx(bd,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:y.title,onChange:D=>p(E,N,{title:D.target.value}),onClick:D=>D.stopPropagation()}),j.slices.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:D=>{D.stopPropagation(),v(E,N)},title:"Remove slice",children:t.jsx(Sn,{size:12,className:"icon-text-secondary"})})]}),d.has(M)&&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:D=>p(E,N,{verification:D.target.value})})]}),y.features.map((D,C)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(cd,{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:D.title,onChange:_=>g(E,N,C,{title:_.target.value})}),D.description&&t.jsx("p",{className:"roadmap-feature-text",children:D.description}),D.acceptanceCriteria&&t.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",D.acceptanceCriteria]})]}),t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>b(E,N,C),title:"Remove feature",children:t.jsx(Sn,{size:12,className:"icon-text-secondary"})})]},C)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>k(E,N),children:[t.jsx(Cn,{size:12}),"Add Feature"]})]})]},N)})]})]},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(bt,{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 iT=30,aT=16,rT=16;function oT(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let il=null;function Rb(){return il===null&&(il=window.visualViewport?.height??window.innerHeight),il}function lT(e){const n=Rb();e>n&&(il=e)}function cT(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 dT(){if(typeof window>"u"||!window.visualViewport)return{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0};const e=window.visualViewport,n=cT(document.activeElement),s=e.offsetTop;n||lT(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=Rb(),o=Math.max(0,r-e.offsetTop-e.height);if(o>=iT&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};if(o>=aT&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};const l=Math.max(0,r-e.height);return n&&l>=rT?{overlap:0,open:!0,vvHeight:e.height,vvOffsetTop:s}:{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0}}function ya({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||!oT()){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 h=dT();s(h.overlap),r(h.vvHeight),l(h.vvOffsetTop),d(h.open)};return m(),u.addEventListener("resize",m),u.addEventListener("scroll",m),document.addEventListener("focusin",m),document.addEventListener("focusout",m),()=>{u.removeEventListener("resize",m),u.removeEventListener("scroll",m),document.removeEventListener("focusin",m),document.removeEventListener("focusout",m),s(0),r(null),l(0),d(!1)}},[e]),{keyboardOverlap:n,viewportHeight:a,viewportOffsetTop:o,keyboardOpen:c}}function uT({isOpen:e,onClose:n,onApplied:s,targetType:a,targetId:r,targetTitle:o,missionContext:l,projectId:c,resumeSessionId:d}){const u=oi();Mi(e);const{keyboardOverlap:m,viewportHeight:h,viewportOffsetTop:f,keyboardOpen:p}=ya({enabled:u==="mobile"}),g=p?{"--keyboard-overlap":`${m}px`,"--vv-offset-top":`${f}px`,...h!==null?{"--vv-height":`${h}px`}:{}}:{},[x,v]=i.useState({type:"initial"}),[b,k]=i.useState(null),[S,j]=i.useState([]),[E,y]=i.useState([]),[N,M]=i.useState(null),[D,C]=i.useState(""),[_,F]=i.useState(!0),[U,A]=i.useState(!1),[$,T]=i.useState(!1),J=i.useRef(null),B=i.useRef(null),se=i.useRef(null),P=i.useRef(null),[O,I]=i.useState(null),w=i.useMemo(()=>va(),[]);Gl(e?O:null);const{activeTabMap:Y,broadcastUpdate:re,broadcastCompleted:le,broadcastLock:ve,broadcastUnlock:de,broadcastHeartbeat:Fe}=lr(),X=a==="milestone"?ZN:i1,L=a==="milestone"?e1:a1,Q=a==="milestone"?t1:r1,ne=a==="milestone"?n1:o1,H=a==="milestone"?s1:l1,z=a==="milestone"?"Milestone":"Slice",W=a==="milestone"?"milestone_interview":"slice_interview",we=i.useCallback(Pe=>{B.current?.close();const ie=Q(Pe,c,{onThinking:Me=>{C(We=>We+Me),re({sessionId:Pe,status:"generating",needsInput:!1,owningTabId:w,type:W,title:o,projectId:c??null})},onQuestion:Me=>{A(!1),Z(),v({type:"question",sessionId:Pe,question:Me}),C(""),re({sessionId:Pe,status:"awaiting_input",needsInput:!0,owningTabId:w,type:W,title:o,projectId:c??null})},onSummary:Me=>{A(!1),Z(),v({type:"summary",sessionId:Pe,summary:Me}),M(Me),C(""),re({sessionId:Pe,status:"complete",needsInput:!1,owningTabId:w,type:W,title:o,projectId:c??null})},onError:Me=>{const We=Me||"Session failed while contacting the AI.";A(!1),k(null),v({type:"error",sessionId:Pe,errorMessage:We}),C(""),se.current=Pe,re({sessionId:Pe,status:"error",needsInput:!1,owningTabId:w,type:W,title:o,projectId:c??null}),le({sessionId:Pe,status:"error"})},onComplete:()=>{A(!1),se.current=null,le({sessionId:Pe,status:"complete"})},onConnectionStateChange:Me=>{A(Me==="reconnecting")}});B.current=ie},[le,re,Q,W,c,w,o]),Z=()=>{M(null),j([]),y([]),C("")},fe=i.useCallback(async()=>{k(null),Z(),A(!1),v({type:"loading"});try{const{sessionId:Pe}=await X(r,c);se.current=Pe,I(Pe),we(Pe)}catch(Pe){A(!1),k(_e(Pe)||`Failed to start ${z.toLowerCase()} interview`),v({type:"initial"}),se.current=null,I(null)}},[we,c,X,r,z]),Oe=i.useCallback(async()=>{k(null),T(!0);try{await H(r,c),s(),v({type:"applied"})}catch(Pe){k(_e(Pe)||`Failed to skip ${z.toLowerCase()} interview`),T(!1)}},[s,c,H,r,z]);i.useEffect(()=>{e&&x.type==="initial"&&J.current?.focus()},[e,x.type]),i.useEffect(()=>{if(!e||!d||x.type!=="initial")return;let Pe=!1;return ji(d).then(ie=>{if(Pe||!ie)return;const Me=Ga(ie.conversationHistory);if(y(Me),I(ie.id),j(Me.map(We=>We.response).filter(We=>!!(We&&typeof We=="object"&&!Array.isArray(We)))),ie.status==="awaiting_input"&&ie.currentQuestion)try{const We=JSON.parse(ie.currentQuestion);se.current=ie.id,v({type:"question",sessionId:ie.id,question:We})}catch{k("Failed to restore session question.")}else if(ie.status==="complete"&&ie.result)try{const We=JSON.parse(ie.result);se.current=ie.id,M(We),v({type:"summary",sessionId:ie.id,summary:We})}catch{k("Failed to restore session result.")}else ie.status==="generating"?(se.current=ie.id,ie.thinkingOutput&&C(ie.thinkingOutput),v({type:"loading"}),we(ie.id)):ie.status==="error"&&(se.current=ie.id,k(null),v({type:"error",sessionId:ie.id,errorMessage:ie.error??"The session encountered an error."}))}).catch(()=>{Pe||k("Failed to resume session.")}),()=>{Pe=!0}},[we,e,d,x.type]),i.useEffect(()=>{e||(A(!1),I(null))},[e]),i.useEffect(()=>{if(!(!e||!O)){if(P.current!==O){P.current&&de(P.current,w),ve(O,w),P.current=O;return}!O&&P.current&&(de(P.current,w),P.current=null)}},[ve,de,e,O,w]),i.useEffect(()=>{if(!e||!O||P.current!==O)return;Fe(w);const Pe=setInterval(()=>{Fe(w)},3e4);return()=>{clearInterval(Pe)}},[Fe,e,O,w]),i.useEffect(()=>()=>{B.current?.close(),B.current=null,P.current&&(de(P.current,w),P.current=null)},[de,w]);const Ve=i.useCallback(()=>{B.current?.close(),B.current=null,n()},[n]),He=i.useCallback(async()=>{B.current?.close(),B.current=null,Z(),v({type:"initial"}),k(null),se.current=null,I(null),n()},[n]),Je=i.useCallback(async Pe=>{if(x.type!=="question")return;const{sessionId:ie}=x;k(null),j(Me=>[...Me,Pe]),y(Me=>[...Me,{question:x.question,response:Pe}]),v({type:"loading"}),C("");try{we(ie),await L(ie,Pe,c,w)}catch(Me){B.current?.close(),B.current=null,k(_e(Me)||"Failed to submit response"),v({type:"question",sessionId:ie,question:x.question})}},[we,c,L,w,x]),$e=i.useCallback(async()=>{if(x.type==="summary"){k(null),T(!0);try{await ne(x.sessionId,N||void 0,c),s(),v({type:"applied"})}catch(Pe){k(_e(Pe)||"Failed to apply interview results"),T(!1)}}},[ne,N,s,c,x]),he=()=>x.type==="question"?Math.min(S.length+1,6):6,ue=x.type==="loading"||x.type==="question"||x.type==="summary"||x.type==="error",Ee=O?Y.get(O):null,xe=!!(Ee&&Ee.tabId!==w&&!Ee.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Pe=>Pe.target===Pe.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(ys,{size:20,className:"icon-triage"}),t.jsxs("h3",{children:["Plan ",z,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[ue&&t.jsx("button",{className:"modal-send-to-background",onClick:Ve,title:"Send to background","aria-label":"Send to background",children:t.jsx(io,{size:16})}),t.jsx("button",{className:"modal-close",onClick:He,"aria-label":"Close",children:t.jsx(en,{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…"}),xe&&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(ys,{size:32,className:"icon-triage-lg"}),t.jsxs("h4",{children:["Refine ",z," 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 fe(),children:[t.jsx(ys,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void Oe(),disabled:$,children:[$?t.jsx(bt,{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(bt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:D?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>F(!_),type:"button",children:_?"Hide thinking":"Show thinking"}),_&&D&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:D})})]})]}),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(ri,{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(mT,{question:x.question,progress:he(),historyEntries:E,onSubmit:Je}),x.type==="summary"&&N&&t.jsx(hT,{summary:N,historyEntries:E,onSummaryChange:M,onApply:$e,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:[z," 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 mT({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(ri,{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(v=>v!==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(en,{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(to,{size:16,className:"icon-ml-4"})]})})]})}function hT({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(ri,{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(Un,{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(bt,{size:16,className:"spin"}):null,"Apply"]}),t.jsx("button",{className:"btn",onClick:r,disabled:o,children:"Cancel"})]})]})}const rp=300,zo=220,Uo=560,op="fusion:mission-sidebar-width",jr={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)"}},lp={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)"}},cp={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)"}},Bo={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)"}},Ho={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)"}},qo={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)"}},dp={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)"}},pT=3;function fT(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function up({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 mp(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const hp={title:"",description:"",status:"planning",autopilotEnabled:!1},Hc={title:"",description:"",status:"planning",dependencies:[]},qc={title:"",description:"",status:"pending"},Vc={title:"",description:"",acceptanceCriteria:"",status:"defined"},gT=3600*1e3;function jl(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 bT(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=gT,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 xT(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 vT(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 Wc(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 Tb=["feature_triaged","feature_completed"],Ib=["slice_activated","slice_completed","milestone_completed"],$b=["mission_started","mission_paused","mission_resumed","mission_completed"],Db=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function pp(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return $b.includes(e);case"tasks":return Tb.includes(e);case"slices":return Ib.includes(e);case"autopilot":return Db.includes(e);default:return!0}}function yT(e){return e==="error"||e==="warning"?"mission-event__type--error":$b.includes(e)?"mission-event__type--state":Tb.includes(e)?"mission-event__type--task":Ib.includes(e)?"mission-event__type--slice":Db.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function wT(e){return e.replace(/_/g," ")}function kT(e,n){return n?e==="watching"?`Watching since ${jl(n)}`:`Last activation ${jl(n)}`:null}function jT({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),[v,b]=i.useState(!0),[k,S]=i.useState(!1),j=oi()==="mobile",[E,y]=i.useState(()=>{if(typeof window>"u")return rp;const q=window.localStorage.getItem(op),ke=q?Number(q):NaN;return Number.isFinite(ke)?Math.max(zo,Math.min(Uo,ke)):rp}),N=i.useCallback(q=>{try{window.localStorage.setItem(op,String(q))}catch{}},[]),M=i.useCallback(q=>{if(j)return;q.preventDefault(),q.stopPropagation();const ke=q.currentTarget;typeof ke.setPointerCapture=="function"&&ke.setPointerCapture(q.pointerId);const qe=q.clientX,Mt=E;let dn=Mt;document.body.style.userSelect="none";const Yt=Xe=>{const nt=Xe.clientX-qe,Ot=Math.max(zo,Math.min(Uo,Mt+nt));dn=Ot,y(Ot)},Nn=Xe=>{typeof ke.releasePointerCapture=="function"&&ke.releasePointerCapture(Xe.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",Yt),document.removeEventListener("pointerup",Nn),N(dn)};document.addEventListener("pointermove",Yt),document.addEventListener("pointerup",Nn)},[j,N,E]),D=i.useCallback(q=>{if(j||q.key!=="ArrowLeft"&&q.key!=="ArrowRight")return;q.preventDefault();const ke=q.shiftKey?50:10,qe=q.key==="ArrowLeft"?-ke:ke,Mt=Math.max(zo,Math.min(Uo,E+qe));y(Mt),N(Mt)},[j,N,E]),[C,_]=i.useState(!1),[F,U]=i.useState(null),[A,$]=i.useState(hp),[T,J]=i.useState(!1),[B,se]=i.useState(new Set),[P,O]=i.useState(new Set),[I,w]=i.useState(null),[Y,re]=i.useState(Hc),[le,ve]=i.useState(!1),[de,Fe]=i.useState(null),[X,L]=i.useState(qc),[Q,ne]=i.useState(!1),[H,z]=i.useState(null),[W,we]=i.useState(null),[Z,fe]=i.useState(Vc),[Oe,Ve]=i.useState(!1),[He,Je]=i.useState(null),[$e,he]=i.useState(null),[ue,Ee]=i.useState(""),[je,xe]=i.useState(!1),[Pe,ie]=i.useState([]),[Me,We]=i.useState(void 0),mt=Me??c,[st,Ze]=i.useState(null),[dt,Ae]=i.useState(null),[Ue,kt]=i.useState(null);i.useEffect(()=>{h&&mt&&xe(!0)},[h,mt]),i.useEffect(()=>{if(!h||mt)return;let q=!1;return nu(r).then(ke=>{if(q)return;const qe=ke.filter(Mt=>Mt.type==="mission_interview"&&(Mt.status==="awaiting_input"||Mt.status==="error"));ie(qe)}).catch(ke=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",ke)}),()=>{q=!0}},[h,r,mt]),i.useEffect(()=>{if(!h||!u)return;let q=!1;return ji(u).then(ke=>{if(!(q||!ke))try{const qe=JSON.parse(ke.inputPayload||"{}");qe.targetId&&qe.targetType&&Ze({type:qe.targetType,id:qe.targetId,title:qe.targetTitle||ke.title,resumeSessionId:u})}catch{Ze({type:"milestone",id:"",title:ke.title,resumeSessionId:u})}}).catch(ke=>{q||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",ke),m?.())}),()=>{q=!0}},[h,u,m]);const[De,be]=i.useState(null),[pe,Re]=i.useState(new Map),[Be,at]=i.useState(null),[me,ft]=i.useState({title:"",assertion:"",status:"pending"}),[Et,jt]=i.useState(!1),[$t,Ft]=i.useState(null),[Rt,It]=i.useState(new Map),[Vt,Qt]=i.useState(new Set),[Jt,on]=i.useState(new Set),[Kt,qt]=i.useState(null),[kn,nn]=i.useState(new Map),[Xt,Gt]=i.useState(null),[ln,ye]=i.useState(null),[Le,ae]=i.useState(!0),[Te,Ne]=i.useState(new Set),[ee,Ie]=i.useState(new Map),[St,pt]=i.useState(null),[Dt,Ut]=i.useState(new Map),[Ce,et]=i.useState(null),[tt,Lt]=i.useState(new Map),[Zt,sn]=i.useState(new Map),[At,cn]=i.useState("structure"),[Tn,En]=i.useState([]),bn=i.useRef([]),In=i.useRef([]),ge=i.useRef(null),ut=i.useRef(null),xn=i.useRef("structure"),oe=i.useRef("all"),[ct,rt]=i.useState(!1),[wt,ot]=i.useState(0),[vt,Wt]=i.useState("all"),[an,pn]=i.useState(new Set),Hn=i.useRef(null),Mn=i.useRef(null);In.current=f,ge.current=g,ut.current=Xt,xn.current=At,oe.current=vt;const Qn=i.useCallback((q="auto")=>{const ke=Mn.current;if(ke&&typeof ke.scrollIntoView=="function"){ke.scrollIntoView({block:"end",behavior:q});return}const qe=Hn.current;qe&&(qe.scrollTop=qe.scrollHeight)},[]),ms=i.useCallback(()=>{const q=Hn.current;return q?q.scrollHeight-q.scrollTop-q.clientHeight<=100:!0},[]),Xn=i.useCallback(async q=>{if(q.length===0){sn(new Map);return}const ke=await wN(r);sn(qe=>{const Mt=new Map(qe);for(const[dn,Yt]of Object.entries(ke))xT(Yt)&&Mt.set(dn,Yt);return Mt})},[r]),mn=i.useCallback(async()=>{try{b(!0);const q=await gN(r);p(q),Xn(q)}catch(q){a(_e(q)||"Failed to load missions","error")}finally{b(!1)}},[a,r,Xn]),Pt=i.useCallback(async q=>{try{S(!0);const ke=await Hf(q,r);if(!ke||!Array.isArray(ke.milestones)){S(!1);return}if(x(ke),ke.milestones.length>0){const qe=ke.milestones[0].id;Gt(qe),ae(!0),se(new Set([qe])),nc(qe,r).then(Mt=>{Re(dn=>{const Yt=new Map(dn);return Yt.set(qe,Mt),Yt})}).catch(()=>{}),sc(qe,r).then(Mt=>{nn(dn=>{const Yt=new Map(dn);return Yt.set(qe,Mt),Yt})}).catch(()=>{}),ke.milestones[0].slices.length>0&&O(new Set([ke.milestones[0].slices[0].id]))}else Gt(null),ye(null)}catch(ke){a(_e(ke)||"Failed to load mission details","error")}finally{S(!1)}},[a,r]);i.useEffect(()=>{if(!h||!Xt){ye(null);return}let q=!1;return ye(null),im(Xt,r).then(ke=>{if(!q){if(!Wc(ke)){ye(null);return}ye(ke),nn(qe=>{const Mt=new Map(qe);return Mt.set(Xt,ke.rollup),Mt})}}).catch(()=>{q||ye(null)}),()=>{q=!0}},[h,Xt,r]),i.useEffect(()=>{ae(!0)},[Xt]);const is=i.useCallback(q=>{!q||q!==ut.current||im(q,r).then(ke=>{ut.current!==q||!Wc(ke)||(ye(ke),nn(qe=>{const Mt=new Map(qe);return Mt.set(q,ke.rollup),Mt}))}).catch(()=>{})},[r]),Gn=i.useCallback(async(q,ke)=>{const qe=ke?.append??!1,Mt=qe?bn.current.length:0;qe||(rt(!0),pn(new Set));try{const dn=await yN(q,{limit:50,offset:Mt,eventType:void 0},r),Yt=dn.events.filter(Nn=>pp(Nn.eventType,vt));En(Nn=>{if(!qe)return Yt;const Xe=new Set(Nn.map(Ot=>Ot.id)),nt=[...Nn];for(const Ot of Yt)Xe.has(Ot.id)||nt.push(Ot);return nt}),ot(dn.total),qe||requestAnimationFrame(()=>{Qn("auto")})}catch(dn){a(_e(dn)||"Failed to load mission activity","error")}finally{qe||rt(!1)}},[a,vt,r,Qn]);i.useEffect(()=>{bn.current=Tn},[Tn]),i.useEffect(()=>{h&&(mn(),x(null),Gt(null),ye(null),En([]),ot(0),cn("structure"),Wt("all"),pn(new Set))},[h,mn]);const K=i.useRef(null);i.useEffect(()=>{h&&d&&K.current!==d&&f.length>0&&(K.current=d,Pt(d))},[h,d,f,Pt]),i.useEffect(()=>{h||(K.current=null)},[h]);const Ke=i.useRef(!1);i.useEffect(()=>{!h||!n||j||v||Ke.current||g||d||f.length!==0&&(Ke.current=!0,Pt(f[0].id))},[h,n,j,v,f,g,d,Pt]),i.useEffect(()=>{h||(Ke.current=!1)},[h]),i.useEffect(()=>{!h||!g||At!=="activity"||Gn(g.id)},[At,h,Gn,g,vt]),i.useEffect(()=>{if(!h||typeof EventSource>"u")return;const q=new URLSearchParams;r&&q.set("projectId",r);const ke=`/api/events${q.size>0?`?${q.toString()}`:""}`,qe=()=>{Xn(In.current)},Mt=fs=>{qe();const gs=fs;if(gs.data)try{const wn=JSON.parse(gs.data);wn?.id&&p(ta=>ta.map(ei=>ei.id===wn.id?{...ei,...wn}:ei))}catch{}ge.current&&Pt(ge.current.id)},dn=fs=>{qe(),ge.current&&Pt(ge.current.id)},Yt=()=>{qe(),ge.current&&Pt(ge.current.id)},Nn=fs=>{qe(),ge.current&&Pt(ge.current.id)},Xe=fs=>{const gs=fs;if(gs.data)try{const wn=JSON.parse(gs.data);wn&&wn.featureId&&(Xs(wn.featureId),li(wn.featureId),wn.milestoneId&&is(wn.milestoneId))}catch{}},nt=fs=>{const gs=fs;if(gs.data)try{const wn=JSON.parse(gs.data);wn&&wn.featureId&&(Xs(wn.featureId),li(wn.featureId),wn.milestoneId&&is(wn.milestoneId),ge.current&&Pt(ge.current.id))}catch{}},Ot=fs=>{const gs=fs;if(gs.data)try{const wn=JSON.parse(gs.data);wn&&wn.milestoneId&&(rs(wn.milestoneId),is(wn.milestoneId))}catch{}},_n=fs=>{const gs=fs;if(gs.data)try{const wn=JSON.parse(gs.data);wn&&wn.milestoneId&&(Fn(wn.milestoneId),rs(wn.milestoneId),is(wn.milestoneId))}catch{}};return gi(ke,{events:{"mission:updated":Mt,"slice:updated":dn,"feature:updated":Yt,"milestone:updated":Nn,"mission:event":fs=>{qe();const gs=ge.current;if(!gs||xn.current!=="activity")return;const wn=ms(),ta=fs;if(ta.data)try{const ei=JSON.parse(ta.data);if(!vT(ei)||ei.missionId!==gs.id||!pp(ei.eventType,oe.current))return;En(Ri=>{const Yl=Ri.filter(Ql=>Ql.id!==ei.id);return[ei,...Yl].slice(0,100)}),ot(Ri=>Ri+1),wn&&requestAnimationFrame(()=>{const Ri=Hn.current;Ri&&(Ri.scrollTop=0)})}catch{}},"validator-run:started":Xe,"validator-run:completed":nt,"milestone:validation:updated":Ot,"assertion:created":_n,"assertion:updated":_n,"assertion:deleted":_n,"assertion:linked":_n,"assertion:unlinked":_n,"fix-feature:created":fs=>{const gs=fs;if(gs.data)try{const wn=JSON.parse(gs.data);if(wn&&wn.sourceFeatureId){Xs(wn.sourceFeatureId);const ta=wn?.feature?.sliceId,ei=ge.current;if(ta&&ei){const Ri=ei.milestones.find(Yl=>Yl.slices.some(Ql=>Ql.id===ta));Ri&&is(Ri.id)}ge.current&&Pt(ge.current.id)}}catch{}}}})},[h,ms,Pt,Xn,r,is]);const Ye=i.useCallback(q=>{U(q.id),_(!1),$({title:q.title,description:q.description||"",status:q.status,autopilotEnabled:q.autopilotEnabled??!1})},[]),ht=i.useCallback(()=>{U(null),_(!1),$(hp)},[]),Nt=i.useCallback(async()=>{if(!A.title.trim()){a("Mission title is required","error");return}try{if(J(!0),C)await bN({title:A.title.trim(),description:A.description.trim()||void 0,autopilotEnabled:A.autopilotEnabled},r),a("Mission created","success");else if(F){const q={title:A.title.trim(),description:A.description.trim()||void 0,status:A.status,autopilotEnabled:A.autopilotEnabled};A.autopilotEnabled&&(q.autoAdvance=!0),await xN(F,q,r),a("Mission updated","success"),g?.id===F&&await Pt(F)}await mn(),ht()}catch(q){a(_e(q)||"Failed to save mission","error")}finally{J(!1)}},[A,C,F,a,mn,Pt,g,ht,r]),_t=i.useCallback(async q=>{try{await vN(q,r),a("Mission deleted","success"),g?.id===q&&x(null),await mn(),be(null)}catch(ke){a(_e(ke)||"Failed to delete mission","error")}},[a,mn,g,r]),zt=i.useCallback(()=>{ve(!0),w(null),re(Hc)},[]),Jn=i.useCallback(q=>{w(q.id),ve(!1),re({title:q.title,description:q.description||"",status:q.status,dependencies:q.dependencies})},[]),as=i.useCallback(()=>{w(null),ve(!1),re(Hc)},[]),ce=i.useCallback(async()=>{if(!Y.title.trim()){a("Milestone title is required","error");return}try{J(!0),le&&g?(await kN(g.id,{title:Y.title.trim(),description:Y.description.trim()||void 0,dependencies:Y.dependencies},r),a("Milestone created","success")):I&&(await jN(I,{title:Y.title.trim(),description:Y.description.trim()||void 0,status:Y.status,dependencies:Y.dependencies},r),a("Milestone updated","success")),await Pt(g.id),as()}catch(q){a(_e(q)||"Failed to save milestone","error")}finally{J(!1)}},[Y,le,I,g,a,Pt,as,A.title,r]),Ge=i.useCallback(async q=>{try{await NN(q,r),a("Milestone deleted","success"),await Pt(g.id),be(null)}catch(ke){a(_e(ke)||"Failed to delete milestone","error")}},[a,Pt,g,r]),lt=i.useCallback(q=>{Gt(q),ae(!0),se(ke=>{const qe=new Set(ke);return!qe.has(q)?(qe.add(q),nc(q,r).then(dn=>{Re(Yt=>{const Nn=new Map(Yt);return Nn.set(q,dn),Nn})}).catch(()=>{}),sc(q,r).then(dn=>{nn(Yt=>{const Nn=new Map(Yt);return Nn.set(q,dn),Nn})}).catch(()=>{})):qe.delete(q),qe})},[r]),tn=i.useCallback(q=>{z(q),ne(!0),Fe(null),L(qc)},[]),G=i.useCallback(q=>{Fe(q.id),ne(!1),L({title:q.title,description:q.description||"",status:q.status})},[]),Se=i.useCallback(()=>{Fe(null),ne(!1),z(null),L(qc)},[]),it=i.useCallback(async()=>{if(!X.title.trim()){a("Slice title is required","error");return}try{J(!0),Q&&H?(await SN(H,{title:X.title.trim(),description:X.description.trim()||void 0},r),a("Slice created","success")):de&&(await CN(de,{title:X.title.trim(),description:X.description.trim()||void 0,status:X.status},r),a("Slice updated","success")),await Pt(g.id),Se()}catch(q){a(_e(q)||"Failed to save slice","error")}finally{J(!1)}},[X,Q,de,H,g,a,Pt,Se,r]),Ct=i.useCallback(async q=>{try{await EN(q,r),a("Slice deleted","success"),await Pt(g.id),be(null)}catch(ke){a(_e(ke)||"Failed to delete slice","error")}},[a,Pt,g,r]),Tt=i.useCallback(async q=>{try{await _N(q,r),a("Slice activated","success"),await Pt(g.id)}catch(ke){a(_e(ke)||"Failed to activate slice","error")}},[a,Pt,g,r]),An=i.useCallback(q=>{O(ke=>{const qe=new Set(ke);return qe.has(q)?qe.delete(q):qe.add(q),qe})},[]),vn=i.useCallback(q=>{Je(q),Ve(!0),we(null),fe(Vc)},[]),yn=i.useCallback(q=>{we(q.id),Ve(!1),fe({title:q.title,description:q.description||"",acceptanceCriteria:q.acceptanceCriteria||"",status:q.status})},[]),fn=i.useCallback(()=>{we(null),Ve(!1),Je(null),fe(Vc)},[]),Ln=i.useCallback(async()=>{if(!Z.title.trim()){a("Feature title is required","error");return}try{J(!0),Oe&&He?(await MN(He,{title:Z.title.trim(),description:Z.description.trim()||void 0,acceptanceCriteria:Z.acceptanceCriteria.trim()||void 0},r),a("Feature created","success")):W&&(await AN(W,{title:Z.title.trim(),description:Z.description.trim()||void 0,acceptanceCriteria:Z.acceptanceCriteria.trim()||void 0,status:Z.status},r),a("Feature updated","success")),await Pt(g.id),fn()}catch(q){a(_e(q)||"Failed to save feature","error")}finally{J(!1)}},[Z,Oe,W,He,g,a,Pt,fn,r]),Zn=i.useCallback(async q=>{try{await PN(q,r),a("Feature deleted","success"),await Pt(g.id),be(null)}catch(ke){a(_e(ke)||"Failed to delete feature","error")}},[a,Pt,g,r]),hs=i.useCallback(async()=>{if(!$e||!ue.trim()){a("Task ID is required","error");return}try{await RN($e,ue.trim(),r),a("Feature linked to task","success"),await Pt(g.id),he(null),Ee("")}catch(q){a(_e(q)||"Failed to link feature to task","error")}},[$e,ue,a,Pt,g,r]),On=i.useCallback(async q=>{try{await TN(q,r),a("Feature unlinked from task","success"),await Pt(g.id)}catch(ke){a(_e(ke)||"Failed to unlink feature","error")}},[a,Pt,g,r]),$n=i.useCallback(async q=>{try{J(!0),await IN(q,void 0,void 0,r),a("Feature triaged — task created","success"),await Pt(g.id)}catch(ke){a(_e(ke)||"Failed to triage feature","error")}finally{J(!1)}},[a,Pt,g,r]),Pn=i.useCallback(async q=>{kt(q);try{const ke=await c1(q,r);Ae({featureId:q,enrichedDescription:ke.description})}catch{await $n(q)}finally{kt(null)}},[$n,r]),ps=i.useCallback(async()=>{dt&&(Ae(null),await $n(dt.featureId))},[$n,dt]),qn=i.useCallback(()=>{Ae(null)},[]),es=i.useCallback(async q=>{try{J(!0);const ke=await $N(q,r);a(`Triaged ${ke.count} feature${ke.count!==1?"s":""}`,"success"),await Pt(g.id)}catch(ke){a(_e(ke)||"Failed to triage slice features","error")}finally{J(!1)}},[a,Pt,g,r]),Fn=i.useCallback(async q=>{try{const ke=await nc(q,r);Re(qe=>{const Mt=new Map(qe);return Mt.set(q,ke),Mt})}catch{}},[r]),rs=i.useCallback(async q=>{try{const ke=await sc(q,r);nn(qe=>{const Mt=new Map(qe);return Mt.set(q,ke),Mt})}catch{}},[r]),ks=i.useCallback(async q=>{if(!me.title.trim()||!me.assertion.trim()){a("Title and assertion text are required","error");return}try{J(!0),await DN(q,{title:me.title.trim(),assertion:me.assertion.trim(),status:me.status},r),a("Assertion created","success"),await Fn(q),await rs(q),jt(!1),ft({title:"",assertion:"",status:"pending"})}catch(ke){a(_e(ke)||"Failed to create assertion","error")}finally{J(!1)}},[me,a,Fn,rs,r]),os=i.useCallback(q=>{at(q.id),ft({title:q.title,assertion:q.assertion,status:q.status})},[]),xs=i.useCallback(()=>{at(null),jt(!1),ft({title:"",assertion:"",status:"pending"})},[]),qs=i.useCallback(async(q,ke)=>{if(!me.title.trim()||!me.assertion.trim()){a("Title and assertion text are required","error");return}try{J(!0),await LN(q,{title:me.title.trim(),assertion:me.assertion.trim(),status:me.status},r),a("Assertion updated","success"),await Fn(ke),await rs(ke),xs()}catch(qe){a(_e(qe)||"Failed to update assertion","error")}finally{J(!1)}},[me,a,Fn,rs,xs,r]),Fs=i.useCallback(async q=>{try{const ke=await zN(q,r);It(qe=>{const Mt=new Map(qe);return Mt.set(q,ke),Mt})}catch{}},[r]),wa=i.useCallback(async q=>{const ke=$t!==q;Ft(qe=>qe===q?null:q),ke&&await Fs(q)},[$t,Fs]),ka=i.useCallback(q=>{Ft(q),Fs(q),requestAnimationFrame(()=>{const ke=document.querySelector(`[data-mission-assertion-id="${q}"]`);ke instanceof HTMLElement&&typeof ke.scrollIntoView=="function"&&ke.scrollIntoView({behavior:"smooth",block:"center"})})},[Fs]),cr=i.useCallback(async(q,ke)=>{try{Qt(qe=>new Set(qe).add(ke)),await ON(q,ke,r),a("Feature linked to assertion","success"),await Fs(ke),qt(null)}catch(qe){a(_e(qe)||"Failed to link feature","error")}finally{Qt(qe=>{const Mt=new Set(qe);return Mt.delete(ke),Mt})}},[a,Fs,r]),Qi=i.useCallback(async(q,ke)=>{const qe=`${q}-${ke}`;try{on(Mt=>new Set(Mt).add(qe)),await FN(q,ke,r),a("Feature unlinked from assertion","success"),await Fs(ke)}catch(Mt){a(_e(Mt)||"Failed to unlink feature","error")}finally{on(Mt=>{const dn=new Set(Mt);return dn.delete(qe),dn})}},[a,Fs,r]),Xi=i.useCallback(async q=>{try{Ne(qe=>new Set(qe).add(q)),await UN(q,r),a("Validation triggered","success");const ke=await am(q,r);Ie(qe=>{const Mt=new Map(qe);return Mt.set(q,ke),Mt})}catch(ke){a(_e(ke)||"Failed to trigger validation","error")}finally{Ne(ke=>{const qe=new Set(ke);return qe.delete(q),qe})}},[a,r]),Xs=i.useCallback(async q=>{try{const ke=await am(q,r);Ie(qe=>{const Mt=new Map(qe);return Mt.set(q,ke),Mt})}catch{}},[r]),li=i.useCallback(async q=>{try{const ke=await BN(q,{limit:10},r);Ut(qe=>{const Mt=new Map(qe);return Mt.set(q,ke),Mt})}catch{}},[r]),Pi=i.useCallback(q=>{const ke=ge.current;if(ke){for(const qe of ke.milestones)for(const Mt of qe.slices)if(Mt.features.find(Yt=>Yt.id===q)){se(Yt=>{const Nn=new Set(Yt);return Nn.add(qe.id),Nn}),O(Yt=>{const Nn=new Set(Yt);return Nn.add(Mt.id),Nn}),pt(q),Gt(qe.id),Xs(q),li(q),requestAnimationFrame(()=>{const Yt=document.querySelector(`[data-mission-feature-id="${q}"]`);Yt instanceof HTMLElement&&typeof Yt.scrollIntoView=="function"&&Yt.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[Xs,li]),bi=i.useCallback(async q=>{try{const ke=await HN(q,r);Lt(qe=>{const Mt=new Map(qe);return Mt.set(q,ke),Mt})}catch{}},[r]),gt=i.useCallback(async q=>{St===q?pt(null):(pt(q),await Xs(q),await li(q))},[St,Xs,li]),hn=i.useCallback(async q=>{Ce===q?et(null):(et(q),await bi(q))},[Ce,bi]),Vs=i.useCallback(async q=>{try{await qN(q,r),a("Mission resumed","success"),await Pt(q),mn()}catch(ke){a(_e(ke)||"Failed to resume mission","error")}},[a,Pt,mn,r]),dr=i.useCallback(async q=>{try{const qe=(await VN(q,r)).pausedTaskIds?.length??0;a(`Mission stopped (${qe} task${qe!==1?"s":""} paused)`,"success"),await Pt(q),mn()}catch(ke){a(_e(ke)||"Failed to stop mission","error")}},[a,Pt,mn,r]),ur=i.useCallback(async q=>{try{await WN(q,r),a("Mission started — first slice activated","success"),await Pt(q),mn()}catch(ke){a(_e(ke)||"Failed to start mission","error")}},[a,Pt,mn,r]),go=i.useCallback(async(q,ke)=>{try{await KN(q,{enabled:ke},r),a(ke?"Autopilot enabled":"Autopilot disabled","success"),await Pt(q),mn()}catch(qe){a(_e(qe)||"Failed to update autopilot","error")}},[a,Pt,mn,r]),bo=i.useCallback(q=>{cn("structure"),Gt(null),ye(null),En([]),ot(0),Wt("all"),pn(new Set),Pt(q.id)},[Pt]),Jl=i.useCallback(()=>{x(null),Gt(null),ye(null),cn("structure"),En([]),ot(0),Wt("all"),pn(new Set),mn()},[mn]),ja=Tn.length<wt,ls=g?.autopilotState??"inactive",Na=ls==="watching"||ls==="activating",Is=kT(ls,g?.lastAutopilotActivityAt),Zi=i.useMemo(()=>!ln||!Xt||!Wc(ln)?null:ln.rollup.milestoneId===Xt?ln:null,[Xt,ln]),xo=i.useMemo(()=>{const q=new Map;for(const ke of Zi?.validationTelemetry.validationRounds??[]){const qe=q.get(ke.featureId);(!qe||ke.startedAt>qe.startedAt)&&q.set(ke.featureId,ke)}return q},[Zi]),vo=i.useCallback(()=>{!g||ct||!ja||Gn(g.id,{append:!0})},[ct,ja,Gn,g]),Sa=i.useCallback(q=>{pn(ke=>{const qe=new Set(ke);return qe.has(q)?qe.delete(q):qe.add(q),qe})},[]),mr=i.useCallback(q=>{q.key==="Enter"&&!q.shiftKey&&(q.preventDefault(),Nt())},[Nt]),Ca=i.useCallback(q=>{q.key==="Enter"&&!q.shiftKey&&(q.preventDefault(),ce())},[ce]),yo=i.useCallback(q=>{q.key==="Enter"&&!q.shiftKey&&(q.preventDefault(),it())},[it]),wo=i.useCallback(q=>{q.key==="Enter"&&!q.shiftKey&&(q.preventDefault(),Ln())},[Ln]),ko=i.useRef(null);if(i.useEffect(()=>{if(!h)return;const q=ke=>{ke.key==="Escape"&&s()};return document.addEventListener("keydown",q),()=>document.removeEventListener("keydown",q)},[h,s]),!h)return null;const ea=()=>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:[Na&&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:(jr[g.status]||jr.planning).bg,color:(jr[g.status]||jr.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:q=>go(g.id,q.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(ds,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),t.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(Ho[ls]||Ho.inactive).bg,color:(Ho[ls]||Ho.inactive).text},"data-testid":"autopilot-state-badge",children:[Na&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),ls]})]}),Is&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:Is})]}),t.jsxs("div",{className:"mission-detail__actions",children:[g.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>dr(g.id),title:"Stop mission","aria-label":"Stop mission",children:t.jsx(si,{size:14})}),g.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Vs(g.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(ns,{size:14})}),g.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>ur(g.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(ns,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ye(g),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(Cs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>be({type:"mission",id:g.id}),title:"Delete mission","aria-label":"Delete mission",children:t.jsx(Sn,{size:14})})]})]}),F===g.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:A.title,onChange:q=>$({...A,title:q.target.value}),onKeyDown:mr,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:A.description,onChange:q=>$({...A,description:q.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:A.status,onChange:q=>$({...A,status:q.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:A.autopilotEnabled,onChange:q=>$({...A,autopilotEnabled:q.target.checked})}),t.jsx(ds,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Nt,disabled:T,children:[T?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(ts,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ht,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[t.jsx("button",{className:`mission-btn ${At==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>cn("structure"),role:"tab","aria-selected":At==="structure","data-testid":"mission-tab-structure",children:"Structure"}),t.jsxs("button",{className:`mission-btn ${At==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>cn("activity"),role:"tab","aria-selected":At==="activity","data-testid":"mission-tab-activity",children:["Activity (",wt,")"]})]}),At==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[g.milestones.map(q=>{const ke=Zi?.rollup.milestoneId===q.id?Zi:null,qe=ke?.rollup??kn.get(q.id),Mt=ke?.validationTelemetry.validationRounds??[],dn=ke?.fixFeatures??[],Yt=dp[qe?.state??"not_started"]??dp.not_started,Nn=qe&&(qe.state==="blocked"||qe.state==="failed")?ke?.validationTelemetry.validationRounds.find(Xe=>Xe.blockedReason)?.blockedReason:void 0;return t.jsxs("div",{className:"mission-milestone",children:[t.jsxs("div",{className:"mission-milestone__header",onClick:()=>lt(q.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:B.has(q.id)?t.jsx(un,{size:16}):t.jsx(Un,{size:16})}),t.jsx(ca,{size:16,className:"mission-milestone__icon"}),t.jsx("span",{className:"mission-milestone__title",children:q.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:lp[q.status].bg,color:lp[q.status].text},children:q.status}),t.jsxs("span",{className:"mission-milestone__count",children:[q.slices.length," slices"]}),t.jsx(up,{state:fT(q.interviewState)}),qe&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Yt.bg,color:Yt.text},title:"Validation state",children:mp(qe.state)}),qe.totalAssertions>0&&t.jsx("div",{className:"mission-milestone__coverage-bar",title:`${qe.passedAssertions??0} of ${qe.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${(qe.passedAssertions??0)/qe.totalAssertions*100}%`,backgroundColor:(qe.passedAssertions??0)===qe.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),q.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ze({type:"milestone",id:q.id,title:q.title}),title:"Plan milestone","aria-label":"Plan milestone",children:t.jsx(Ki,{size:14})}),t.jsxs("div",{className:"mission-milestone__actions",onClick:Xe=>Xe.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>tn(q.id),title:"Add slice",children:t.jsx(Cn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Jn(q),title:"Edit milestone",children:t.jsx(Cs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>be({type:"milestone",id:q.id}),title:"Delete milestone",children:t.jsx(Sn,{size:14})})]})]}),B.has(q.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(le||I===q.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:Y.title,onChange:Xe=>re({...Y,title:Xe.target.value}),onKeyDown:Ca,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:Y.description,onChange:Xe=>re({...Y,description:Xe.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:ce,disabled:T,children:[T?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(ts,{size:14}),I?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:as,children:"Cancel"})]})]}),ke&&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:[ke.validationTelemetry.totalRuns," rounds",ke.validationTelemetry.lastValidatorStatus?` · Last ${ke.validationTelemetry.lastValidatorStatus}`:""]})]}),Nn&&t.jsxs("div",{className:"mission-blocked-reason",children:[t.jsx("strong",{children:"Blocked reason:"})," ",Nn]}),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:()=>ae(Xe=>!Xe),title:Le?"Hide validation rounds":"Show validation rounds",children:[Le?t.jsx(un,{size:12}):t.jsx(Un,{size:12}),"Validation rounds (",Mt.length,")"]}),Le&&t.jsx("div",{className:"mission-validation-rounds__list",children:Mt.map(Xe=>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--${Xe.validatorStatus}`,children:Xe.validatorStatus}),t.jsx("span",{className:"mission-validation-round__feature",children:Xe.featureTitle}),t.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",Xe.implementationAttempt," · reviewer #",Xe.validatorAttempt]})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),Xe.failedAssertionIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Xe.failedAssertionIds.map(nt=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ka(nt),title:`Jump to assertion ${nt}`,children:nt},`${Xe.roundId}-${nt}`))}):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:"}),Xe.generatedFixFeatureIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Xe.generatedFixFeatureIds.map(nt=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Pi(nt),title:`Jump to fix feature ${nt}`,children:nt},`${Xe.roundId}-${nt}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),Xe.blockedReason&&t.jsx("div",{className:"mission-validation-round__blocked-reason",children:Xe.blockedReason})]},Xe.roundId))})]}),dn.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:dn.map(Xe=>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:()=>Pi(Xe.id),title:`Jump to feature ${Xe.id}`,children:Xe.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Bo[Xe.status].bg,color:Bo[Xe.status].text},children:Xe.status}),Xe.loopState&&t.jsx("span",{className:`mission-loop-state mission-loop-state--${Xe.loopState}`,children:Xe.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:()=>Pi(Xe.sourceFeatureId),title:`Jump to source feature ${Xe.sourceFeatureId}`,children:Xe.sourceFeatureId}),t.jsx("span",{children:"Run:"}),t.jsx("span",{className:"mission-fix-feature__run",children:Xe.runId})]}),Xe.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:Xe.failedAssertionIds.map(nt=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ka(nt),title:`Jump to assertion ${nt}`,children:nt},`${Xe.id}-${nt}`))})]})]},Xe.id))})]})]}),t.jsxs("div",{className:"mission-slices",children:[q.slices.map(Xe=>t.jsxs("div",{className:"mission-slice",children:[t.jsxs("div",{className:"mission-slice__header",onClick:()=>An(Xe.id),children:[t.jsx("button",{className:"mission-slice__expand",children:P.has(Xe.id)?t.jsx(un,{size:16}):t.jsx(Un,{size:16})}),t.jsx(bd,{size:16,className:"mission-slice__icon"}),t.jsx("span",{className:"mission-slice__title",children:Xe.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:cp[Xe.status].bg,color:cp[Xe.status].text},children:Xe.status}),t.jsxs("span",{className:"mission-slice__count",children:[Xe.features?.length||0," features"]}),t.jsx(up,{state:Xe.planState??"not_started"}),Xe.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ze({type:"slice",id:Xe.id,title:Xe.title}),title:"Plan slice","aria-label":"Plan slice",children:t.jsx(Ki,{size:14})}),t.jsxs("div",{className:"mission-slice__actions",onClick:nt=>nt.stopPropagation(),children:[Xe.status==="pending"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Tt(Xe.id),title:"Activate slice",children:t.jsx(ns,{size:14})}),Xe.status==="active"&&Xe.features?.some(nt=>nt.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>es(Xe.id),title:"Triage all features",disabled:T,children:T?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(ds,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>vn(Xe.id),title:"Add feature",children:t.jsx(Cn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>G(Xe),title:"Edit slice",children:t.jsx(Cs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>be({type:"slice",id:Xe.id}),title:"Delete slice",children:t.jsx(Sn,{size:14})})]})]}),P.has(Xe.id)&&t.jsxs("div",{className:"mission-slice__body",children:[Q&&H===q.id&&!de&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:X.title,onChange:nt=>L({...X,title:nt.target.value}),onKeyDown:yo,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:X.description,onChange:nt=>L({...X,description:nt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:it,disabled:T,children:[T?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(ts,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Se,children:"Cancel"})]})]}),de===Xe.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:X.title,onChange:nt=>L({...X,title:nt.target.value}),onKeyDown:yo,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:X.description,onChange:nt=>L({...X,description:nt.target.value}),rows:2}),t.jsxs("select",{value:X.status,onChange:nt=>L({...X,status:nt.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:it,disabled:T,children:[T?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(ts,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Se,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-features",children:[Xe.features?.map(nt=>t.jsxs("div",{className:"mission-feature","data-mission-feature-id":nt.id,children:[t.jsxs("div",{className:"mission-feature__header",children:[t.jsx("button",{className:"mission-feature__expand",onClick:()=>gt(nt.id),title:St===nt.id?"Collapse details":"Expand to show run history",children:St===nt.id?t.jsx(un,{size:14}):t.jsx(Un,{size:14})}),t.jsx(cd,{size:14,className:"mission-feature__icon"}),t.jsx("span",{className:"mission-feature__title",children:nt.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Bo[nt.status].bg,color:Bo[nt.status].text},children:nt.status}),nt.loopState&&nt.loopState!=="idle"&&t.jsxs("span",{className:`mission-loop-state mission-loop-state--${nt.loopState}`,title:`Loop state: ${nt.loopState}`,children:[nt.loopState==="implementing"&&"⏳",nt.loopState==="validating"&&"🔄",nt.loopState==="needs_fix"&&"🔧",nt.loopState==="passed"&&"✅",nt.loopState==="blocked"&&"🚫"]}),nt.generatedFromFeatureId&&t.jsx("button",{className:"mission-feature__lineage",onClick:()=>Pi(nt.generatedFromFeatureId),title:`Generated from feature: ${nt.generatedFromFeatureId}`,children:"🔗 Fix"}),(nt.loopState==="validating"||nt.loopState==="needs_fix")&&(()=>{const Ot=ee.get(nt.id),_n=xo.get(nt.id),Ss=Ot?.implementationAttemptCount??_n?.implementationAttempt??nt.implementationAttemptCount??0,$s=Ot?.retryBudgetRemaining??Math.max(0,pT-Ss);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",Ss," · ",$s," ",$s===1?"retry":"retries"," left"]})})(),nt.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>Xi(nt.id),title:"Validate feature",disabled:Te.has(nt.id),children:Te.has(nt.id)?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(ys,{size:14})}),nt.taskId&&t.jsx("span",{className:"mission-feature__task-link",onClick:()=>o?.(nt.taskId),title:"Click to view task",children:nt.taskId}),t.jsxs("div",{className:"mission-feature__actions",children:[nt.status==="defined"&&!nt.taskId&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Pn(nt.id),title:"Triage — create task",disabled:T||Ue===nt.id,children:Ue===nt.id?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(ds,{size:14})}),nt.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>On(nt.id),title:"Unlink task",children:t.jsx(Iu,{size:14})}):nt.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>he(nt.id),title:"Link to task",children:t.jsx(Ha,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>yn(nt),title:"Edit feature",children:t.jsx(Cs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>be({type:"feature",id:nt.id}),title:"Delete feature",children:t.jsx(Sn,{size:14})})]})]}),nt.description&&t.jsx("p",{className:"mission-feature__description",children:nt.description}),nt.acceptanceCriteria&&t.jsxs("p",{className:"mission-feature__criteria",children:[t.jsx("strong",{children:"Acceptance:"})," ",nt.acceptanceCriteria]}),dt?.featureId===nt.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:dt.enrichedDescription}),t.jsxs("div",{className:"mission-triage-preview__actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:ps,disabled:T,children:[T?t.jsx(bt,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:qn,disabled:T,children:"Cancel"})]})]}),W===nt.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:Z.title,onChange:Ot=>fe({...Z,title:Ot.target.value}),onKeyDown:wo,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:Z.description,onChange:Ot=>fe({...Z,description:Ot.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:Z.acceptanceCriteria,onChange:Ot=>fe({...Z,acceptanceCriteria:Ot.target.value}),rows:2}),t.jsxs("select",{value:Z.status,onChange:Ot=>fe({...Z,status:Ot.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:Ln,disabled:T,children:[T?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(ts,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:fn,children:"Cancel"})]})]}),St===nt.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"})}),(Dt.get(nt.id)??[]).map(Ot=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>hn(Ot.id),children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${Ot.status}`,title:Ot.status,children:Ot.status}),t.jsx("span",{className:"mission-run__time",children:new Date(Ot.startedAt).toLocaleString()}),Ot.completedAt&&t.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(Ot.completedAt).getTime()-new Date(Ot.startedAt).getTime())/1e3),"s"]}),Ot.triggerType&&t.jsx("span",{className:"mission-run__trigger",children:Ot.triggerType}),t.jsx("button",{className:"mission-icon-btn",title:Ce===Ot.id?"Hide details":"Show details",children:Ce===Ot.id?t.jsx(un,{size:12}):t.jsx(Un,{size:12})})]}),Ce===Ot.id&&tt.get(Ot.id)&&t.jsxs("div",{className:"mission-run__details",children:[Ot.summary&&t.jsx("p",{className:"mission-run__summary",children:Ot.summary}),Ot.blockedReason&&t.jsxs("p",{className:"mission-run__blocked-reason",children:[t.jsx("strong",{children:"Blocked:"})," ",Ot.blockedReason]}),tt.get(Ot.id)?.failures&&tt.get(Ot.id).failures.length>0&&t.jsxs("div",{className:"mission-run__failures",children:[t.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),tt.get(Ot.id).failures.map(_n=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:_n.message}),_n.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",_n.expected]}),_n.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",_n.actual]})]},_n.id))]}),(!tt.get(Ot.id)?.failures||tt.get(Ot.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},Ot.id)),(!Dt.get(nt.id)||Dt.get(nt.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},nt.id)),Oe&&He===Xe.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:Z.title,onChange:nt=>fe({...Z,title:nt.target.value}),onKeyDown:wo,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:Z.description,onChange:nt=>fe({...Z,description:nt.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:Z.acceptanceCriteria,onChange:nt=>fe({...Z,acceptanceCriteria:nt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Ln,disabled:T,children:[T?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(ts,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:fn,children:"Cancel"})]})]}),!Oe&&(!Xe.features||Xe.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(cd,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},Xe.id)),q.slices.length===0&&!Q&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(bd,{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"}),qe&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Yt.bg,color:Yt.text},children:mp(qe.state)}),qe&&qe.totalAssertions>0&&t.jsx("div",{className:"mission-assertions__coverage-bar",title:`${qe.passedAssertions??0} of ${qe.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${(qe.passedAssertions??0)/qe.totalAssertions*100}%`,backgroundColor:(qe.passedAssertions??0)===qe.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>{jt(!0),at(null),ft({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx(Cn,{size:14})})]}),Et&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:me.title,onChange:Xe=>ft({...me,title:Xe.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:me.assertion,onChange:Xe=>ft({...me,assertion:Xe.target.value}),rows:2}),t.jsxs("select",{value:me.status,onChange:Xe=>ft({...me,status:Xe.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:()=>ks(q.id),disabled:T,children:[T?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(ts,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:xs,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(pe.get(q.id))?pe.get(q.id):[]).map(Xe=>t.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":Xe.id,children:[t.jsx("div",{className:"mission-assertion__header",children:Be===Xe.id?t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:me.title,onChange:nt=>ft({...me,title:nt.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:me.assertion,onChange:nt=>ft({...me,assertion:nt.target.value}),rows:2}),t.jsxs("select",{value:me.status,onChange:nt=>ft({...me,status:nt.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:()=>qs(Xe.id,q.id),disabled:T,children:[T?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(ts,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:xs,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(qo[Xe.status]??qo.pending).bg,color:(qo[Xe.status]??qo.pending).text},children:Xe.status}),t.jsx("span",{className:"mission-assertion__title",children:Xe.title}),(()=>{const Ot=Rt.get(Xe.id)?.length??0;return Ot>0?t.jsxs("span",{className:"mission-assertion__linked-count",title:`${Ot} linked feature${Ot!==1?"s":""}`,children:["(",Ot," linked)"]}):null})(),t.jsx("button",{className:"mission-icon-btn",onClick:()=>wa(Xe.id),title:"Toggle details",children:$t===Xe.id?t.jsx(un,{size:14}):t.jsx(Un,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>os(Xe),title:"Edit assertion",children:t.jsx(Cs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>be({type:"assertion",id:Xe.id}),title:"Delete assertion",children:t.jsx(Sn,{size:14})})]})}),$t===Xe.id&&t.jsxs("div",{className:"mission-assertion__body",children:[t.jsx("p",{className:"mission-assertion__text",children:Xe.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()=>{$t!==Xe.id&&await wa(Xe.id),qt(Kt===Xe.id?null:Xe.id)},title:"Link a feature",children:[t.jsx(Ha,{size:12}),"Link Feature"]})]}),Kt===Xe.id&&t.jsx("div",{className:"mission-assertion__feature-picker",children:t.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const nt=new Set((Rt.get(Xe.id)??[]).map(_n=>_n.id)),Ot=[];return g?.milestones.forEach(_n=>_n.slices.forEach(Ss=>Ot.push(...Ss.features.filter($s=>!nt.has($s.id))))),Ot.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):Ot.map(_n=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>cr(_n.id,Xe.id),disabled:Vt.has(Xe.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:_n.title}),Vt.has(Xe.id)&&t.jsx(bt,{size:12,className:"spinner"})]},_n.id))})()})}),(()=>{const nt=Rt.get(Xe.id)??[];return nt.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):nt.map(Ot=>{const _n=`${Ot.id}-${Xe.id}`,Ss=Jt.has(_n);return t.jsxs("div",{className:"mission-assertion__linked-feature",children:[t.jsx("span",{className:"mission-assertion__linked-feature-title",children:Ot.title}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Qi(Ot.id,Xe.id),disabled:Ss,title:"Unlink feature",children:Ss?t.jsx(bt,{size:12,className:"spinner"}):t.jsx(Iu,{size:12})})]},Ot.id)})})()]})]})]},Xe.id)),(!pe.get(q.id)||pe.get(q.id)?.length===0)&&!Et&&t.jsx("div",{className:"mission-manager__empty mission-assertions__empty",children:t.jsx("span",{children:"No assertions defined. Add one to define completion criteria."})})]})]})]})]})]},q.id)}),g&&!le&&I===null&&t.jsxs("button",{className:"mission-add-btn",onClick:zt,children:[t.jsx(Cn,{size:16}),"Add Milestone"]}),le&&I===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:Y.title,onChange:q=>re({...Y,title:q.target.value}),onKeyDown:Ca,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:Y.description,onChange:q=>re({...Y,description:q.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:ce,disabled:T,children:[T?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(ts,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:as,children:"Cancel"})]})]}),g.milestones.length===0&&!le&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(ca,{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:vt,onChange:q=>Wt(q.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:[Tn.length," of ",wt]})]}),!ct&&ja&&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:vo,"data-testid":"mission-activity-load-more",children:"Load more"})}),ct?t.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[t.jsx(bt,{size:18,className:"spinner"}),t.jsx("span",{children:"Loading mission activity..."})]}):Tn.length===0?t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Gs,{size:18}),t.jsx("span",{children:"No events yet."})]}):t.jsxs("div",{ref:Hn,className:"mission-events","data-testid":"mission-activity-events",children:[Tn.map(q=>{const ke=!!(q.metadata&&Object.keys(q.metadata).length>0),qe=an.has(q.id);return t.jsxs("div",{className:"mission-event",children:[t.jsxs("div",{className:"mission-event__header",children:[t.jsx("span",{className:`mission-event__type ${yT(q.eventType)}`,children:wT(q.eventType)}),t.jsx("span",{className:"mission-event__time",children:jl(q.timestamp)})]}),t.jsx("p",{className:"mission-event__description",children:q.description}),t.jsx("span",{className:"mission-event__timestamp",children:new Date(q.timestamp).toLocaleString()}),ke&&t.jsxs("div",{className:"mission-event__metadata",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>Sa(q.id),"data-testid":`mission-event-metadata-${q.id}`,children:[qe?"Hide":"Show"," metadata"]}),qe&&t.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(q.metadata,null,2)})]})]},q.id)}),t.jsx("div",{ref:Mn})]})]})]}):null,te=()=>f.map(q=>{const ke=q,qe=g?.id===ke.id,Mt=jr[ke.status]||{bg:"",text:""},dn=ke.summary,Yt=Zt.get(ke.id),Nn=bT(Yt),Xe=!!(dn&&(dn.totalMilestones>0||dn.totalFeatures>0)),nt=Yt?.totalTasks??0,Ot=Yt?.tasksCompleted??0,_n=Yt?.tasksFailed??0,Ss=Yt?.estimatedCompletionPercent??dn?.progressPercent??0,$s=Xe||nt>0||_n>0||!!Yt?.lastActivityAt;return t.jsxs("div",{className:`mission-list__item ${qe?"mission-list__item--selected":""}`,onClick:()=>bo(q),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(As,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:ke.title})]}),t.jsxs("div",{className:"mission-list__item-tags",children:[q.autopilotEnabled&&t.jsx("span",{title:"Autopilot enabled",children:t.jsx(ds,{size:12,className:"mission-list__item-autopilot-icon"})}),t.jsx("span",{className:`mission-health-badge mission-health-badge--${Nn}`,"data-testid":`mission-health-badge-${ke.id}`,"aria-label":`Mission health: ${Nn}`}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Mt.bg,color:Mt.text},children:ke.status})]}),ke.description&&t.jsx("p",{className:"mission-list__item-description",children:ke.description}),$s&&t.jsxs("div",{className:"mission-list__item-summary",children:[Xe&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[dn.completedMilestones,"/",dn.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[dn.completedFeatures,"/",dn.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${ke.id}`,children:[Ot,"/",nt," tasks"]}),_n>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:fs=>{fs.stopPropagation(),bo(q)},"data-testid":`mission-failed-${ke.id}`,title:"View mission failures",children:[_n," failed"]}),t.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${Nn}`,children:t.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${Ss}%`}})})]}),$s&&t.jsx("div",{className:"mission-list__item-activity",children:t.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${ke.id}`,children:["Activity ",jl(Yt?.lastActivityAt)]})})]}),t.jsxs("div",{className:"mission-list__item-actions",onClick:fs=>fs.stopPropagation(),children:[ke.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>dr(ke.id),title:"Stop mission",children:t.jsx(si,{size:14})}),ke.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Vs(ke.id),title:"Resume mission",children:t.jsx(ns,{size:14})}),ke.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>ur(ke.id),title:"Start mission",children:t.jsx(ns,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ye(q),title:"Edit mission",children:t.jsx(Cs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>be({type:"mission",id:ke.id}),title:"Delete mission",children:t.jsx(Sn,{size:14})})]})]},ke.id)}),ze=({hideBottomButtons:q=!1}={})=>t.jsxs("div",{className:"mission-list",children:[C&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:A.title,onChange:ke=>$({...A,title:ke.target.value}),onKeyDown:mr,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:A.description,onChange:ke=>$({...A,description:ke.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Nt,disabled:T,children:[T?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(ts,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ht,children:"Cancel"})]})]}),te(),F&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:A.title,onChange:ke=>$({...A,title:ke.target.value}),onKeyDown:mr,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:A.description,onChange:ke=>$({...A,description:ke.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:A.status,onChange:ke=>$({...A,status:ke.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:A.autopilotEnabled,onChange:ke=>$({...A,autopilotEnabled:ke.target.checked})}),t.jsx(ds,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Nt,disabled:T,children:[T?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(ts,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ht,children:"Cancel"})]})]}),f.length===0&&!C&&t.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large mission-manager__empty--mission",children:[t.jsx(As,{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:()=>xe(!0),children:[t.jsx(ys,{size:14}),"Plan New Mission"]})]}),!C&&t.jsxs("div",{className:"mission-list__footer",children:[Pe.length>0&&t.jsxs("div",{className:"mission-resume-prompt",children:[t.jsx(Rs,{size:16}),t.jsx("span",{children:Pe.length===1?`Resume "${Pe[0].title}"?`:`${Pe.length} interview sessions pending`}),t.jsx("div",{className:"mission-list__resume-actions",children:Pe.map(ke=>t.jsxs("button",{className:"mission-add-btn",onClick:()=>{We(ke.id),xe(!0),ie([])},children:[ke.status==="error"?t.jsx(us,{size:14}):t.jsx(ys,{size:14}),ke.status==="error"?"Retry":"Resume"]},ke.id))})]}),!q&&t.jsx("div",{className:"mission-list__footer-actions",children:t.jsxs("button",{className:"mission-add-btn",onClick:()=>xe(!0),children:[t.jsx(ys,{size:16}),"Plan New Mission"]})})]})]}),yt=()=>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 ",De?.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()=>{De&&(De.type==="mission"?await _t(De.id):De.type==="milestone"?await Ge(De.id):De.type==="slice"?await Ct(De.id):De.type==="feature"&&await Zn(De.id))},children:"Delete"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>be(null),children:"Cancel"})]})]})}),Bt=()=>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:ue,onChange:q=>Ee(q.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(q=>t.jsxs("button",{className:"mission-task-suggestions__item",onClick:()=>Ee(q.id),children:[q.id,": ",q.title||"Untitled"]},q.id))})]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--primary",onClick:hs,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{he(null),Ee("")},children:"Cancel"})]})]})}),Yn=t.jsxs("div",{ref:ko,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:Jl,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(_l,{size:18})}),t.jsx(As,{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(en,{size:18})})]}),j?t.jsxs("div",{className:"mission-manager__body mission-manager__body--stacked",children:[v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(bt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):k?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(bt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?ea():ze(),De&&yt(),$e&&Bt()]}):t.jsxs("div",{className:"mission-manager__split",children:[t.jsxs("aside",{className:"mission-manager__sidebar","data-testid":"mission-sidebar","aria-label":"Mission list",style:j?void 0:{width:`${E}px`},children:[t.jsx("div",{className:"mission-manager__sidebar-header",children:t.jsxs("button",{className:"btn btn-sm btn-primary mission-manager__sidebar-cta",onClick:()=>xe(!0),title:"Plan New Mission","aria-label":"Plan New Mission",children:[t.jsx(ys,{size:14}),"Plan New Mission"]})}),t.jsx("div",{className:"mission-manager__sidebar-list",children:v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(bt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):ze({hideBottomButtons:!0})})]}),!j&&t.jsx("div",{className:"mission-manager__sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":zo,"aria-valuemax":Uo,"aria-valuenow":E,"aria-label":"Resize mission sidebar",tabIndex:0,onPointerDown:M,onKeyDown:D}),t.jsxs("div",{className:"mission-manager__detail-pane",children:[k?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(bt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?ea():t.jsxs("div",{className:"mission-manager__detail-pane-empty","data-testid":"mission-empty-detail",children:[t.jsx(As,{size:32}),t.jsx("span",{children:"Select a mission to view details"})]}),De&&yt(),$e&&Bt()]})]})]}),Zs=t.jsx(tT,{isOpen:je,onClose:()=>xe(!1),onMissionCreated:()=>{mn(),a("Mission created from AI interview","success")},projectId:r,resumeSessionId:mt}),hr=st?t.jsx(uT,{isOpen:!0,onClose:()=>Ze(null),onApplied:()=>{Ze(null),g&&Pt(g.id)},targetType:st.type,targetId:st.id,targetTitle:st.title,missionContext:g?.title,projectId:r,resumeSessionId:st.resumeSessionId}):null;return n?t.jsxs(t.Fragment,{children:[Yn,Zs,hr]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mission-manager-overlay open",onClick:q=>q.target===q.currentTarget&&s(),"data-testid":"mission-manager-overlay",role:"dialog","aria-modal":"true",children:Yn}),Zs,hr]})}const Vo=2e3;function fp({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),[v,b]=i.useState(null),k=d.trim()!==""&&f.trim().length>0&&f.length<=Vo,S=i.useCallback(async()=>{if(!(!k||g)){x(!0),b(null);try{const E=m==="agent"?"user-to-agent":"system";await _1({toId:d.trim(),toType:m,content:f.trim(),type:E,...n?{metadata:{replyTo:{messageId:n.messageId}}}:{}},a),r()}catch(E){const y=_e(E)||"Failed to send message";b(y),l?.(y,"error")}finally{x(!1)}}},[k,g,d,m,f,n,a,r,l]),j=i.useCallback(E=>{u(E),h("agent")},[]);return 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(en,{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:E=>j(E.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(E=>t.jsx("option",{value:E.id,children:E.name||E.id},E.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(zn,{size:14}),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",className:"message-composer-textarea",placeholder:"Type your message…",value:f,onChange:E=>p(E.target.value),maxLength:Vo,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>Vo?"over-limit":"",children:[f.length,"/",Vo]})})]}),v&&t.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[t.jsx(Rs,{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:S,disabled:!k||g,"data-testid":"message-composer-send",children:g?t.jsxs(t.Fragment,{children:[t.jsx(bt,{size:14,className:"spin"}),t.jsx("span",{children:"Sending…"})]}):t.jsxs(t.Fragment,{children:[t.jsx(ra,{size:14}),t.jsx("span",{children:"Send"})]})})]})]})}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 NT(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 ST(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 gp(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function CT(e){const n=new Map;for(const s of e){const a=`${s.fromType}:${s.fromId}`,r=n.get(a);r?(r.messages.push(s),new Date(s.createdAt)>new Date(r.latestMessage.createdAt)&&(r.latestMessage=s),s.read||r.unreadCount++):n.set(a,{key:a,fromId:s.fromId,fromType:s.fromType,latestMessage:s,messages:[s],unreadCount:s.read?0:1})}return Array.from(n.values()).sort((s,a)=>new Date(a.latestMessage.createdAt).getTime()-new Date(s.latestMessage.createdAt).getTime())}function ET({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,v]=i.useState([]),[b,k]=i.useState(!1),[S,j]=i.useState(null),[E,y]=i.useState(null),[N,M]=i.useState(null),[D,C]=i.useState("inbox"),[_,F]=i.useState(null),[U,A]=i.useState([]),$=i.useMemo(()=>new Map(U.map(W=>[W.id,W.name??""])),[U]),T=i.useCallback((W,we)=>NT(W,we,$),[$]),B=oi()==="mobile",se=!B,P=i.useCallback(async()=>{f(!0);try{const W=await C1({limit:50},e);l(W),m(W.unreadCount),s?.(W.unreadCount)}catch{}finally{f(!1)}},[e,s]),O=i.useCallback(async()=>{f(!0);try{const W=await E1({limit:50},e);d(W)}catch{}finally{f(!1)}},[e]),I=i.useCallback(async W=>{f(!0);try{const we=await T1(W,e);F(we)}catch{}finally{f(!1)}},[e]),w=i.useCallback(async()=>{try{const W=await ba(void 0,e);A(W)}catch{}},[e]),Y=i.useCallback(async()=>{try{const W=await Wf(e);m(W.unreadCount),s?.(W.unreadCount)}catch{}},[e,s]);i.useEffect(()=>{a==="inbox"?P():a==="outbox"?O():a==="agents"&&w()},[a,P,O,w]),i.useEffect(()=>{N&&I(N)},[N,I]),i.useEffect(()=>{Y()},[Y]),i.useEffect(()=>{w()},[w]),i.useEffect(()=>{if(typeof EventSource>"u")return;const W=e?`?projectId=${encodeURIComponent(e)}`:"",we=()=>{Y(),a==="inbox"?P():a==="outbox"&&O(),N&&I(N)};return gi(`/api/events${W}`,{events:{"message:sent":we,"message:received":we,"message:read":we,"message:deleted":we}})},[e,a,N,Y,P,O,I]);const re=i.useCallback(async W=>{if(g(W),!W.read)try{const we=await M1(W.id,e);we&&l(fe=>fe&&{...fe,messages:fe.messages.map(Oe=>Oe.id===we.id?we:Oe),unreadCount:Math.max(0,fe.unreadCount-1)});const Z=Math.max(0,u-1);m(Z),s?.(Z)}catch{}try{const we=await R1(W.fromId,W.fromType,e);v(we)}catch{v([W])}},[e,u,s]),le=i.useCallback(()=>{g(null),v([])},[]),ve=i.useCallback(async()=>{try{const W=await A1(e);m(0),s?.(0),l(we=>we&&{...we,messages:we.messages.map(Z=>({...Z,read:!0})),unreadCount:0}),n?.(`Marked ${W.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[e,n,s]),de=i.useCallback(async W=>{try{await P1(W,e),g(null),v([]),a==="inbox"?P():a==="outbox"?O():N&&I(N),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,a,N,P,O,I,n]),Fe=i.useCallback(W=>{j({id:W.fromId,type:W.fromType}),y({messageId:W.id,preview:gp(W.content,120)}),k(!0)},[]),X=i.useCallback(()=>{k(!1),j(null),y(null),n?.("Message sent","success"),a==="outbox"?O():a==="agents"&&N&&I(N),Y()},[a,O,N,I,n,Y]),L=i.useCallback(()=>{j(a==="agents"&&N?{id:N,type:"agent"}:null),y(null),k(!0)},[a,N]),Q=i.useCallback(()=>{k(!1),j(null),y(null)},[]),ne=()=>!p||b?null:t.jsxs("div",{className:"mailbox-message-detail","data-testid":"mailbox-message-detail",children:[t.jsxs("div",{className:"mailbox-message-detail-header",children:[B&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:le,"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:ST(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:()=>Fe(p),"data-testid":"mailbox-reply",children:[t.jsx(Di,{size:14}),t.jsx("span",{children:"Reply"})]}),t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>de(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(zn,{size:14}):t.jsx(Ea,{size:14}),T(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(zn,{size:14}):t.jsx(Ea,{size:14}),T(p.toId,p.toType)]})]})]}),x.length>1&&t.jsxs("div",{className:"mailbox-conversation","data-testid":"mailbox-conversation",children:[t.jsx("div",{className:"mailbox-conversation-label",children:"Conversation"}),x.map(W=>{const we=W.metadata?.replyTo?.messageId,Z=we?x.find(fe=>fe.id===we):void 0;return t.jsxs("div",{className:`mailbox-conversation-msg ${W.id===p.id?"current":""}`,children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:T(W.fromId,W.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:Ta(W.createdAt)})]}),we&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":`mailbox-reply-context-${W.id}`,children:["↪ Replying to ",Z?gp(Z.content,60):`message ${we}`]}),t.jsx("div",{className:"mailbox-conversation-msg-body",children:W.content})]},W.id)})]}),x.length<=1&&t.jsxs(t.Fragment,{children:[p.metadata?.replyTo?.messageId&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":"mailbox-selected-reply-context",children:["↪ Replying to message ",p.metadata.replyTo.messageId]}),t.jsx("div",{className:"mailbox-message-body","data-testid":"mailbox-message-body",children:p.content})]})]}),H=()=>t.jsxs(t.Fragment,{children:[a==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!o&&t.jsx(Kc,{}),o&&o.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[t.jsx(Ar,{size:32}),t.jsx("p",{children:"No messages in your inbox"})]}),o&&o.messages.length>0&&t.jsx("div",{className:"mailbox-conversations","data-testid":"mailbox-conversations",children:CT(o.messages).map(W=>t.jsxs("div",{className:`mailbox-conversation-group ${W.unreadCount>0?"unread":""}`,onClick:()=>re(W.latestMessage),"data-testid":`mailbox-conversation-${W.key}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:W.fromType==="agent"?t.jsx(zn,{size:16}):t.jsx(Ea,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsx("span",{className:"mailbox-item-from",children:T(W.fromId,W.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:Ta(W.latestMessage.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[W.latestMessage.content.slice(0,80),W.latestMessage.content.length>80?"…":""]})]}),W.unreadCount>0&&t.jsx("div",{className:"mailbox-group-unread-badge","data-testid":`mailbox-unread-badge-${W.key}`,children:W.unreadCount>9?"9+":W.unreadCount})]},W.key))})]}),a==="outbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!c&&t.jsx(Kc,{}),c&&c.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[t.jsx(ra,{size:32}),t.jsx("p",{children:"No sent messages"})]}),c?.messages.map(W=>t.jsxs("div",{className:"mailbox-item",onClick:()=>re(W),"data-testid":`mailbox-item-${W.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:W.toType==="agent"?t.jsx(zn,{size:16}):t.jsx(Ea,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsxs("span",{className:"mailbox-item-to",children:["To: ",T(W.toId,W.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:Ta(W.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[W.content.slice(0,80),W.content.length>80?"…":""]})]})]},W.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(zn,{size:32}),t.jsx("p",{children:"No agents found"})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"mailbox-agents-header",children:[t.jsx("div",{className:"mailbox-agents-dropdown",children:t.jsxs("select",{className:"message-composer-select mailbox-agent-select",value:N??"",onChange:W=>{M(W.target.value||null),C("inbox")},"data-testid":"mailbox-agent-select",children:[t.jsx("option",{value:"",children:"Select an agent…"}),U.map(W=>t.jsx("option",{value:W.id,children:W.name||W.id},W.id))]})}),t.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:L,"data-testid":"mailbox-compose-btn",children:[t.jsx(Di,{size:14}),t.jsx("span",{children:"Compose"})]})]}),N&&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 ${D==="inbox"?"active":""}`,onClick:()=>C("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[t.jsx(Ar,{size:12}),t.jsx("span",{children:"Inbox"}),_&&_.unreadCount>0&&t.jsx("span",{className:"mailbox-tab-badge",children:_.unreadCount})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${D==="outbox"?"active":""}`,onClick:()=>C("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[t.jsx(ra,{size:12}),t.jsx("span",{children:"Outbox"})]})]}),t.jsxs("div",{className:"mailbox-agents-content",children:[!N&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(zn,{size:32}),t.jsx("p",{children:"Select an agent to view their mailbox"})]}),N&&h&&!_&&t.jsx(Kc,{}),N&&_&&D==="inbox"&&_.inbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Ar,{size:32}),t.jsx("p",{children:"No received messages for this agent"})]}),N&&_&&D==="outbox"&&_.outbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(ra,{size:32}),t.jsx("p",{children:"No sent messages for this agent"})]}),N&&_&&D==="inbox"&&_.inbox.map(W=>t.jsxs("div",{className:`mailbox-item ${W.read?"":"unread"}`,onClick:()=>re(W),"data-testid":`mailbox-item-${W.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:W.fromType==="agent"?t.jsx(zn,{size:16}):t.jsx(Ea,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsx("span",{className:"mailbox-item-from",children:T(W.fromId,W.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:Ta(W.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[W.content.slice(0,80),W.content.length>80?"…":""]})]})]},W.id)),N&&_&&D==="outbox"&&_.outbox.map(W=>t.jsxs("div",{className:"mailbox-item",onClick:()=>re(W),"data-testid":`mailbox-item-${W.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:W.toType==="agent"?t.jsx(zn,{size:16}):t.jsx(Ea,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsxs("span",{className:"mailbox-item-to",children:["To: ",T(W.toId,W.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:Ta(W.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[W.content.slice(0,80),W.content.length>80?"…":""]})]})]},W.id))]})]})})]}),z=()=>b?t.jsx(fp,{recipient:S,replyContext:E,agents:U,projectId:e,onSend:X,onCancel:Q,addToast:n}):p?ne():t.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[t.jsx(da,{size:24}),t.jsx("p",{children:"Select a conversation to read messages"})]});return t.jsxs("div",{className:"mailbox-view","data-testid":"mailbox-view",children:[t.jsxs("div",{className:"mailbox-header",children:[t.jsxs("div",{className:"mailbox-title",children:[t.jsx(da,{size:18}),t.jsx("span",{children:"Mailbox"}),u>0&&t.jsx("span",{className:"mailbox-unread-badge","data-testid":"mailbox-unread-badge",children:u})]}),t.jsxs("div",{className:"mailbox-header-actions",children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:L,title:"Compose message","data-testid":"mailbox-header-compose",children:[t.jsx(Di,{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(zx,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{a==="inbox"?P():a==="outbox"?O():N&&I(N)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?t.jsx(bt,{size:14,className:"spin"}):t.jsx(us,{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(Ar,{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(ra,{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)},"data-testid":"mailbox-tab-agents",children:[t.jsx(zn,{size:14}),t.jsx("span",{children:"Agents"})]})]}),t.jsx("div",{className:"mailbox-content","data-testid":"mailbox-content",children:se?t.jsxs("div",{className:"mailbox-split-layout","data-testid":"mailbox-split-layout",children:[t.jsx("div",{className:"mailbox-split-list-pane","data-testid":"mailbox-split-list-pane",children:H()}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:z()})]}):t.jsxs(t.Fragment,{children:[ne(),b&&t.jsx(fp,{recipient:S,replyContext:E,agents:U,projectId:e,onSend:X,onCancel:Q,addToast:n}),!p&&!b&&H()]})})]})}function Kc(){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 _T=640;function MT({isOpen:e,onClose:n,onImport:s,tasks:a,projectId:r}){Mi(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,v]=i.useState([]),[b,k]=i.useState(null),[S,j]=i.useState([]),[E,y]=i.useState(null),[N,M]=i.useState(null),[D,C]=i.useState(!1),[_,F]=i.useState([]),[U,A]=i.useState(!1),[$,T]=i.useState(""),J=i.useRef(!1),B=i.useRef(null);_i(B,e,"fusion:github-modal-size");const se=Fi(n),[P,O]=i.useState(!1),[I,w]=i.useState("list"),Y=i.useRef(null),re=new Set;for(const ie of a){const Me=ie.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);Me&&re.add(Me[1]);const We=ie.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);We&&re.add(We[1])}i.useEffect(()=>{if(e)return l(""),d(""),m(""),v([]),k(null),j([]),y(null),g("issues"),M(null),C(!1),F([]),A(!0),T(""),Y.current=null,J.current=!0,Ak().then(ie=>{if(J.current)if(F(ie),A(!1),ie.length===1){const Me=ie[0];l(Me.owner),d(Me.repo),T(Me.name)}else ie.length>1&&(l(""),d(""),T(""))}).catch(()=>{J.current&&A(!1)}),()=>{J.current=!1}},[e]);const le=i.useCallback(ie=>{if(T(ie),ie==="")l(""),d("");else{const Me=_.find(We=>We.name===ie);Me&&(l(Me.owner),d(Me.repo))}},[_]),ve=i.useCallback(async()=>{if(!o.trim()||!c.trim()){M("Repository must be selected");return}f(!0),M(null),v([]),k(null);try{const ie=u.split(",").map(We=>We.trim()).filter(Boolean),Me=await Ck(o.trim(),c.trim(),30,ie.length>0?ie:void 0);v(Me),Me.length===0&&M("No open issues found")}catch(ie){M(_e(ie)||"Failed to fetch issues")}finally{f(!1)}},[o,c,u]),de=i.useCallback(async()=>{if(!o.trim()||!c.trim()){M("Repository must be selected");return}f(!0),M(null),j([]),y(null);try{const ie=await _k(o.trim(),c.trim(),30);j(ie),ie.length===0&&M("No open pull requests found")}catch(ie){M(_e(ie)||"Failed to fetch pull requests")}finally{f(!1)}},[o,c]);i.useEffect(()=>{if(!e||!o.trim()||!c.trim()||h||D)return;const ie={owner:o.trim(),repo:c.trim(),labels:u.trim(),tab:p};Y.current?.owner===ie.owner&&Y.current?.repo===ie.repo&&Y.current?.labels===ie.labels&&Y.current?.tab===ie.tab||(Y.current=ie,p==="issues"?ve():de())},[o,c,u,p,e,h,D,ve,de]),i.useEffect(()=>{if(!e)return;const ie=Me=>{Me.key==="Escape"&&n()};return document.addEventListener("keydown",ie),()=>document.removeEventListener("keydown",ie)},[e,n]),i.useEffect(()=>{if(!e)return;const ie=()=>{O(window.innerWidth<=_T)};return ie(),window.addEventListener("resize",ie),()=>window.removeEventListener("resize",ie)},[e]);const Fe=i.useCallback(ie=>{k(ie),P&&w("preview")},[P]),X=i.useCallback(ie=>{y(ie),P&&w("preview")},[P]),L=i.useCallback(()=>{w("list")},[]),Q=i.useCallback(async()=>{if(p==="issues"){if(b===null)return;C(!0),M(null);try{const ie=await Ek(o.trim(),c.trim(),b,r);s(ie),k(null),P&&I==="preview"&&w("list")}catch(ie){const Me=_e(ie);Me?.includes("already imported")?M(Me):M(Me||"Failed to import issue")}finally{C(!1)}}else{if(E===null)return;C(!0),M(null);try{const ie=await Mk(o.trim(),c.trim(),E,r);s(ie),y(null),P&&I==="preview"&&w("list")}catch(ie){const Me=_e(ie);Me?.includes("already imported")?M(Me):M(Me||"Failed to import pull request")}finally{C(!1)}}},[p,b,E,o,c,s,P,I]),ne=x.find(ie=>ie.number===b),H=S.find(ie=>ie.number===E);if(!e)return null;const z=_.length>0,W=_.length===1,we=x.filter(ie=>re.has(ie.html_url)).length,Z=S.filter(ie=>re.has(ie.html_url)).length,fe=N==="No open issues found",Oe=N==="No open pull requests found",Ve=p==="issues"?fe:Oe,He=!!N&&!fe&&x.length===0&&!h,Je=!!N&&!Oe&&S.length===0&&!h,$e=p==="issues"?He:Je,he=h||x.length>0||fe||He,ue=h||S.length>0||Oe||Je,Ee=p==="issues"?he:ue,je=!!N&&x.length>0&&!fe,xe=!!N&&S.length>0&&!Oe,Pe=p==="issues"?je:xe;return t.jsx("div",{className:"modal-overlay open",...se,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg github-import-modal",ref:B,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||D,children:[t.jsx(Ml,{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"),k(null)},disabled:h||D,children:[t.jsx(Ks,{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(bt,{size:16,className:"spin"}),t.jsx("span",{children:"Detecting…"})]}):z?W?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:_[0].name}),t.jsxs("span",{className:"github-import-remote-pill__repo",children:[_[0].owner,"/",_[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:ie=>le(ie.target.value),disabled:h||D,"aria-label":"Select Git remote",children:[t.jsx("option",{value:"",children:"Select remote…"}),_.map(ie=>t.jsxs("option",{value:ie.name,children:[ie.name," (",ie.owner,"/",ie.repo,")"]},ie.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:ie=>m(ie.target.value),onKeyDown:ie=>ie.key==="Enter"&&ve(),disabled:h||D||!z,"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"?ve:de,disabled:h||D||!o.trim()||!c.trim(),"aria-label":h?`Loading ${p}`:`Load ${p} from repository`,title:h?"Loading…":`Load ${p}`,children:[h?t.jsx(bt,{size:14,className:"spin"}):t.jsx(us,{size:14}),t.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!U&&!z&&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"})]}),Pe&&t.jsx("div",{className:"form-error github-import-banner",role:"alert",children:N}),t.jsxs("div",{className:"github-import-workspace",children:[t.jsxs("section",{className:`github-import-list-pane ${P?"mobile":""} ${I==="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:[we," imported"]})]}),p==="pulls"&&S.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[S.length," pull request",S.length===1?"":"s"]}),t.jsxs("span",{children:[Z," imported"]})]})]}),t.jsxs("div",{className:"github-import-pane-content",children:[!Ee&&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(bt,{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."})]})]}),$e&&t.jsx("div",{className:"github-import-state github-import-state--error",role:"alert",children:t.jsxs("div",{children:[t.jsxs("strong",{children:["Could not load ",p==="issues"?"issues":"pull requests"]}),t.jsx("span",{children:N})]})}),Ve&&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(ie=>{const Me=re.has(ie.html_url);return t.jsxs("div",{className:`issue-item ${b===ie.number?"selected":""} ${Me?"imported":""}`,onClick:()=>!Me&&Fe(ie.number),children:[t.jsx("input",{type:"radio",name:"issue",checked:b===ie.number,onChange:()=>Fe(ie.number),disabled:Me,"aria-label":`Select issue #${ie.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",ie.number]}),t.jsx("span",{className:"issue-title",children:ie.title})]}),ie.labels.length>0&&t.jsx("span",{className:"issue-labels",children:ie.labels.map(We=>t.jsx("span",{className:"label-chip",children:We.name},We.name))})]}),Me&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},ie.number)})}),p==="pulls"&&S.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:S.map(ie=>{const Me=re.has(ie.html_url);return t.jsxs("div",{className:`issue-item ${E===ie.number?"selected":""} ${Me?"imported":""}`,onClick:()=>!Me&&X(ie.number),children:[t.jsx("input",{type:"radio",name:"pull",checked:E===ie.number,onChange:()=>X(ie.number),disabled:Me,"aria-label":`Select pull request #${ie.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",ie.number]}),t.jsx("span",{className:"issue-title",children:ie.title})]}),t.jsxs("span",{className:"pull-branch-info",children:[ie.headBranch," → ",ie.baseBranch]})]}),Me&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},ie.number)})})]})]}),t.jsxs("section",{className:`github-import-preview-pane ${P?"mobile":""} ${I==="preview"?"active":""}`,"data-testid":"github-import-preview-pane","aria-labelledby":"github-import-preview-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[P&&t.jsxs("button",{className:"github-import-back-button",onClick:L,"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"&&ne?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Issue #",ne.number]}),t.jsx("div",{className:"preview-title",children:ne.title}),t.jsx("div",{className:"preview-body",children:ne.body?ne.body.slice(0,200)+(ne.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"&&H?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Pull Request #",H.number]}),t.jsx("div",{className:"preview-title",children:H.title}),t.jsxs("div",{className:"preview-branch",children:[t.jsx("strong",{children:"Branch:"})," ",H.headBranch," → ",H.baseBranch]}),t.jsx("div",{className:"preview-body",children:H.body?H.body.slice(0,200)+(H.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:D,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:Q,disabled:(p==="issues"?b===null:E===null)||D,children:D?t.jsx(bt,{size:14,className:"spin"}):"Import"})]})]})})}function ii({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(Un,{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 AT=["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 PT(e,n){return e&&n?`${e}/${n}`:""}function RT(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 TT({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([]),[v,b]=i.useState([]),[k,S]=i.useState(null),j=i.useRef(!1),E=i.useRef(!1),[y,N]=i.useState(""),[M,D]=i.useState(!0),[C,_]=i.useState(!1),[F,U]=i.useState(!1),[A,$]=i.useState(null),[T,J]=i.useState(0),B=i.useRef(null),se=i.useRef(null),P=i.useRef(null),O=i.useRef(null),I=i.useRef(null),w=i.useRef(null),Y=i.useRef(null),[re,le]=i.useState(c??null),ve=i.useMemo(()=>va(),[]),{isLockedByOther:de,takeControl:Fe,isLoading:X}=Gl(e?re:null),{activeTabMap:L,broadcastUpdate:Q,broadcastCompleted:ne,broadcastLock:H,broadcastUnlock:z,broadcastHeartbeat:W}=lr(),[we,Z]=i.useState(void 0),[fe,Oe]=i.useState(void 0),[Ve,He]=i.useState("medium"),[Je,$e]=i.useState(""),[he,ue]=i.useState([]),[Ee,je]=i.useState(!1),[xe,Pe]=i.useState(null),[ie,Me]=i.useState([]),[We,mt]=i.useState([]),[st,Ze]=i.useState({}),dt=i.useRef(null),[Ae,Ue]=i.useState([]),[kt,De]=i.useState(!1),[be,pe]=i.useState(c??null),[Re,Be]=i.useState(!!c),[at,me]=i.useState(null),[ft,Et]=i.useState(!1),jt=i.useRef(!1),$t=i.useRef(null),Ft=i.useRef(""),Rt=i.useRef(null),It=i.useRef(null);_i(se,e,"fusion:planning-modal-size");const Vt=oi(),{keyboardOverlap:Qt,viewportHeight:Jt,viewportOffsetTop:on,keyboardOpen:Kt}=ya({enabled:Vt==="mobile"});Mi(Vt==="mobile"&&e),i.useEffect(()=>{const oe=se.current;oe&&(Kt?(oe.style.setProperty("--keyboard-overlap",`${Qt}px`),oe.style.setProperty("--vv-offset-top",`${on}px`),Jt!==null?oe.style.setProperty("--vv-height",`${Jt}px`):oe.style.removeProperty("--vv-height")):(oe.style.removeProperty("--keyboard-overlap"),oe.style.removeProperty("--vv-offset-top"),oe.style.removeProperty("--vv-height")))},[Kt,Qt,on,Jt]),i.useEffect(()=>{Ft.current=y},[y]),i.useEffect(()=>{const oe=$t.current;if(!oe)return;oe.scrollHeight-oe.scrollTop-oe.clientHeight<32&&(oe.scrollTop=oe.scrollHeight)},[y]),i.useEffect(()=>{if(m.type!=="loading"){$(null),J(0);return}const oe=Date.now();$(oe),J(0);const ct=setInterval(()=>{J(Math.max(0,Math.floor((Date.now()-oe)/1e3)))},1e3);return()=>clearInterval(ct)},[m.type]),i.useEffect(()=>{if(m.type!=="loading")return;const oe=O.current;if(!oe)return;let ct=!1;const wt=setInterval(async()=>{try{const ot=await ji(oe);if(ct||!ot||O.current!==oe)return;if(ot.status==="awaiting_input"&&ot.currentQuestion){const vt=JSON.parse(ot.currentQuestion);h({type:"question",session:{sessionId:oe,currentQuestion:vt,summary:null}}),N("")}else if(ot.status==="complete"&&ot.result){const vt=JSON.parse(ot.result);h({type:"summary",session:{sessionId:oe,currentQuestion:null,summary:vt},summary:vt}),S(vt),N("")}}catch{}},8e3);return()=>{ct=!0,clearInterval(wt)}},[m.type]);const qt=i.useCallback(()=>{u(""),h({type:"initial"}),p(null),x([]),b([]),S(null),N(""),_(!1),U(!1),Z(void 0),Oe(void 0),He("medium"),$e(""),O.current=null,le(null)},[]),kn=PT(we,fe),nn=i.useCallback((oe,ct)=>{if(!oe||!ct)return st.provider&&st.modelId?`${st.provider}/${st.modelId}`:"Using default";const rt=he.find(wt=>wt.provider===oe&&wt.id===ct);return rt?`${rt.provider}/${rt.id}`:`${oe}/${ct}`},[he,st.modelId,st.provider]),Xt=i.useCallback(async()=>{je(!0),Pe(null);try{const oe=await Os();ue(oe.models),Me(oe.favoriteProviders),mt(oe.favoriteModels),Ze({provider:oe.resolvedPlanningProvider,modelId:oe.resolvedPlanningModelId})}catch(oe){Pe(_e(oe)||"Failed to load models")}finally{je(!1)}},[]),Gt=i.useCallback(oe=>{Me(ct=>{const rt=ct,ot=rt.includes(oe)?rt.filter(vt=>vt!==oe):[oe,...rt];return Dn({favoriteProviders:ot,favoriteModels:We}).catch(()=>{Me(rt)}),ot})},[We]),ln=i.useCallback(oe=>{mt(ct=>{const rt=ct,ot=rt.includes(oe)?rt.filter(vt=>vt!==oe):[oe,...rt];return Dn({favoriteProviders:ie,favoriteModels:ot}).catch(()=>{mt(rt)}),ot})},[ie]),ye=i.useCallback(oe=>{P.current?.close();const ct=()=>O.current!==oe,rt=Pj(oe,l,{onThinking:wt=>{ct()||(N(ot=>ot+wt),Q({sessionId:oe,status:"generating",needsInput:!1,owningTabId:ve,type:"planning",title:d.trim()||void 0,projectId:l??null}))},onQuestion:wt=>{if(ct())return;_(!1),U(!1),Ra(l);const ot=Ft.current.trim();ot&&b(vt=>vt[vt.length-1]?.thinkingOutput===ot?vt:[...vt,{thinkingOutput:ot}]),h({type:"question",session:{sessionId:oe,currentQuestion:wt,summary:null}}),N(""),Q({sessionId:oe,status:"awaiting_input",needsInput:!0,owningTabId:ve,type:"planning",title:d.trim()||void 0,projectId:l??null})},onSummary:wt=>{if(ct())return;_(!1),U(!1),Ra(l);const ot=Ft.current.trim();ot&&b(vt=>vt[vt.length-1]?.thinkingOutput===ot?vt:[...vt,{thinkingOutput:ot}]),h({type:"summary",session:{sessionId:oe,currentQuestion:null,summary:wt},summary:wt}),S(wt),N(""),Q({sessionId:oe,status:"complete",needsInput:!1,owningTabId:ve,type:"planning",title:d.trim()||void 0,projectId:l??null})},onError:wt=>{const ot=wt||"Session failed while contacting the AI.";_(!0),(async()=>{try{const vt=await ji(oe);if(vt&&(vt.status==="generating"||vt.status==="awaiting_input")){ye(oe);return}}catch{}_(!1),U(!1),p(null),h(vt=>vt.type==="question"||vt.type==="summary"||vt.type==="error"?{type:"error",session:vt.session,errorMessage:ot}:{type:"error",session:{sessionId:oe,currentQuestion:null,summary:null},errorMessage:ot}),N(""),O.current=oe,Q({sessionId:oe,status:"error",needsInput:!1,owningTabId:ve,type:"planning",title:d.trim()||void 0,projectId:l??null}),ne({sessionId:oe,status:"error"})})()},onComplete:()=>{_(!1),U(!1),O.current=null,ne({sessionId:oe,status:"complete"})},onConnectionStateChange:wt=>{_(wt==="reconnecting")}});P.current=rt},[ne,Q,d,l,ve]),Le=i.useCallback(async oe=>{const ct=oe??d;if(ct.trim()){p(null),N(""),b([]),x([]),_(!1),h({type:"loading"});try{const rt=we&&fe?{planningModelProvider:we,planningModelId:fe}:void 0,wt=Je.trim()?Number.parseInt(Je,10):void 0,ot=I.current,{sessionId:vt}=await hj(ct.trim(),l,rt,{planningDepth:Ve,customQuestionCount:Number.isInteger(wt)?wt:void 0},ot??void 0);I.current=null,O.current=vt,le(vt),pe(vt),ye(vt),x([])}catch(rt){_(!1),p(_e(rt)||"Failed to start planning session"),h({type:"initial"}),O.current=null,le(null)}}},[ye,Je,d,Ve,fe,we,l]);i.useEffect(()=>{e&&m.type==="initial"&&B.current?.focus()},[e,m.type]),i.useEffect(()=>{e&&Xt()},[e,Xt]),i.useEffect(()=>{if(e&&o&&!j.current&&m.type==="initial"){u(o);const oe=setTimeout(()=>{j.current=!0,Le(o)},0);return()=>clearTimeout(oe)}else if(e&&!o&&!j.current&&!E.current&&m.type==="initial"){E.current=!0;const oe=OR(l);oe&&u(oe)}},[e,o,m.type,Le,l]);const ae=i.useCallback(async oe=>{P.current?.close(),P.current=null,p(null),N(""),x([]),b([]),S(null),U(!1),h({type:"loading"});try{const ct=await ji(oe);if(!ct){pe(null),Be(!1),h({type:"initial"});return}O.current=oe,le(oe);const rt=Ga(ct.conversationHistory);if(b(rt),x(rt.map(wt=>wt.response).filter(wt=>!!(wt&&typeof wt=="object"&&!Array.isArray(wt)))),ct.status==="draft"){let wt="",ot,vt;try{const Wt=ct.inputPayload?JSON.parse(ct.inputPayload):null;Wt&&typeof Wt.initialPlan=="string"&&(wt=Wt.initialPlan),Wt&&typeof Wt.modelProvider=="string"&&typeof Wt.modelId=="string"&&(ot=Wt.modelProvider,vt=Wt.modelId)}catch{}u(wt),Z(ot),Oe(vt),I.current=oe,It.current=wt?{sessionId:oe,initialPlan:wt.trim(),modelProvider:ot,modelId:vt}:null,h({type:"initial"})}else if(ct.status==="awaiting_input"&&ct.currentQuestion){Ra(l);const wt=JSON.parse(ct.currentQuestion);if(h({type:"question",session:{sessionId:oe,currentQuestion:wt,summary:null}}),ct.thinkingOutput){const ot=ct.thinkingOutput.trim();ot&&b(vt=>vt[vt.length-1]?.thinkingOutput===ot?vt:[...vt,{thinkingOutput:ot}])}ye(oe)}else if(ct.status==="complete"&&ct.result){Ra(l);const wt=JSON.parse(ct.result);h({type:"summary",session:{sessionId:oe,currentQuestion:null,summary:wt},summary:wt}),S(wt)}else ct.status==="generating"?(h({type:"loading"}),ct.thinkingOutput&&N(ct.thinkingOutput),ye(oe)):ct.status==="error"&&h({type:"error",session:{sessionId:oe,currentQuestion:null,summary:null},errorMessage:ct.error||"Session failed"})}catch{p("Failed to load session"),h({type:"initial"})}},[ye,l]);i.useEffect(()=>{!e||!c||O.current!==c&&Y.current!==c&&(pe(c),Be(!0),ae(c))},[e,c]),i.useEffect(()=>{e&&be&&(c&&c===be||ae(be))},[e]);const Te=i.useCallback(async()=>{De(!0);try{const ct=(await nu(l,{includeCompleted:!0,includeArchived:ft})).filter(rt=>rt.type==="planning").sort((rt,wt)=>Date.parse(wt.updatedAt)-Date.parse(rt.updatedAt));Ue(ct)}catch{}finally{De(!1)}},[l,ft]);i.useEffect(()=>{e&&Te()},[e,Te]);const Ne=i.useRef(!1);i.useEffect(()=>{const oe=Ne.current&&!kt;Ne.current=kt,oe&&Vt==="mobile"&&(Re||c||be||Ae.length>0||Be(!0))},[Vt,Re,c,be,kt,Ae.length]),i.useEffect(()=>{if(!e)return;const oe=l?`?projectId=${encodeURIComponent(l)}`:"",ct=wt=>{try{const ot=JSON.parse(wt.data);if(ot.type!=="planning")return;Ue(vt=>{const Wt=vt.findIndex(pn=>pn.id===ot.id);return(Wt>=0?[...vt.slice(0,Wt),ot,...vt.slice(Wt+1)]:[ot,...vt]).sort((pn,Hn)=>Date.parse(Hn.updatedAt)-Date.parse(pn.updatedAt))})}catch{}},rt=wt=>{try{const ot=JSON.parse(wt.data);Ue(vt=>vt.filter(Wt=>Wt.id!==ot))}catch{}};return gi(`/api/events${oe}`,{events:{"ai_session:updated":ct,"ai_session:deleted":rt},onReconnect:()=>{Te()}})},[e,l,Te]);const ee=i.useCallback(oe=>{if(be===oe){Be(!0);return}pe(oe),Be(!0),ae(oe)},[ae,be]),Ie=i.useCallback(()=>{P.current?.close(),P.current=null,I.current=null,w.current&&(clearTimeout(w.current),w.current=null),c&&(Y.current=c),qt(),pe(null),Be(!0)},[qt,c]),St=i.useCallback(()=>{Be(!1)},[]),pt=i.useCallback(async(oe,ct)=>{const rt=ct.trim();if(!(!rt||It.current?.sessionId===oe&&It.current.initialPlan===rt&&It.current.modelProvider===we&&It.current.modelId===fe))try{await N1(oe,{initialPlan:rt,modelProvider:we&&fe?we:void 0,modelId:we&&fe?fe:void 0},l),It.current={sessionId:oe,initialPlan:rt,modelProvider:we,modelId:fe}}catch{}},[fe,we,l]);i.useEffect(()=>{if(Rt.current&&(clearTimeout(Rt.current),Rt.current=null),!(!e||m.type!=="initial"||!be))return Rt.current=setTimeout(()=>{pt(be,d)},500),()=>{Rt.current&&(clearTimeout(Rt.current),Rt.current=null)}},[d,e,be,pt,m.type]),i.useEffect(()=>{It.current=null},[be]),i.useEffect(()=>()=>{Rt.current&&(clearTimeout(Rt.current),Rt.current=null)},[]);const Dt=i.useCallback(async oe=>{const ct=wt=>wt==="generating"||wt==="awaiting_input",rt=Ae.find(wt=>wt.id===oe);if(rt&&ct(rt.status))try{await Lf(oe,l,ve)}catch{}try{await Vf(oe)}catch{}ne({sessionId:oe,status:"complete",timestamp:Date.now()}),Ue(wt=>wt.filter(ot=>ot.id!==oe)),be===oe&&(P.current?.close(),P.current=null,qt(),pe(null),Be(!1)),me(null)},[ne,Ae,l,qt,be,ve]),Ut=i.useCallback(async oe=>{const rt=Ae.find(wt=>wt.id===oe)?.archived===!0;try{rt?await v1(oe):await x1(oe)}catch{return}Ue(wt=>!rt&&!ft?wt.filter(ot=>ot.id!==oe):wt.map(ot=>ot.id===oe?{...ot,archived:!rt}:ot)),!rt&&be===oe&&!ft&&(P.current?.close(),P.current=null,qt(),pe(null),Be(!1))},[Ae,qt,be,Be,ft]);i.useEffect(()=>{e||(j.current=!1,E.current=!1,_(!1),U(!1),le(null))},[e]),i.useEffect(()=>{if(!e){dt.current&&(z(dt.current,ve),dt.current=null);return}if(re&&dt.current!==re){dt.current&&z(dt.current,ve),H(re,ve),dt.current=re;return}!re&&dt.current&&(z(dt.current,ve),dt.current=null)},[H,z,e,re,ve]),i.useEffect(()=>{if(!e||!re||dt.current!==re)return;W(ve);const oe=setInterval(()=>{W(ve)},3e4);return()=>{clearInterval(oe)}},[W,e,re,ve]),i.useEffect(()=>()=>{w.current&&(clearTimeout(w.current),w.current=null),P.current?.close(),P.current=null,dt.current&&(z(dt.current,ve),dt.current=null)},[z,ve]),i.useEffect(()=>{if(!e)return;const oe=()=>{P.current?.close(),P.current=null};return window.addEventListener("beforeunload",oe),()=>window.removeEventListener("beforeunload",oe)},[e]);const Ce=i.useCallback((oe,ct)=>{Rt.current&&(clearTimeout(Rt.current),Rt.current=null),(async()=>{try{await pt(oe,ct),await S1(oe,l)}catch{}})()},[l,pt]),et=i.useCallback(()=>{if(Vt!=="mobile")return;const oe=document.activeElement;oe instanceof HTMLElement&&oe.blur(),window.scrollTo(0,0),requestAnimationFrame(()=>{window.scrollTo(0,0)})},[Vt]),tt=i.useCallback(()=>{d&&m.type==="initial"&&LR(d,l);const oe=I.current;oe&&d.trim()&&Ce(oe,d),I.current=null,w.current&&(clearTimeout(w.current),w.current=null),P.current?.close(),P.current=null,_(!1),U(!1),et(),n()},[Ce,d,n,l,et,m.type]);i.useEffect(()=>{if(!e)return;const oe=ct=>{ct.key==="Escape"&&tt()};return document.addEventListener("keydown",oe),()=>document.removeEventListener("keydown",oe)},[e,tt]);const Lt=i.useCallback(async oe=>{if(m.type!=="question")return;const{session:ct}=m,rt=ct.sessionId,wt=ct.currentQuestion;if(!wt){p("No active question in session");return}p(null),x(ot=>[...ot,oe]),b(ot=>{const vt=Ft.current.trim();let Wt=ot;return vt&&Wt[Wt.length-1]?.thinkingOutput!==vt&&(Wt=[...Wt,{thinkingOutput:vt}]),[...Wt,{question:wt,response:oe}]}),h({type:"loading"}),N("");try{await Ku(rt,oe,l,ve)}catch(ot){p(_e(ot)||"Failed to submit response"),h({type:"question",session:ct})}},[l,ve,m]),Zt=i.useCallback(async()=>{if(m.type!=="summary")return;const{session:oe,summary:ct}=m,rt=oe.sessionId;O.current=rt,le(rt),p(null),U(!1),N(""),h({type:"loading"}),ye(rt);try{await Ku(rt,{refine:!0},l,ve)}catch(wt){P.current?.close(),P.current=null,p(_e(wt)||"Failed to refine plan"),h({type:"summary",session:oe,summary:k??ct})}},[ye,k,l,ve,m]),sn=i.useCallback(async()=>{const oe=O.current;if(oe){try{await gj(oe,l,ve)}catch{}P.current?.close(),P.current=null,_(!1),U(!1),h({type:"error",session:{sessionId:oe,currentQuestion:null,summary:null},errorMessage:"Generation stopped by user. You can retry or start a new session."}),N("")}},[l,ve]),At=i.useCallback(async()=>{if(m.type!=="error")return;const oe=m.session;p(null),U(!0),N(""),h({type:"loading"}),ye(oe.sessionId);try{O.current=oe.sessionId,le(oe.sessionId),await fj(oe.sessionId,l,ve)}catch(ct){let rt=ct;if((_e(ct)||"").includes("not in an error state"))try{const ot=await ji(oe.sessionId);if(!ot)throw new Error("Failed to refresh planning session.");if(O.current=ot.id,le(ot.id),ot.status==="generating")N(ot.thinkingOutput??""),h({type:"loading"});else if(ot.status==="awaiting_input"){if(!ot.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const vt=JSON.parse(ot.currentQuestion);if(Ra(l),h({type:"question",session:{sessionId:ot.id,currentQuestion:vt,summary:null}}),ot.thinkingOutput){const Wt=ot.thinkingOutput.trim();Wt&&b(an=>an[an.length-1]?.thinkingOutput===Wt?an:[...an,{thinkingOutput:Wt}])}P.current?.isConnected()||ye(ot.id)}else if(ot.status==="complete"){if(!ot.result)throw new Error("Planning session is complete but has no result.");const vt=JSON.parse(ot.result);Ra(l),h({type:"summary",session:{sessionId:ot.id,currentQuestion:null,summary:vt},summary:vt}),S(vt)}else ot.status==="error"&&h({type:"error",session:{sessionId:ot.id,currentQuestion:null,summary:null},errorMessage:ot.error||"Retry failed. Please try again."});_(!1);return}catch(ot){rt=ot}P.current?.close(),P.current=null,h({type:"error",session:oe,errorMessage:_e(rt)||"Retry failed. Please try again."}),_(!1)}finally{U(!1)}},[ye,l,ve,m]),cn=i.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const oe=m.session.sessionId,ct=await bj(oe,k??void 0,l);s(ct),pe(null),Ue(rt=>rt.filter(wt=>wt.id!==oe)),ne({sessionId:oe,status:"complete",timestamp:Date.now()}),tt()}catch(oe){p(_e(oe)||"Failed to create task"),h({type:"summary",session:m.session,summary:m.summary})}}},[ne,k,m,l,s,tt]),Tn=i.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const oe=await xj(m.session.sessionId,k??void 0,l);le(oe.sessionId),h({type:"breakdown",sessionId:oe.sessionId,subtasks:oe.subtasks,dirty:!1})}catch(oe){p(_e(oe)||"Failed to start breakdown"),h({type:"summary",session:m.session,summary:m.summary})}}},[k,m,l]),En=i.useCallback(async()=>{if(m.type==="breakdown"){p(null),h({type:"creating"});try{const oe=m.sessionId,ct=await vj(oe,m.subtasks,l);a(ct.tasks),Ue(rt=>rt.filter(wt=>wt.id!==oe)),ne({sessionId:oe,status:"complete",timestamp:Date.now()}),u(""),h({type:"initial"}),p(null),x([]),b([]),S(null),N(""),Z(void 0),Oe(void 0),He("medium"),$e(""),O.current=null,le(null),pe(null),tt()}catch(oe){p(_e(oe)||"Failed to create tasks"),h({type:"breakdown",sessionId:m.sessionId,subtasks:m.subtasks,dirty:m.dirty})}}},[ne,tt,m,a,l]),bn=i.useCallback(async()=>{if(m.type!=="question"||g.length===0)return;const oe=m.session.sessionId;p(null),h({type:"loading"});try{const ct=await pj(oe,l,ve);x(ct.history.map(rt=>rt.response&&typeof rt.response=="object"&&!Array.isArray(rt.response)?rt.response:{[rt.question.id]:rt.response})),b(ct.history.map(rt=>({question:rt.question,response:rt.response&&typeof rt.response=="object"&&!Array.isArray(rt.response)?rt.response:{[rt.question.id]:rt.response},thinkingOutput:rt.thinkingOutput}))),N(""),h({type:"question",session:{...m.session,currentQuestion:ct.currentQuestion,summary:null}})}catch(ct){p(_e(ct)||"Failed to go back to the previous question"),h({type:"question",session:m.session})}},[l,g.length,ve,m]),In=()=>m.type==="question"?Math.min(g.length+1,3):3,ge=re?L.get(re):null,ut=ge&&ge.tabId!==ve,xn=de&&(!ut||ge.stale);return e?t.jsx("div",{className:"modal-overlay open",onMouseDown:oe=>{jt.current=oe.target===oe.currentTarget},onClick:oe=>{oe.target===oe.currentTarget&&jt.current&&tt(),jt.current=!1},role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",ref:se,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[Re&&t.jsx("button",{className:"modal-back planning-mobile-back",onClick:St,"aria-label":"Back to sessions",title:"Back to sessions",children:t.jsx(_l,{size:18})}),t.jsx(fi,{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:tt,"aria-label":"Close",children:t.jsx(en,{size:20})})})]}),t.jsxs("div",{className:`planning-modal-body planning-modal-body--split ${Re?"planning-modal-body--show-detail":"planning-modal-body--show-list"}`,children:[t.jsx(OT,{sessions:Ae,loading:kt,selectedSessionId:be,pendingDeleteId:at,showArchived:ft,onToggleShowArchived:()=>Et(oe=>!oe),onArchive:oe=>void Ut(oe),onSelectSession:ee,onNewSession:Ie,onRequestDelete:me,onConfirmDelete:oe=>void Dt(oe),onCancelDelete:()=>me(null)}),t.jsxs("div",{className:"planning-detail",children:[f&&t.jsx("div",{className:"form-error planning-error",children:f}),C&&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(ys,{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:B,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:oe=>{const ct=oe.target.value;u(ct),!(I.current||ct.trim().length===0)&&(w.current&&clearTimeout(w.current),w.current=setTimeout(()=>{if(I.current)return;const rt=ct.trim();if(!rt)return;mj(rt,l,we&&fe?{planningModelProvider:we,planningModelId:fe}:void 0).then(ot=>{I.current=ot.sessionId,Ue(vt=>vt.some(an=>an.id===ot.sessionId)?vt:[{id:ot.sessionId,type:"planning",status:"draft",title:ot.title,preview:rt.length>80?`${rt.slice(0,79).trimEnd()}…`:rt,projectId:l??null,lockedByTab:null,updatedAt:new Date().toISOString(),archived:!1},...vt].sort((an,pn)=>Date.parse(pn.updatedAt)-Date.parse(an.updatedAt))),pe(ot.sessionId)}).catch(()=>{})},300))},onKeyDown:oe=>{oe.key==="Enter"&&!oe.shiftKey&&d.trim()&&(oe.preventDefault(),Le())},onBlur:()=>{const oe=I.current;oe&&d.trim()&&Ce(oe,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:AT.map((oe,ct)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>u(oe),children:oe.length>40?oe.slice(0,40)+"...":oe},ct))})]}),t.jsx(ii,{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",Ee&&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:kn,onChange:oe=>{const{provider:ct,modelId:rt}=RT(oe);Z(ct),Oe(rt)},models:he,disabled:Ee,favoriteProviders:ie,onToggleFavorite:Gt,favoriteModels:We,onToggleModelFavorite:ln}),xe&&t.jsxs("div",{className:"form-hint form-hint-error",children:[xe," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{Xt()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${we&&fe?"model-badge-custom":"model-badge-default"}`,children:nn(we,fe)})})]}),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(oe=>t.jsx("button",{type:"button",className:`planning-depth-chip btn ${Ve===oe.value?"btn-primary planning-depth-chip-active":""}`,onClick:()=>He(oe.value),"aria-pressed":Ve===oe.value,children:oe.label},oe.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:Je,onChange:oe=>$e(oe.target.value),placeholder:"Auto"})]})]})]})]})})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>Le(),disabled:!d.trim(),children:[t.jsx(fi,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),m.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(bt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:y?"AI is thinking...":"Generating next question..."}),A&&t.jsxs("div",{className:"planning-elapsed",children:["Thinking… (",T,"s)"]}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>D(!M),type:"button",children:M?"Hide thinking":"Show thinking"}),t.jsx("div",{className:"planning-loading-actions",children:t.jsxs("button",{className:"btn planning-stop-btn",type:"button",onClick:()=>void sn(),children:[t.jsx(Zx,{size:14}),t.jsx("span",{className:"icon-ml-6",children:"Stop"})]})}),M&&y&&t.jsx("div",{className:"planning-thinking-output",ref:$t,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:[v.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(ri,{entries:v}),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 At(),disabled:F,children:[F?t.jsx(bt,{size:14,className:"spin"}):t.jsx(us,{size:14}),t.jsx("span",{className:"icon-ml-6",children:F?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:tt,disabled:F,children:"Dismiss"})]})]})]})}),m.type==="creating"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(bt,{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(IT,{question:m.session.currentQuestion,progress:In(),historyEntries:v,onSubmit:Lt,onBack:g.length>0?bn:void 0})}),m.type==="summary"&&k&&t.jsx($T,{summary:k,historyEntries:v,onSummaryChange:S,tasks:r,onCreateTask:cn,onBreakIntoTasks:Tn,onRefine:()=>{Zt()},isLoading:!1}),m.type==="breakdown"&&t.jsx(LT,{subtasks:m.subtasks,dirty:m.dirty,isLoading:!1,onUpdateSubtasks:oe=>h({...m,subtasks:oe,dirty:!0}),onCreateTasks:En,onBack:()=>{const ct={sessionId:m.sessionId,currentQuestion:null,summary:k??null};k&&h({type:"summary",session:ct,summary:k})}})]}),de&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Il,{size:16}),t.jsx("span",{children:xn?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),xn&&t.jsx("button",{type:"button",onClick:()=>{Fe()},disabled:X,className:"btn btn-primary session-lock-take-control",children:X?"Taking control...":"Take Control"})]})})]})]})}):null}function IT({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(ri,{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 v=x.target.checked?[...g,p.id]:g.filter(b=>b!==p.id);l({[e.id]:v})}}),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(en,{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(to,{size:16,className:"icon-ml-4"})]})]})]})}function $T({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=p=>{const g=m.includes(p)?m.filter(x=>x!==p):[...m,p];h(g),s({...e,suggestedDependencies:g})};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(ii,{summary:"Show user Q&A",className:"planning-summary-qa-disclosure",children:[t.jsx(ri,{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:p=>s({...e,description:p.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Size"}),t.jsxs("select",{className:"planning-size-select",value:e.suggestedSize,onChange:p=>s({...e,suggestedSize:p.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)"})]})]}),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(p=>t.jsxs("label",{className:`planning-dep-chip ${m.includes(p.id)?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:m.includes(p.id),onChange:()=>f(p.id)}),t.jsx("span",{className:"planning-dep-id",children:p.id}),t.jsx("span",{className:"planning-dep-title",children:p.title||p.description.slice(0,30)})]},p.id))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Key Deliverables"}),t.jsx("ul",{className:"planning-deliverables",children:e.keyDeliverables.map((p,g)=>t.jsx("li",{children:p},g))})]})]})]}),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(bt,{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(bt,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Tl,{size:16,className:"icon-mr-8"}),"Break into Tasks"]})})]})]})]})}function bp(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 DT(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function LT({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(N=>!N.title.trim())?!0:bp(e),[e]),g=i.useCallback((N,M)=>{a(e.map(D=>D.id===N?{...D,...M}:D))},[e,a]),x=i.useCallback(()=>{a([...e,DT(e.length+1)])},[e,a]),v=i.useCallback(N=>{a(e.filter(M=>M.id!==N).map(M=>({...M,dependsOn:M.dependsOn.filter(D=>D!==N)})))},[e,a]),b=i.useCallback((N,M)=>{if(M<0||M>=e.length)return;const D=[...e],[C]=D.splice(N,1);D.splice(M,0,C),a(D)},[e,a]),k=i.useCallback(N=>M=>{c(N),M.dataTransfer.setData("text/plain",N),M.dataTransfer.effectAllowed="move"},[]),S=i.useCallback(()=>{c(null),u(null),h(null)},[]),j=i.useCallback(N=>M=>{if(M.preventDefault(),N===l)return;const D=M.currentTarget.getBoundingClientRect(),C=D.top+D.height/2,_=M.clientY<C?"before":"after";u(N),h(_)},[l]),E=i.useCallback(N=>M=>{M.preventDefault();const D=M.dataTransfer.getData("text/plain");if(!D||D===N){S();return}const C=e.findIndex($=>$.id===D),_=e.findIndex($=>$.id===N);if(C===-1||_===-1){S();return}const F=[...e],[U]=F.splice(C,1);let A=_;m==="after"&&C<_&&A--,m==="after"&&A++,F.splice(A,0,U),a(F),S()},[e,m,a,S]),y=i.useCallback(N=>{const M=N.currentTarget.getBoundingClientRect(),D=N.clientX,C=N.clientY;(D<M.left||D>M.right||C<M.top||C>M.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(Tl,{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, and dependencies before creating."})]}),t.jsxs("div",{className:"planning-summary-form",children:[e.map((N,M)=>{const D=l===N.id,C=d===N.id,_=["task-detail-section","subtask-item",D?"subtask-item-dragging":"",C?"subtask-item-drop-target":"",C&&m==="before"?"subtask-item-drop-before":"",C&&m==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:_,"data-testid":`subtask-item-${M}`,draggable:!s,onDragStart:k(N.id),onDragEnd:S,onDragOver:j(N.id),onDrop:E(N.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(Rl,{size:16}),t.jsx("strong",{children:N.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>b(M,M-1),disabled:s||M===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(oa,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>b(M,M+1),disabled:s||M===e.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(eo,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>v(N.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:F=>{f.current[M]=F},value:N.title,onChange:F=>g(N.id,{title:F.target.value}),onKeyDown:F=>{F.key==="Enter"&&(F.preventDefault(),M<e.length-1&&f.current[M+1]?.focus())},disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:N.description,onChange:F=>g(N.id,{description:F.target.value}),disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:N.suggestedSize,onChange:F=>g(N.id,{suggestedSize:F.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",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[e.slice(0,M).filter(F=>F.id!==N.id).map(F=>{const U=N.dependsOn.includes(F.id);return t.jsxs("label",{className:`planning-dep-chip ${U?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:U,onChange:()=>{const A=U?N.dependsOn.filter($=>$!==F.id):[...N.dependsOn,F.id];g(N.id,{dependsOn:A})},disabled:s}),t.jsx("span",{className:"planning-dep-id",children:F.id}),t.jsx("span",{className:"planning-dep-title",children:F.title||"Untitled"})]},F.id)}),M===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),M>0&&e.slice(0,M).filter(F=>F.id!==N.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},N.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:x,disabled:s,children:[t.jsx(Cn,{size:16,className:"icon-mr-6"})," Add subtask"]}),bp(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(bt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]})}function OT({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(py,{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,v=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(FT,{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(zT,{status:f.status}),t.jsx("span",{"aria-hidden":!0,children:" · "}),t.jsx("span",{children:UT(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:[v&&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(Cx,{size:14}):t.jsx(Zr,{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 FT({status:e}){switch(e){case"generating":return t.jsx(bt,{size:14,className:"spin planning-sidebar-status-icon planning-sidebar-status-generating"});case"awaiting_input":return t.jsx(dd,{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(Rs,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-error"});default:return t.jsx(Oi,{size:14,className:"planning-sidebar-status-icon"})}}function zT({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 UT(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 BT(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function xp(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 HT({isOpen:e,onClose:n,initialDescription:s,onTasksCreated:a,parentTaskId:r,projectId:o,resumeSessionId:l}){const c=oi();Mi(e);const{keyboardOverlap:d,viewportHeight:u,viewportOffsetTop:m,keyboardOpen:h}=ya({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,v]=i.useState([]),[b,k]=i.useState([]),[S,j]=i.useState(""),[E,y]=i.useState(!0),[N,M]=i.useState(!1),[D,C]=i.useState(!1),[_,F]=i.useState(s),[U,A]=i.useState(null),[$,T]=i.useState(!1),[J,B]=i.useState(null),[se,P]=i.useState(null),[O,I]=i.useState(null),w=i.useRef(null),Y=i.useRef([]),re=i.useRef(!1),le=i.useRef(null),ve=p.type==="generating"||p.type==="editing"||p.type==="creating"||p.type==="error"?p.sessionId:null,de=i.useMemo(()=>va(),[]),{isLockedByOther:Fe,takeControl:X,isLoading:L}=Gl(e?ve:null),{activeTabMap:Q,broadcastUpdate:ne,broadcastCompleted:H,broadcastLock:z,broadcastUnlock:W,broadcastHeartbeat:we}=lr(),Z=i.useMemo(()=>x.length===0||x.some(be=>!be.title.trim())?!0:xp(x),[x]),fe=p.type==="generating"||p.type==="editing"||p.type==="error",Oe=ve?Q.get(ve):null,{confirm:Ve}=Qs(),He=Oe&&Oe.tabId!==de,Je=!!(He&&!Oe.stale),$e=Fe&&(!He||Oe.stale),he=i.useCallback(()=>{_&&FR(_,o),w.current?.close(),w.current=null,g({type:"initial"}),v([]),k([]),j(""),y(!0),M(!1),C(!1),A(null),T(!1),re.current=!1},[_,o]),ue=i.useCallback(()=>{w.current?.close(),w.current=null,n()},[n]),Ee=i.useCallback(async()=>{if(!(($||p.type==="editing"||p.type==="creating")&&!await Ve({title:"Discard Changes",message:"Close subtask breakdown? Unsaved changes will be lost.",danger:!0}))){if(ve)try{await zf(ve,o,de)}catch{}he(),n()}},[$,n,he,ve,de,p.type,o,Ve]),je=i.useCallback(be=>{w.current?.close(),w.current=Gj(be,o,{onThinking:pe=>{j(Re=>Re+pe),ne({sessionId:be,status:"generating",needsInput:!1,owningTabId:de,type:"subtask",title:_.trim()||void 0,projectId:o??null})},onSubtasks:pe=>{M(!1),C(!1),Bc(o),v(pe),g({type:"editing",sessionId:be}),T(!1),ne({sessionId:be,status:"awaiting_input",needsInput:!0,owningTabId:de,type:"subtask",title:_.trim()||void 0,projectId:o??null})},onError:pe=>{const Re=pe||"Session failed while contacting the AI.";M(!1),C(!1),A(null),g({type:"error",sessionId:be,errorMessage:Re}),ne({sessionId:be,status:"error",needsInput:!1,owningTabId:de,type:"subtask",title:_.trim()||void 0,projectId:o??null}),H({sessionId:be,status:"error"})},onComplete:()=>{H({sessionId:be,status:"complete"})},onConnectionStateChange:pe=>{M(pe==="reconnecting")}})},[H,ne,_,o,de]),xe=i.useCallback(async()=>{if(_.trim()){A(null),k([]),j(""),M(!1);try{const{sessionId:be}=await Vj(_.trim(),o);g({type:"generating",sessionId:be}),je(be)}catch(be){A(_e(be)||"Failed to start subtask breakdown"),g({type:"initial"})}}},[je,_,o]);i.useEffect(()=>{if(!e){he();return}if(e&&s&&!re.current)F(s),re.current=!0,xe();else if(e&&!s&&!re.current){const be=zR(o);be&&F(be)}},[e,s,xe,he]),i.useEffect(()=>{!e||!l||p.type!=="initial"||(async()=>{try{const be=await ji(l);if(!be)return;const pe=Ga(be.conversationHistory);if(k(pe),be.status==="generating"||be.status==="awaiting_input")j(be.thinkingOutput??""),g({type:"generating",sessionId:l}),je(l);else if(be.status==="complete"&&be.result){Bc(o);const Re=JSON.parse(be.result);v(Re),g({type:"editing",sessionId:l})}else be.status==="error"&&(A(null),g({type:"error",sessionId:l,errorMessage:be.error??"Session encountered an error"}))}catch(be){A(_e(be)||"Failed to resume session")}})()},[je,e,l,p.type,o]),i.useEffect(()=>{if(!e){le.current&&(W(le.current,de),le.current=null);return}if(ve&&le.current!==ve){le.current&&W(le.current,de),z(ve,de),le.current=ve;return}!ve&&le.current&&(W(le.current,de),le.current=null)},[z,W,e,ve,de]),i.useEffect(()=>{if(!e||!ve||le.current!==ve)return;we(de);const be=setInterval(()=>{we(de)},3e4);return()=>{clearInterval(be)}},[we,e,ve,de]),i.useEffect(()=>()=>{w.current?.close(),le.current&&(W(le.current,de),le.current=null)},[W,de]),i.useEffect(()=>{if(!e)return;const be=pe=>{pe.key==="Escape"&&(pe.preventDefault(),Ee())};return document.addEventListener("keydown",be),()=>document.removeEventListener("keydown",be)},[e,Ee]);const Pe=i.useCallback((be,pe)=>{v(Re=>Re.map(Be=>Be.id===be?{...Be,...pe}:Be)),T(!0)},[]),ie=i.useCallback(()=>{v(be=>[...be,BT(be.length+1)]),T(!0)},[]),Me=i.useCallback(be=>{v(pe=>pe.filter(Re=>Re.id!==be).map(Re=>({...Re,dependsOn:Re.dependsOn.filter(Be=>Be!==be)}))),T(!0)},[]),We=i.useCallback(be=>pe=>{B(be),pe.dataTransfer.setData("text/plain",be),pe.dataTransfer.effectAllowed="move"},[]),mt=i.useCallback(()=>{B(null),P(null),I(null)},[]),st=i.useCallback(be=>pe=>{if(pe.preventDefault(),be===J)return;const Re=pe.currentTarget.getBoundingClientRect(),Be=Re.top+Re.height/2,at=pe.clientY<Be?"before":"after";P(be),I(at)},[J]),Ze=i.useCallback(be=>pe=>{pe.preventDefault();const Re=pe.dataTransfer.getData("text/plain");if(!Re||Re===be){B(null),P(null),I(null);return}v(Be=>{const at=Be.findIndex($t=>$t.id===Re),me=Be.findIndex($t=>$t.id===be);if(at===-1||me===-1)return Be;const ft=[...Be],[Et]=ft.splice(at,1);let jt=me;return O==="after"&&at<me&&jt--,O==="after"&&jt++,ft.splice(jt,0,Et),ft}),T(!0),B(null),P(null),I(null)},[O]),dt=i.useCallback(be=>{const pe=be.currentTarget.getBoundingClientRect(),Re=be.clientX,Be=be.clientY;(Re<pe.left||Re>pe.right||Be<pe.top||Be>pe.bottom)&&(P(null),I(null))},[]),Ae=i.useCallback((be,pe)=>{pe<0||pe>=x.length||(v(Re=>{const Be=[...Re],[at]=Be.splice(be,1);return Be.splice(pe,0,at),Be}),T(!0))},[x.length]),Ue=i.useCallback(be=>{Y.current[be+1]?.focus()},[]),kt=i.useCallback(async()=>{if(!(!ve||Z)){A(null),g({type:"creating",sessionId:ve});try{const be=await Jj(ve,x,r,o);a(be.tasks),he(),n()}catch(be){A(_e(be)||"Failed to create tasks"),g({type:"editing",sessionId:ve})}}},[Z,n,a,r,o,he,ve,x]),De=i.useCallback(async()=>{if(p.type!=="error")return;const be=p.sessionId;A(null),C(!0),j(""),g({type:"generating",sessionId:be}),je(be);try{await Wj(be,o,de)}catch(pe){let Re=pe;if((_e(pe)||"").includes("not in an error state"))try{const at=await ji(be);if(!at)throw new Error("Failed to refresh subtask session.");if(k(Ga(at.conversationHistory)),at.status==="generating"||at.status==="awaiting_input")j(at.thinkingOutput??""),g({type:"generating",sessionId:at.id}),w.current?.isConnected()||je(at.id);else if(at.status==="complete"){if(!at.result)throw new Error("Subtask session is complete but has no result.");Bc(o);const me=JSON.parse(at.result);v(me),g({type:"editing",sessionId:at.id}),T(!1)}else at.status==="error"&&g({type:"error",sessionId:at.id,errorMessage:at.error??"Retry failed. Please try again."});M(!1);return}catch(at){Re=at}w.current?.close(),w.current=null,g({type:"error",sessionId:be,errorMessage:_e(Re)||"Retry failed. Please try again."}),M(!1)}finally{C(!1)}},[je,o,de,p]);return e?t.jsx("div",{className:"modal-overlay open",onClick:be=>be.target===be.currentTarget&&void Ee(),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(Tl,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Subtask Breakdown"})]}),t.jsxs("div",{className:"modal-header-actions",children:[fe&&t.jsx("button",{className:"modal-send-to-background",onClick:ue,title:"Send to background","aria-label":"Send to background",children:t.jsx(io,{size:16})}),t.jsx("button",{className:"modal-close",onClick:()=>void Ee(),"aria-label":"Close",children:t.jsx(en,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[U&&t.jsx("div",{className:"form-error planning-error",children:U}),N&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Je&&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:_})]})}),p.type==="generating"&&t.jsxs("div",{className:"planning-loading",children:[b.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(ri,{entries:b,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsx(bt,{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&&S&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:S})})]})]}),p.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[b.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(ri,{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 De(),disabled:D,children:[D?t.jsx(bt,{size:14,className:"spin"}):t.jsx(us,{size:14}),t.jsx("span",{className:"icon-ml-6",children:D?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:()=>void Ee(),disabled:D,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(ri,{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:[x.map((be,pe)=>{const Re=J===be.id,Be=se===be.id,at=["task-detail-section","subtask-item",Re?"subtask-item-dragging":"",Be?"subtask-item-drop-target":"",Be&&O==="before"?"subtask-item-drop-before":"",Be&&O==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:at,"data-testid":`subtask-item-${pe}`,draggable:p.type!=="creating",onDragStart:We(be.id),onDragEnd:mt,onDragOver:st(be.id),onDrop:Ze(be.id),onDragLeave:dt,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(Rl,{size:16}),t.jsx("strong",{children:be.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ae(pe,pe-1),disabled:p.type==="creating"||pe===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(oa,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ae(pe,pe+1),disabled:p.type==="creating"||pe===x.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(eo,{})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>Me(be.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:me=>{Y.current[pe]=me},value:be.title,onChange:me=>Pe(be.id,{title:me.target.value}),onKeyDown:me=>{me.key==="Enter"&&(me.preventDefault(),Ue(pe))},disabled:p.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:8,value:be.description,onChange:me=>Pe(be.id,{description:me.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:be.suggestedSize,onChange:me=>Pe(be.id,{suggestedSize:me.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,pe).filter(me=>me.id!==be.id).map(me=>{const ft=be.dependsOn.includes(me.id);return t.jsxs("label",{className:`planning-dep-chip ${ft?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:ft,onChange:()=>{const Et=ft?be.dependsOn.filter(jt=>jt!==me.id):[...be.dependsOn,me.id];Pe(be.id,{dependsOn:Et})},disabled:p.type==="creating"}),t.jsx("span",{className:"planning-dep-id",children:me.id}),t.jsx("span",{className:"planning-dep-title",children:me.title||"Untitled"})]},me.id)}),pe===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),pe>0&&x.slice(0,pe).filter(me=>me.id!==be.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},be.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:ie,disabled:p.type==="creating",children:[t.jsx(Cn,{size:16,className:"icon-mr-6"})," Add subtask"]}),xp(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 Ee(),disabled:p.type==="creating",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:()=>void kt(),disabled:p.type==="creating"||Z,children:p.type==="creating"?t.jsxs(t.Fragment,{children:[t.jsx(bt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]}),Fe&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Il,{size:16}),t.jsx("span",{children:$e?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),$e&&t.jsx("button",{type:"button",onClick:()=>{X()},disabled:L,className:"btn btn-primary session-lock-take-control",children:L?"Taking control...":"Take Control"})]})})]})]})}):null}const qT=5,VT=1e3,WT=45e3;function Wo(){return{scrollback:null,connected:null,data:[]}}function KT(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),v=i.useRef(new Set),b=i.useRef(new Set),k=i.useRef(Wo()),S=i.useCallback(A=>{p.current.add(A);const $=k.current;return $.data.length>0&&($.data.forEach(T=>A(T)),$.data=[]),()=>p.current.delete(A)},[]),j=i.useCallback(A=>(g.current.add(A),()=>g.current.delete(A)),[]),E=i.useCallback(A=>{x.current.add(A);const $=k.current;return $.connected&&(A($.connected),$.connected=null),()=>x.current.delete(A)},[]),y=i.useCallback(A=>{v.current.add(A);const $=k.current;return $.scrollback&&(A($.scrollback),$.scrollback=null),()=>v.current.delete(A)},[]),N=i.useCallback(A=>(b.current.add(A),()=>b.current.delete(A)),[]),M=i.useCallback(A=>{const $=d.current;$?.readyState===WebSocket.OPEN&&$.send(JSON.stringify({type:"input",data:A}))},[]),D=i.useCallback((A,$)=>{const T=d.current;T?.readyState===WebSocket.OPEN&&T.send(JSON.stringify({type:"resize",cols:A,rows:$}))},[]),C=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),k.current=Wo()},[]),_=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),k.current=Wo()},[]),F=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 A=r.current;let T=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(e)}`;n&&(T+=`&projectId=${encodeURIComponent(n)}`);const J=new WebSocket(Ni(T));d.current=J,J.onopen=()=>{if(r.current!==A){J.close();return}k.current=Wo(),a("connected"),u.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===A&&J.readyState===WebSocket.OPEN&&J.send(JSON.stringify({type:"ping"}))},WT)},J.onmessage=B=>{if(r.current===A)try{const se=JSON.parse(B.data),P=k.current;switch(se.type){case"data":se.data&&(p.current.size===0&&P.data.push(se.data),p.current.forEach(O=>O(se.data)));break;case"scrollback":se.data&&(P.scrollback=se.data,v.current.forEach(O=>O(se.data)));break;case"connected":se.shell&&se.cwd&&(P.connected={shell:se.shell,cwd:se.cwd},x.current.forEach(O=>O({shell:se.shell,cwd:se.cwd})));break;case"exit":se.exitCode!==void 0&&g.current.forEach(O=>O(se.exitCode));break;case"ping":J.readyState===WebSocket.OPEN&&J.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},J.onclose=B=>{if(r.current!==A)return;if(d.current=null,h.current&&(clearInterval(h.current),h.current=null),f.current){a("disconnected");return}if(B.code===4e3||B.code===4004){a("disconnected"),B.code===4004&&b.current.forEach(O=>O());return}if(u.current++,u.current>qT){a("disconnected");return}const se=VT*Math.pow(2,u.current-1);a("reconnecting");const P=r.current;m.current=setTimeout(()=>{r.current===P&&(f.current||F())},Math.min(se,16e3))},J.onerror=()=>{}},[e,n]),U=i.useCallback(()=>{u.current=0,_(),F()},[_,F]);return i.useEffect(()=>(c&&(C(),u.current=0,a("disconnected")),e?F():a("disconnected"),_),[e,n,c,F,_,C]),{connectionStatus:s,sendInput:M,resize:D,onData:S,onExit:j,onConnect:E,onScrollback:y,reconnect:U,onSessionInvalid:N}}const Lb="kb-terminal-tabs",GT=15e3,JT=15e3;function vp(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function yp(e){if(typeof window>"u")return[];try{const n=ss(Lb,e);if(n)return JSON.parse(n)}catch{}return[]}function Gc(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function wp(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 YT(e){const[n,s]=i.useState(()=>yp(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(yp(e)),r(!1),l(!0),d(null)},[e]),i.useEffect(()=>{try{vs(Lb,JSON.stringify(n),e)}catch{}},[e,n]),i.useEffect(()=>{let E=!1;const y=h.current;return(async()=>{if(!E)try{const M=await wp(Fk(e),GT,"listTerminalSessions");if(E||y!==h.current)return;const D=new Set(M.map(C=>C.id));l(!0),s(C=>{if(E||y!==h.current)return C;const F=C.map($=>({...$,_verified:D.has($.sessionId)})).filter($=>$._verified);if(F.length===0)return[];const U=F.map(({_verified:$,...T})=>T);return U.find($=>$.isActive)?U:U.map(($,T)=>({...$,isActive:T===0}))}),r(!0)}catch(M){if(E||y!==h.current)return;const D=Gc(M);D||console.warn("Failed to validate terminal sessions with server:",M),l(!D),r(!0)}})(),()=>{E=!0}},[e]),i.useEffect(()=>{if(n.length===0&&a&&o){const E=h.current,y=setTimeout(()=>{wp(No(void 0,void 0,void 0,e),JT,"createTerminalSession").then(N=>{if(E!==h.current)return;const M={id:vp(),sessionId:N.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(D=>D.length>0?D:[...D.map(_=>({..._,isActive:!1})),M]),d(null)}).catch(N=>{if(E!==h.current)return;Gc(N)||console.error(N);const M=N instanceof Error?N.message:typeof N=="string"?N:"Failed to create terminal session";d(M)})},0);return()=>clearTimeout(y)}},[a,o,n.length,u]);const f=i.useCallback(async()=>{const E=await No(void 0,void 0,void 0,e),y={id:vp(),sessionId:E.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(N=>[...N.map(D=>({...D,isActive:!1})),y]),y},[n.length]),p=i.useCallback(async()=>f(),[f]),g=i.useCallback(E=>{s(y=>{const N=y.find(_=>_.id===E);if(!N)return y;Hu(N.sessionId,e).catch(_=>{console.warn(`Failed to kill terminal session ${N.sessionId}:`,_)});const M=y.findIndex(_=>_.id===E),D=N.isActive,C=y.filter(_=>_.id!==E);if(C.length===0)return[];if(D){const _=Math.min(M,C.length-1);return C.map((F,U)=>({...F,isActive:U===_}))}return C})},[]),x=i.useCallback(E=>{s(y=>{let N=!1;const M=y.map(D=>D.id===E?(N=!0,{...D,isActive:!0}):{...D,isActive:!1});return N?M:y})},[]),v=i.useCallback((E,y)=>{s(N=>N.map(M=>M.id===E?{...M,title:y}:M))},[]),b=i.useCallback(async()=>{s(N=>{const M=N.find(D=>D.isActive);return M&&Hu(M.sessionId,e).catch(D=>{console.warn(`Failed to kill old session ${M.sessionId}:`,D)}),N});const E=n.find(N=>N.isActive);if(!E)return;const y=await No(void 0,void 0,void 0,e);s(N=>N.map(M=>M.id===E.id?{...M,sessionId:y.sessionId}:M))},[n]),k=i.useCallback(async()=>{const E=n.find(y=>y.isActive);if(E)try{const y=await No(void 0,void 0,void 0,e);s(N=>N.map(M=>M.id===E.id?{...M,sessionId:y.sessionId}:M)),d(null)}catch(y){Gc(y)||console.error(y);const N=y instanceof Error?y.message:typeof y=="string"?y:"Failed to create terminal session";d(N)}},[n]),S=n.find(E=>E.isActive)??null,j=i.useCallback(()=>{d(null),h.current+=1,m(E=>E+1)},[]);return{tabs:n,activeTab:S,isReady:a,bootstrapError:c,createTab:p,closeTab:g,setActiveTab:x,updateTabTitle:v,restartActiveTab:b,retryBootstrap:j,replaceActiveTabSession:k}}const QT=1e4,XT=[500,1500,3e3],Ob="kb-terminal-font-size",Ir=14,ZT=8,eI=32,tI='"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 nI(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 sI(e){return`\x1B${e}`}const iI=[{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 $r(e){return Math.min(eI,Math.max(ZT,e))}function aI(){if(typeof window>"u")return Ir;try{const e=window.localStorage.getItem(Ob);if(!e)return Ir;const n=Number.parseInt(e,10);return Number.isFinite(n)?$r(n):Ir}catch{return Ir}}function rI(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 oI(e){return new Promise(n=>setTimeout(n,e))}async function lI(e,n=XT){let s;for(let a=0;a<=n.length;a+=1)try{return await e()}catch(r){if(!rI(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 oI(o)}throw s??new Error("Dynamic import failed")}function kp(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}function cI(){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=dI()-e.offsetTop-e.height;return a>=30&&a>80?a:0}let Jc=null;function dI(){return Jc===null&&(Jc=window.innerHeight),Jc}function uI({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),[v,b]=i.useState(null),[k,S]=i.useState(()=>aI()),[j,E]=i.useState(!1),[y,N]=i.useState(null),M=i.useRef(null),D=i.useRef(null),C=i.useRef(!1);_i(D,e,"fusion:terminal-modal-size");const _=i.useRef(null),F=i.useRef(null),U=i.useRef(!1),A=i.useRef(!1),$=i.useRef(null),T=i.useRef(()=>{}),J=i.useRef(null),B=i.useRef(0),se=i.useRef(k),P=i.useRef(null),O=i.useRef(a);B.current=g,se.current=k;const I=i.useCallback(Ae=>{if(Ae&&A.current!==Ae)return;const Ue=F.current,kt=_.current,De=$.current;if(!(!Ue||!kt)&&!(Ae&&A.current!==Ae))try{Ue.fit(),De&&De(kt.cols,kt.rows)}catch{}},[]);i.useEffect(()=>{e&&p(Ae=>Ae+1)},[e]),i.useEffect(()=>{if(!e||!kp())return;const Ae=window.visualViewport;if(!Ae)return;const Ue=()=>{const kt=cI();x(kt),b(Ae.height),kt>0&&D.current?.scrollIntoView&&D.current.scrollIntoView({block:"end",behavior:"smooth"}),P.current!==null&&(cancelAnimationFrame(P.current),P.current=null);const De=typeof A.current=="string"?A.current:void 0;P.current=requestAnimationFrame(()=>{P.current=null,I(De)})};return Ue(),Ae.addEventListener("resize",Ue),Ae.addEventListener("scroll",Ue),()=>{Ae.removeEventListener("resize",Ue),Ae.removeEventListener("scroll",Ue),P.current!==null&&(cancelAnimationFrame(P.current),P.current=null),x(0),b(null)}},[I,e]),i.useEffect(()=>{if(!e)return;const Ae=D.current;if(!Ae||typeof ResizeObserver>"u")return;let Ue=null;const kt=new ResizeObserver(()=>{Ue!==null&&cancelAnimationFrame(Ue),Ue=requestAnimationFrame(()=>{Ue=null;const De=typeof A.current=="string"?A.current:void 0;I(De)})});return kt.observe(Ae),()=>{kt.disconnect(),Ue!==null&&cancelAnimationFrame(Ue)}},[I,e]);const{tabs:w,activeTab:Y,isReady:re,bootstrapError:le,createTab:ve,closeTab:de,setActiveTab:Fe,updateTabTitle:X,restartActiveTab:L,retryBootstrap:Q,replaceActiveTabSession:ne}=YT(a),{connectionStatus:H,sendInput:z,resize:W,onData:we,onConnect:Z,onExit:fe,onScrollback:Oe,reconnect:Ve,onSessionInvalid:He}=KT(Y?.sessionId??null,a);$.current=W,T.current=z,i.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Ob,String(k))}catch{}},[k]);const Je=i.useCallback(()=>{const Ae=_.current;if(Ae)try{F.current?.fit(),W(Ae.cols,Ae.rows)}catch{}},[W]);i.useEffect(()=>{if(!e||!re)return;const Ae=Y?.sessionId;if(!Ae)return;const Ue=O.current!==a;if(Ue&&(O.current=a),A.current===Ae&&_.current&&!Ue)return;_.current&&(A.current!==Ae||Ue)&&(_.current.dispose(),_.current=null,F.current=null,A.current=!1,J.current&&(window.removeEventListener("resize",J.current),J.current=null),u(!1),h(null));let kt=!0,De;return(async()=>{const pe=lI(()=>Promise.all([Rn(()=>import("./vendor-xterm-DzcZoU0P.js").then(me=>me.x),__vite__mapDeps([5,1,6])),Rn(()=>import("./addon-fit-C7jRorKK.js").then(me=>me.a),__vite__mapDeps([8,1])),Rn(()=>import("./addon-web-links-CkJwd4cQ.js").then(me=>me.a),__vite__mapDeps([9,1]))])),Re=new Promise((me,ft)=>{De=setTimeout(()=>{ft(new Error("xterm initialization timed out"))},QT)});let Be,at;try{const[{Terminal:me},{FitAddon:ft},{WebLinksAddon:Et}]=await Promise.race([pe,Re]);if(!kt||!M.current||_.current)return;Be=new me({cursorBlink:!0,cursorStyle:"block",fontSize:se.current,fontFamily:tI,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}),at=new ft,Be.loadAddon(at);const jt=new Et;if(Be.loadAddon(jt),!kp())try{const{WebglAddon:Rt}=await Rn(async()=>{const{WebglAddon:Vt}=await import("./addon-webgl-BjvOw43o.js").then(Qt=>Qt.a);return{WebglAddon:Vt}},__vite__mapDeps([10,1])),It=new Rt;It.onContextLoss(()=>{It.dispose()}),Be.loadAddon(It)}catch{}Be.open(M.current),De&&clearTimeout(De);const $t=M.current?.querySelector(".xterm-helper-textarea");if($t&&$t.focus(),M.current)try{M.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{at.fit();const Rt=M.current?.querySelector(".xterm-helper-textarea");Rt&&Rt.focus()},50),_.current=Be,F.current=at,A.current=Ae,B.current>0&&(P.current!==null&&(cancelAnimationFrame(P.current),P.current=null),P.current=requestAnimationFrame(()=>{P.current=null,I(Ae)})),Be.onData(Rt=>{A.current===Ae&&T.current(Rt)});const Ft=()=>{if(A.current===Ae&&F.current&&_.current)try{F.current.fit();const{cols:Rt,rows:It}=_.current;$.current?.(Rt,It)}catch{}};window.addEventListener("resize",Ft),J.current&&window.removeEventListener("resize",J.current),J.current=Ft,u(!0),h(null)}catch(me){if(De&&clearTimeout(De),!kt)return;const ft=me instanceof Error?me.message:"xterm initialization failed";h(ft)}})(),()=>{kt=!1,De&&clearTimeout(De)}},[I,e,re,Y?.sessionId,a]),i.useEffect(()=>{e||(_.current&&(_.current.dispose(),_.current=null),F.current=null,A.current=!1,J.current&&(window.removeEventListener("resize",J.current),J.current=null),u(!1),h(null),U.current=!1,o(null),c(null),E(!1),N(null))},[e]),i.useEffect(()=>{if(!d||!_.current||!Y)return;const Ae=Y.sessionId,Ue=Re=>{A.current===Ae&&_.current?.write(Re)},kt=we(Re=>{Ue(Re)}),De=Oe(Re=>{Ue(Re)}),be=Z(Re=>{X(Y.id,au(Re.shell)||Re.shell)}),pe=fe(Re=>{A.current===Ae&&(c(Re),_.current?.write(`\r
689
- \x1B[33m[Process exited with code ${Re}]\x1B[0m\r
690
- `))});return()=>{kt(),De(),be(),pe()}},[d,Y?.sessionId,Y?.id,Y,H,we,Oe,Z,fe,X]),i.useEffect(()=>{H==="connected"&&s&&U.current!==s&&Y&&(U.current=s,setTimeout(()=>{z(s+`
691
- `)},500))},[H,s,z,Y,f]),i.useEffect(()=>{if(!d||!_.current)return;_.current.options.fontSize=k,P.current!==null&&(cancelAnimationFrame(P.current),P.current=null);const Ae=requestAnimationFrame(()=>{P.current=null,Je()});return P.current=Ae,()=>{P.current===Ae&&(cancelAnimationFrame(Ae),P.current=null)}},[k,d,Je]),i.useEffect(()=>{if(!e)return;const Ae=Ue=>{if(!(!Ue.ctrlKey&&!Ue.metaKey)){if(Ue.code==="Equal"||Ue.code==="NumpadAdd"){Ue.preventDefault(),S(kt=>$r(kt+1));return}if(Ue.code==="Minus"||Ue.code==="NumpadSubtract"){Ue.preventDefault(),S(kt=>$r(kt-1));return}if(Ue.code==="Digit0"||Ue.code==="Numpad0"){Ue.preventDefault(),S(Ir);return}}};return window.addEventListener("keydown",Ae),()=>window.removeEventListener("keydown",Ae)},[e,Je]),i.useEffect(()=>{if(!e)return;const Ae=Ue=>{Ue.key==="Escape"&&n()};return document.addEventListener("keydown",Ae),()=>document.removeEventListener("keydown",Ae)},[e,n]),i.useEffect(()=>{H==="connected"&&_.current&&setTimeout(()=>{if(!_.current||!M.current)return;const Ae=M.current.querySelector(".xterm-helper-textarea");Ae&&Ae.focus();try{M.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[H]);const $e=i.useCallback(()=>{if(!M.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;_.current?.focus();const Ue=M.current.querySelector(".xterm-helper-textarea");if(!Ue)return;Ue.autocapitalize="off",Ue.autocomplete="off",Ue.autocorrect="off",Ue.spellcheck=!1,Ue.setAttribute("inputmode","text");try{Ue.focus({preventScroll:!0})}catch{Ue.focus()}const kt=Ue.value.length;Ue.setSelectionRange(kt,kt)},[]);i.useEffect(()=>He(()=>{_.current?.clear(),c(null),U.current=!1,_.current&&(_.current.dispose(),_.current=null),F.current=null,A.current=!1,J.current&&(window.removeEventListener("resize",J.current),J.current=null),u(!1),h(null),ne().catch(Ue=>{console.error("Failed to replace invalid terminal session:",Ue)})}),[He,ne]);const he=i.useCallback(Ae=>{Ae.target===Ae.currentTarget&&(C.current=!0)},[]),ue=i.useCallback(Ae=>{C.current&&Ae.target===Ae.currentTarget&&n(),C.current=!1},[n]),Ee=i.useCallback(()=>{_.current?.clear()},[]),je=i.useCallback(async()=>{_.current?.clear(),c(null),U.current=!1;try{await L()}catch(Ae){o(_e(Ae)||"Failed to restart terminal session")}},[L]),xe=i.useCallback(()=>{_.current&&(_.current.dispose(),_.current=null),F.current=null,A.current=!1,J.current&&(window.removeEventListener("resize",J.current),J.current=null),h(null),u(!1)},[]),Pe=i.useCallback(()=>{window.location.reload()},[]),ie=i.useCallback(()=>{S(Ae=>$r(Ae+1))},[]),Me=i.useCallback(()=>{S(Ae=>$r(Ae-1))},[]),We=i.useCallback(Ae=>{N(Ue=>Ue===Ae?null:Ae)},[]),mt=i.useCallback(Ae=>{if(y==="ctrl"){z(nI(Ae)),N(null);return}if(y==="alt"){z(sI(Ae)),N(null);return}z(Ae)},[z,y]),st=i.useCallback(Ae=>{z(Ae),N(null)},[z]);if(!e)return null;const Ze=()=>{switch(H){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}},dt=!re||!Y&&!le;return t.jsx("div",{className:"modal-overlay open",onMouseDown:he,onMouseUp:ue,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:g>0?{"--overlay-padding-top":"0px"}:void 0,children:t.jsxs("div",{ref:D,className:"modal terminal-modal","data-testid":"terminal-modal",style:g>0?{"--keyboard-overlap":`${g}px`,"--vv-height":v?`${v}px`:void 0}:void 0,children:[t.jsxs("div",{className:"terminal-header",children:[t.jsxs("div",{className:"terminal-tabs","data-testid":"terminal-tabs",children:[w.map(Ae=>t.jsxs("div",{className:`terminal-tab ${Ae.isActive?"terminal-tab--active":""}`,onClick:()=>Fe(Ae.id),title:Ae.title,role:"tab","aria-selected":Ae.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:Ae.title}),w.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:Ue=>{Ue.stopPropagation(),de(Ae.id)},title:"Close tab",children:"×"})]},Ae.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:ve,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(Li,{size:16}),Ze()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[H==="disconnected"&&Y&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:Ve,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(us,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:je,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(us,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:Ee,"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(Ae=>!Ae),"data-testid":"terminal-shortcut-toggle",title:"Shortcuts","aria-pressed":j,children:[t.jsx(Yv,{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(en,{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:[dt&&!le&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),le&&!Y&&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: ",le]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:Q,"data-testid":"terminal-retry-btn",children:[t.jsx(us,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Pe,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(us,{size:14}),"Refresh page"]})]})]})}),m&&Y&&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:xe,"data-testid":"terminal-reinit-btn",children:[t.jsx(us,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Pe,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(us,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:M,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:$e,onTouchStart:$e},Y?.sessionId)]}),j&&t.jsxs("div",{className:"terminal-shortcut-panel","data-testid":"terminal-shortcut-panel",children:[t.jsxs("div",{className:"terminal-shortcut-modifier-row",children:[t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${y==="ctrl"?"is-active":""}`,"data-testid":"terminal-modifier-ctrl",onClick:()=>We("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:()=>We("alt"),"aria-pressed":y==="alt",children:"Alt"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>st("\x1B"),children:"ESC"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>st(" "),children:"Tab"})]}),iI.map(Ae=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>mt(Ae.key),title:Ae.description,children:Ae.label},Ae.label))]}),t.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[t.jsxs("span",{className:`terminal-connection-status ${H}`,children:[H==="connected"&&"Connected",H==="connecting"&&"Connecting...",H==="reconnecting"&&"Reconnecting...",H==="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:Me,"data-testid":"terminal-font-size-decrease","aria-label":"Decrease terminal font size",children:t.jsx(xy,{size:14})}),t.jsxs("span",{className:"terminal-font-size-value","data-testid":"terminal-font-size-value",children:[k,"px"]}),t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:ie,"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 Nr={name:"",command:""};function jp(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function mI(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function hI({isOpen:e,onClose:n,addToast:s,projectId:a,onRunScript:r}){Mi(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(Nr),[x,v]=i.useState(!1),[b,k]=i.useState(null),[S,j]=i.useState(null),E=Fi(n),y=i.useCallback(async()=>{try{d(!0);const T=await Gr(a);l(T)}catch(T){s(_e(T)||"Failed to load scripts","error")}finally{d(!1)}},[s,a]);i.useEffect(()=>{e&&y()},[e,y]);const N=i.useCallback(()=>{m(!0),f(null),g(Nr),j(null)},[]),M=i.useCallback((T,J)=>{f(T),m(!1),g({name:T,command:J}),j(null)},[]),D=i.useCallback(()=>{f(null),m(!1),g(Nr),j(null)},[]),C=i.useCallback(T=>{g(J=>({...J,name:T})),T&&!jp(T)?j("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):j(null)},[]),_=i.useCallback(async()=>{const T=p.name.trim(),J=p.command.trim();if(!T){s("Script name is required","error");return}if(!jp(T)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!J){s("Script command is required","error");return}v(!0);try{await Hj(T,J,a),s(h?"Script updated":"Script created","success"),f(null),m(!1),g(Nr),j(null),await y()}catch(B){const se=_e(B);se?.includes("already exists")?s("A script with this name already exists","error"):s(se||"Failed to save script","error")}finally{v(!1)}},[p,h,s,y,a]),F=i.useCallback(async T=>{try{await qj(T,a),s("Script deleted","success"),k(null),h===T&&(f(null),g(Nr)),await y()}catch(J){s(_e(J)||"Failed to delete script","error")}},[h,s,y,a]),U=i.useCallback((T,J)=>{r&&r(T,J)},[r]);if(!e)return null;const A=u||h!==null,$=Object.entries(o).map(([T,J])=>({name:T,command:J}));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(Li,{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(bt,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),"Loading scripts..."]}):A?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:T=>C(T.target.value),placeholder:"e.g., build, test, lint",disabled:x||h!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:S?"var(--color-error)":void 0}}),S&&t.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:S}),t.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",marginTop:"4px"},children:"Letters, numbers, hyphens, and underscores only"})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"script-command",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Command"}),t.jsx("textarea",{id:"script-command",className:"input",value:p.command,onChange:T=>g(J=>({...J,command:T.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:D,disabled:x,"data-testid":"script-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:_,disabled:x||!!S,"data-testid":"script-save-btn",children:x?t.jsxs(t.Fragment,{children:[t.jsx(bt,{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:N,"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(Li,{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(T=>t.jsx("div",{className:"script-card","data-testid":`script-${T.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:T.name})}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:T.command,children:mI(T.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(T.name,T.command),title:"Run script","aria-label":`Run ${T.name}`,"data-testid":`run-script-${T.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[t.jsx(ns,{size:12}),"Run"]}),t.jsx("button",{className:"btn-icon",onClick:()=>M(T.name,T.command),title:"Edit","aria-label":`Edit ${T.name}`,"data-testid":`edit-script-${T.name}`,children:t.jsx(Cn,{size:14,style:{transform:"rotate(45deg)"}})}),b===T.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>F(T.name),title:"Confirm delete","aria-label":`Confirm delete ${T.name}`,"data-testid":`confirm-delete-script-${T.name}`,style:{color:"var(--color-error)"},children:t.jsx(Sn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>k(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${T.name}`,children:t.jsx(en,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>k(T.name),title:"Delete","aria-label":`Delete ${T.name}`,"data-testid":`delete-script-${T.name}`,children:t.jsx(Sn,{size:14})})]})]})},T.name))})]})})]})})}function pI(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 v(){d(!0),m(null);try{const b=await sj(e,o==="."?void 0:o,s);x||r(b.entries)}catch(b){x||(m(_e(b)||"Failed to load files"),r([]))}finally{x||d(!1)}}return v(),()=>{x=!0}},[e,o,n,h,s]),{entries:a,currentPath:o,setPath:g,loading:c,error:u,refresh:p}}function fI(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),v=i.useCallback(S=>{o(S),x(null)},[]);i.useEffect(()=>{if(!e||!n){o(""),c(""),u(null),x(null);return}let S=!1;async function j(){h(!0),x(null);try{const E=await ij(e,n,a);S||(o(E.content),c(E.content),u(E.mtime))}catch(E){S||(x(_e(E)||"Failed to load file"),o(""),c(""),u(null))}finally{S||h(!1)}}return j(),()=>{S=!0}},[e,n,s,a]);const b=r!==l,k=i.useCallback(async()=>{if(!(!e||!n||!b)){p(!0),x(null);try{const S=await aj(e,n,r,a);c(r),u(S.mtime)}catch(S){throw x(_e(S)||"Failed to save file"),S}finally{p(!1)}}},[e,n,r,b,a]);return{content:r,setContent:v,originalContent:l,loading:m,saving:f,error:g,save:k,hasChanges:b,mtime:d}}const gI=1e4;function bI(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function xI(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function vI(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 nj(e);if(u)return;s(bI(f.project)),r(f.tasks.map(xI)),d(null)}catch(f){u||d(_e(f)||"Failed to load workspaces")}finally{u||l(!1)}}m();const h=window.setInterval(()=>{m()},gI);return()=>{u=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:a,loading:o,error:c}}function yI(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function wI(e){return e?new Date(e).toLocaleDateString():""}function Np(e,n){return dS(e,n)}const Sr={visible:!1,x:0,y:0,entry:null,entryFullPath:""},Yc={type:null,entry:null,entryFullPath:""},kI=200,jI=500,Sp=10;function NI({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,v=f?.offsetTop??0,b=8;let k=e-x,S=n-v;k+h.width>p-b&&(k=p-b-h.width),S+h.height>g-b&&(S=g-b-h.height),k<b&&(k=b),S<b&&(S=b),c({x:k+x,y:S+v})},[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:Wi,disabled:!1},{id:"move",label:"Move",icon:wy,disabled:!1},{id:"rename",label:"Rename",icon:Cs,disabled:!1},...d?[{id:"download-zip",label:"Download as ZIP",icon:Zr,disabled:!1}]:[{id:"download",label:"Download",icon:cv,disabled:!1}],{id:"divider",label:"",icon:Wi,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 SI({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 CI({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(Sr),[f,p]=i.useState(Yc),[g,x]=i.useState(!1),[v,b]=i.useState(null),[k,S]=i.useState(!1),[j,E]=i.useState(null),y=i.useRef(null),N=i.useRef(null),M=i.useRef(null),D=i.useRef(!1),C=i.useCallback(()=>{y.current!==null&&(window.clearTimeout(y.current),y.current=null),N.current!==null&&(window.clearTimeout(N.current),N.current=null)},[]),_=i.useCallback(()=>{C(),M.current=null,S(!1),E(null)},[C]);i.useEffect(()=>()=>{C()},[C]);const F=i.useCallback((O,I,w,Y)=>{h({visible:!0,x:O,y:I,entry:w,entryFullPath:Y})},[]),U=i.useCallback((O,I,w)=>{if(O.touches.length!==1)return;const Y=O.touches[0];Y&&(_(),M.current={x:Y.clientX,y:Y.clientY},N.current=window.setTimeout(()=>{S(!0),E(w)},kI),y.current=window.setTimeout(()=>{const re=M.current;re&&(D.current=!0,S(!1),E(null),C(),F(re.x,re.y,I,w))},jI))},[_,C,F]),A=i.useCallback(O=>{const I=M.current,w=O.touches[0];!I||!w||(Math.abs(w.clientX-I.x)>Sp||Math.abs(w.clientY-I.y)>Sp)&&_()},[_]),$=i.useCallback(()=>{_()},[_]);i.useEffect(()=>{if(!m.visible)return;const O=document.querySelector(".file-browser-list"),I=()=>{D.current=!1,_(),h(Sr)};return O?.addEventListener("scroll",I),()=>O?.removeEventListener("scroll",I)},[_,m.visible]),i.useEffect(()=>{if(!m.visible)return;const O=I=>{I.key==="Escape"&&(D.current=!1,h(Sr))};return document.addEventListener("keydown",O),()=>document.removeEventListener("keydown",O)},[m.visible]);const T=i.useCallback((O,I)=>{O.preventDefault(),O.stopPropagation(),_(),D.current=!1,F(O.clientX,O.clientY,I,Np(n,I.name))},[_,n,F]),J=i.useCallback(O=>{if(!m.entry)return;D.current=!1;const I=m.entry,w=m.entryFullPath;if(h(Sr),O==="download"){if(!c)return;const Y=Df(c,w,u);window.open(Ni(Y),"_blank");return}if(O==="download-zip"){if(!c)return;const Y=uj(c,w,u);window.open(Ni(Y),"_blank");return}p({type:O,entry:I,entryFullPath:w}),b(null)},[m,c,u]),B=i.useCallback(async O=>{if(!(!f.type||!f.entry||!c)){x(!0),b(null);try{switch(f.type){case"copy":await oj(c,f.entryFullPath,O,u);break;case"move":await lj(c,f.entryFullPath,O,u);break;case"rename":await dj(c,f.entryFullPath,O,u);break;case"delete":await cj(c,f.entryFullPath,u);break}p(Yc),d?.()}catch(I){b(_e(I)||"Operation failed")}finally{x(!1)}}},[f,c,d,u]),se=i.useCallback(()=>{p(Yc),b(null)},[]),P=i.useCallback((O,I)=>{if(D.current){D.current=!1;return}m.visible||(O.type==="directory"?a(I):s(I))},[m.visible,a,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(bt,{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(uS(n))},children:[t.jsx(Un,{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(O=>{const I=Np(n,O.name),w=k&&j===I;return t.jsxs("div",{className:`file-node file-node--${O.type} ${w?"file-node--long-pressing":""}`,onClick:()=>P(O,I),onContextMenu:Y=>T(Y,O),onTouchStart:Y=>U(Y,O,I),onTouchMove:A,onTouchEnd:$,onTouchCancel:$,children:[t.jsx("div",{className:"file-node-icon",children:O.type==="directory"?t.jsx(ws,{size:16}):t.jsx(Sf,{size:16})}),t.jsx("div",{className:"file-node-name",children:O.name}),O.type==="file"&&O.size!==void 0&&t.jsx("div",{className:"file-node-size",children:yI(O.size)}),O.mtime&&t.jsx("div",{className:"file-node-time",children:wI(O.mtime)})]},O.name)})}),m.visible&&m.entry&&t.jsx(NI,{x:m.x,y:m.y,entry:m.entry,onAction:J,onClose:()=>{D.current=!1,h(Sr)}}),f.type&&f.entry&&t.jsx(SI,{type:f.type,entry:f.entry,entryFullPath:f.entryFullPath,onConfirm:B,onCancel:se,loading:g,error:v})]})}function EI(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function _I({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=EI(a),h=m&&(s?!0:o),f=r&&!s&&!h,p=i.useMemo(()=>f?e.split(`
692
- `).length:0,[e,f]),g=i.useCallback(()=>{l(!1)},[]),x=i.useCallback(()=>{l(!0)},[]),v=i.useCallback(()=>{d(k=>!k)},[]),b=i.useCallback(k=>{u.current&&(u.current.scrollTop=k.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(Nf,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${h?"btn-primary":""}`,onClick:x,disabled:h,"aria-label":"Preview mode",children:[t.jsx(sr,{size:14}),"Preview"]})]}),!s&&t.jsx("button",{className:`btn btn-sm ${c?"btn-primary":""}`,onClick:v,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(cl,{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:v,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(cl,{size:14})})]}),h?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(Ci,{remarkPlugins:[Ei],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},(k,S)=>t.jsx("div",{className:"file-editor-line-number",children:S+1},`line-${S+1}`))}),t.jsx("textarea",{className:`file-editor-textarea ${c?"file-editor-textarea--wrap":""}`,value:e,onChange:k=>n(k.target.value),onScroll:b,readOnly:s,spellCheck:!1,"aria-label":a?`Editor for ${a}`:"File editor"})]})]})}function MI(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function AI({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(Ru,{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(Ru,{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:MI(c.title)})]},c.id))]})]})]})}const PI=768,RI=280,Ko=180,Go=500,Cp="fusion:file-browser-sidebar-width",Ep="kb-files-line-numbers",Fb=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),TI=new Set([...Fb,".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 Qc(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return TI.has(n)}function II(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return Fb.has(n)}function $I({initialWorkspace:e="project",onClose:n,onWorkspaceChange:s,projectId:a}){const{projectName:r,workspaces:o}=vI(a),l=i.useRef(null);_i(l,!0,"fusion:files-modal-size");const c=Fi(n),[d,u]=i.useState(e),[m,h]=i.useState(null),[f,p]=i.useState(!1),[g,x]=i.useState("list"),[v,b]=i.useState(RI),[k,S]=i.useState(!1),{entries:j,currentPath:E,setPath:y,loading:N,error:M,refresh:D}=pI(d,!0,a),{content:C,setContent:_,originalContent:F,loading:U,saving:A,error:$,save:T,hasChanges:J,mtime:B}=fI(d,m,!0,a);i.useEffect(()=>{u(e)},[e]),i.useEffect(()=>{const L=()=>{p(window.innerWidth<=PI)};return L(),window.addEventListener("resize",L),()=>window.removeEventListener("resize",L)},[]),i.useEffect(()=>{m||x("list")},[m]),i.useEffect(()=>{try{const L=localStorage.getItem(Cp);if(!L)return;const Q=Number.parseInt(L,10);if(!Number.isNaN(Q)){const ne=Math.max(Ko,Math.min(Go,Q));b(ne)}}catch{}},[]),i.useEffect(()=>{const L=ss(Ep,a);S(L==="true")},[a]),i.useEffect(()=>{const L=Q=>{Q.key==="Escape"&&n(),(Q.metaKey||Q.ctrlKey)&&Q.key==="s"&&(Q.preventDefault(),J&&!A&&T())};return document.addEventListener("keydown",L),()=>document.removeEventListener("keydown",L)},[n,J,A,T]);const se=i.useCallback(L=>{h(L),f&&x("editor")},[f]),P=i.useCallback(()=>{x("list")},[]),O=i.useCallback(()=>{_(F)},[F,_]),I=i.useCallback(L=>{u(L),h(null),x("list"),s?.(L)},[s]),w=i.useCallback(L=>{try{localStorage.setItem(Cp,String(L))}catch{}},[]),Y=i.useCallback(L=>{if(f)return;L.preventDefault(),L.stopPropagation();const Q=L.currentTarget;typeof Q.setPointerCapture=="function"&&Q.setPointerCapture(L.pointerId);const ne=L.clientX,H=v;let z=H;document.body.style.userSelect="none";const W=Z=>{const fe=Z.clientX-ne,Oe=Math.max(Ko,Math.min(Go,H+fe));z=Oe,b(Oe)},we=Z=>{typeof Q.releasePointerCapture=="function"&&Q.releasePointerCapture(Z.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",W),document.removeEventListener("pointerup",we),w(z)};document.addEventListener("pointermove",W),document.addEventListener("pointerup",we)},[f,w,v]),re=i.useCallback(L=>{if(f)return;const Q=20;if(L.key!=="ArrowLeft"&&L.key!=="ArrowRight")return;L.preventDefault();const ne=L.key==="ArrowLeft"?-Q:Q,H=Math.max(Ko,Math.min(Go,v+ne));b(H),w(H)},[f,w,v]),le=i.useCallback(()=>{S(L=>{const Q=!L;return vs(Ep,String(Q),a),Q})},[a]),de=`Files — ${i.useMemo(()=>d==="project"?"Project":o.find(L=>L.id===d)?.id??d,[d,o])}`,Fe=i.useMemo(()=>!m||!II(m)?null:Df(d,m,a),[m,d,a]),X=L=>{const Q=new Blob([L]).size;return Q<1024?`${Q} B`:`${(Q/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(ws,{size:18}),t.jsx("span",{children:de}),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 ${k?"btn-primary":""}`,onClick:le,"aria-label":"Toggle line numbers","aria-pressed":k,title:"Toggle line numbers",children:[t.jsx(sy,{size:14}),t.jsx("span",{children:"Line #"})]}),t.jsx(AI,{currentWorkspace:d,projectName:r,workspaces:o,onSelect:I}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(en,{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:`${v}px`},children:t.jsx(CI,{entries:j,currentPath:E,onSelectFile:se,onNavigate:y,loading:N,error:M,onRetry:D,workspace:d,onRefresh:D,projectId:a})}),!f&&t.jsx("div",{className:"file-browser-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":Ko,"aria-valuemax":Go,"aria-valuenow":v,"aria-label":"Resize sidebar",tabIndex:0,onPointerDown:Y,onKeyDown:re}),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:P,"aria-label":"Back to file list",children:[t.jsx(fa,{size:16}),t.jsx("span",{children:"Back"})]}),m,Qc(m)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(Ev,{size:12}),"Binary file — read only"]}),B&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(B).toLocaleString()]}),U&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!Fe&&J&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:O,disabled:A,children:[t.jsx(Dy,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void T(),disabled:A,children:[t.jsx(Af,{size:14}),A?"Saving...":"Save"]})]})})]}),$&&!Fe&&t.jsx("div",{className:"file-browser-error-banner",children:$}),Fe?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:Fe,alt:m??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(_I,{content:C,onChange:_,filePath:m,readOnly:Qc(m),showLineNumbers:k&&!Qc(m)})}),!Fe&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:X(C)}),J&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(ws,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}function DI(e){const{items:n,...s}=e;return s}function _p(e){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`${e}-${crypto.randomUUID()}`:`${e}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function LI(e={}){const{projectId:n,addToast:s}=e,[a,r]=i.useState([]),[o,l]=i.useState([]),[c,d]=i.useState(!0),[u,m]=i.useState(null),[h,f]=i.useState(null),[p,g]=i.useState([]),x=i.useRef(h);x.current=h,i.useEffect(()=>{let M=!1;async function D(){d(!0),m(null);try{const C=await d1(n);if(M)return;g(C),r(C.map(DI));const _=x.current&&C.some(F=>F.id===x.current)?x.current:C[0]?.id??null;f(_),l(_?C.find(F=>F.id===_)?.items??[]:[])}catch(C){if(M)return;g([]),r([]),l([]),f(null),m(C instanceof Error?C.message:"Failed to load todo lists")}finally{M||d(!1)}}return D(),()=>{M=!0}},[n]),i.useEffect(()=>{if(!h){l([]);return}const M=p.find(D=>D.id===h);l(M?.items??[])},[p,h]);const v=i.useCallback(async M=>{const D=a,C=p,_=new Date().toISOString(),F={id:_p("temp-list"),projectId:n??"",title:M,createdAt:_,updatedAt:_};m(null),r(U=>[...U,F]),g(U=>[...U,{...F,items:[]}]);try{const U=await u1(M,n);r(A=>A.map($=>$.id===F.id?U:$)),g(A=>A.map($=>$.id===F.id?{...U,items:[]}:$)),x.current||f(U.id)}catch(U){r(D),g(C),m(U instanceof Error?U.message:"Failed to create list"),s?.("Failed to create todo list","error")}},[s,p,a,n]),b=i.useCallback(async(M,D)=>{const C=a,_=p;m(null),r(F=>F.map(U=>U.id===M?{...U,title:D}:U)),g(F=>F.map(U=>U.id===M?{...U,title:D}:U));try{const F=await m1(M,D,n);r(U=>U.map(A=>A.id===M?F:A)),g(U=>U.map(A=>A.id===M?{...F,items:A.items}:A))}catch(F){r(C),g(_),m(F instanceof Error?F.message:"Failed to rename list"),s?.("Failed to rename todo list","error")}},[s,p,a,n]),k=i.useCallback(async M=>{const D=a,C=p,_=x.current,F=_===M?a.find(U=>U.id!==M)?.id??null:_;m(null),r(U=>U.filter(A=>A.id!==M)),g(U=>U.filter(A=>A.id!==M)),_===M&&f(F);try{await h1(M,n)}catch(U){r(D),g(C),f(_),m(U instanceof Error?U.message:"Failed to delete list"),s?.("Failed to delete todo list","error")}},[s,p,a,n]),S=i.useCallback(async M=>{const D=x.current;if(!D)return;const C=o,_=p,F=new Date().toISOString(),U=o.reduce(($,T)=>Math.max($,T.sortOrder),-1),A={id:_p("temp-item"),listId:D,text:M,completed:!1,completedAt:null,createdAt:F,updatedAt:F,sortOrder:U+1};m(null),l($=>[...$,A]),g($=>$.map(T=>T.id===D?{...T,items:[...T.items,A]}:T));try{const $=await p1(D,M,n);l(T=>T.map(J=>J.id===A.id?$:J)),g(T=>T.map(J=>J.id===D?{...J,items:J.items.map(B=>B.id===A.id?$:B)}:J))}catch($){l(C),g(_),m($ instanceof Error?$.message:"Failed to create item"),s?.("Failed to create todo item","error")}},[s,o,p,n]),j=i.useCallback(async(M,D)=>{const C=o.find($=>$.id===M);if(!C)return;const _=o,F=p,U=D.completed??C.completed,A={...C,...D,completed:U,completedAt:U?C.completedAt??new Date().toISOString():null,updatedAt:new Date().toISOString()};m(null),l($=>$.map(T=>T.id===M?A:T)),g($=>$.map(T=>T.id===A.listId?{...T,items:T.items.map(J=>J.id===M?A:J)}:T));try{const $=await f1(M,D,n);l(T=>T.map(J=>J.id===M?$:J)),g(T=>T.map(J=>J.id===$.listId?{...J,items:J.items.map(B=>B.id===M?$:B)}:J))}catch($){l(_),g(F),m($ instanceof Error?$.message:"Failed to update item"),s?.("Failed to update todo item","error")}},[s,o,p,n]),E=i.useCallback(async M=>{const D=o.find(C=>C.id===M);D&&await j(M,{completed:!D.completed})},[o,j]),y=i.useCallback(async M=>{const D=o,C=p;m(null),l(_=>_.filter(F=>F.id!==M)),g(_=>_.map(F=>({...F,items:F.items.filter(U=>U.id!==M)})));try{await g1(M,n)}catch(_){l(D),g(C),m(_ instanceof Error?_.message:"Failed to delete item"),s?.("Failed to delete todo item","error")}},[s,o,p,n]),N=i.useCallback(async M=>{const D=x.current;if(!D)return;const C=o,_=p,F=new Map(o.map(A=>[A.id,A])),U=M.map((A,$)=>{const T=F.get(A);return T?{...T,sortOrder:$}:null}).filter(A=>A!==null);m(null),l(U),g(A=>A.map($=>$.id===D?{...$,items:U}:$));try{await b1(D,M,n)}catch(A){l(C),g(_),m(A instanceof Error?A.message:"Failed to reorder items"),s?.("Failed to reorder todo items","error")}},[s,o,p,n]);return{lists:a,items:o,loading:c,error:u,selectedListId:h,setSelectedListId:f,createList:v,renameList:b,deleteList:k,createItem:S,updateItem:j,toggleItem:E,deleteItem:y,reorderItems:N}}function OI(e){return[...e].sort((n,s)=>n.sortOrder-s.sortOrder)}function zb({projectId:e,addToast:n,onPlanningMode:s,onTaskCreated:a}){const{lists:r,items:o,loading:l,error:c,selectedListId:d,setSelectedListId:u,createList:m,renameList:h,deleteList:f,createItem:p,updateItem:g,toggleItem:x,deleteItem:v,reorderItems:b}=LI({projectId:e,addToast:(he,ue)=>{if(ue==="success"||ue==="error"||ue==="info"||ue===void 0){n(he,ue);return}n(he,"info")}}),[k,S]=i.useState(null),[j,E]=i.useState(""),[y,N]=i.useState(null),[M,D]=i.useState(""),[C,_]=i.useState(""),[F,U]=i.useState(!1),[A,$]=i.useState(""),[T,J]=i.useState([]),[B,se]=i.useState(!1),[P,O]=i.useState(!1),[I,w]=i.useState(null),Y=i.useRef(null),{confirm:re}=Qs(),le=i.useMemo(()=>r.find(he=>he.id===d)??null,[r,d]),ve=i.useMemo(()=>OI(o.filter(he=>he.listId===d)),[o,d]);function de(){S(null),E(""),_(""),U(!1)}function Fe(){N(null),D(""),$("")}function X(he){de(),Fe(),u(he)}const L=i.useCallback(async()=>{se(!0);try{const he=await ba(void 0,e);J(he),O(!0)}catch(he){n(`Failed to load agents: ${_e(he)}`,"error"),O(!1),w(null)}finally{se(!1)}},[e,n]);i.useEffect(()=>{S(null),E(""),_(""),U(!1),N(null),D(""),$(""),O(!1),w(null)},[d]),i.useEffect(()=>{if(!P)return;const he=ue=>{Y.current&&!Y.current.contains(ue.target)&&(O(!1),w(null))};return document.addEventListener("mousedown",he),()=>{document.removeEventListener("mousedown",he)}},[P]);function Q(he){Fe(),S(he.id),E(he.title),U(!1)}async function ne(){if(!k)return;const he=j.trim();if(!he){S(null),E("");return}await h(k,he),S(null),E("")}function H(){S(null),E("")}function z(he){de(),N(he.id),D(he.text)}async function W(){if(!y)return;const he=M.trim();if(!he){N(null),D("");return}await g(y,{text:he}),N(null),D("")}function we(){N(null),D("")}async function Z(){const he=C.trim();he&&(await m(he),_(""),U(!1))}async function fe(){if(!d)return;const he=A.trim();he&&(await p(he),$(""))}async function Oe(he){await re({title:"Delete List",message:"Delete this list and all its items?",danger:!0})&&await f(he)}async function Ve(he){await v(he)}async function He(he,ue){const Ee=ve.map(Pe=>Pe.id),je=Ee.findIndex(Pe=>Pe===he);if(je<0)return;const xe=ue==="up"?je-1:je+1;xe<0||xe>=Ee.length||([Ee[je],Ee[xe]]=[Ee[xe],Ee[je]],await b(Ee))}const Je=i.useCallback(async he=>{try{const ue={description:he.text,column:"triage",source:{sourceType:"dashboard_ui"}},Ee=await ml(ue,e);a?.(Ee),n(`Created ${Ee.id} from todo`,"success")}catch(ue){n(`Failed to create task: ${_e(ue)}`,"error")}},[e,n,a]),$e=i.useCallback(async(he,ue)=>{try{const Ee={description:he.text,column:"triage",assignedAgentId:ue,source:{sourceType:"dashboard_ui"}},je=await ml(Ee,e);a?.(je);const Pe=T.find(ie=>ie.id===ue)?.name??ue;n(`Created ${je.id} and assigned to ${Pe}`,"success"),O(!1),w(null)}catch(Ee){n(`Failed to create and assign task: ${_e(Ee)}`,"error")}},[e,n,T,a]);return l?t.jsx("div",{className:"todo-view",children:t.jsxs("div",{className:"todo-loading",children:[t.jsx(bt,{className:"todo-loading-icon","aria-hidden":"true"}),t.jsx("p",{children:"Loading todos..."})]})}):t.jsx("div",{className:"todo-view",children:t.jsxs("div",{className:"todo-view-layout",children:[t.jsxs("aside",{className:"todo-view-sidebar","aria-label":"Todo lists sidebar",children:[t.jsxs("div",{className:"todo-sidebar-header",children:[t.jsx("h3",{className:"todo-sidebar-title",children:"Lists"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-add-list-btn",onClick:()=>{Fe(),U(!0),S(null)},"aria-label":"Add list","data-testid":"add-list-button",children:t.jsx(Cn,{})})]}),F&&t.jsxs("div",{className:"todo-list-item",children:[t.jsx("input",{className:"input todo-inline-edit-input",placeholder:"New list title",value:C,onChange:he=>_(he.target.value),onKeyDown:he=>{he.key==="Enter"&&Z(),he.key==="Escape"&&(_(""),U(!1))},autoFocus:!0,"data-testid":"new-list-input"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{Z()},"aria-label":"Save list",children:t.jsx(ts,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{_(""),U(!1)},"aria-label":"Cancel list",children:t.jsx(en,{})})]}),r.length===0&&!F?t.jsxs("div",{className:"todo-empty-state",children:[t.jsx(pd,{"aria-hidden":"true"}),t.jsx("p",{children:"No todo lists yet. Create one to get started."}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{Fe(),U(!0)},children:"Create List"})]}):t.jsx("div",{className:"todo-list-items",role:"list","aria-label":"Todo lists",children:r.map(he=>{const ue=he.id===d,Ee=he.id===k;return t.jsx("div",{className:`todo-list-item${ue?" todo-list-item--active":""}`,role:"listitem",children:Ee?t.jsxs(t.Fragment,{children:[t.jsx("input",{className:"input todo-inline-edit-input",value:j,onChange:je=>E(je.target.value),onKeyDown:je=>{je.key==="Enter"&&ne(),je.key==="Escape"&&H()},autoFocus:!0,"data-testid":`rename-list-input-${he.id}`}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{ne()},"aria-label":"Save list rename",children:t.jsx(ts,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:H,"aria-label":"Cancel list rename",children:t.jsx(en,{})})]}):t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"todo-list-select-btn",onClick:()=>X(he.id),"aria-label":`Select list ${he.title}`,"aria-current":ue?"true":void 0,"data-testid":`todo-list-${he.id}`,children:t.jsx("span",{className:"todo-list-item-name",children:he.title})}),t.jsxs("div",{className:"todo-list-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{Q(he)},"aria-label":`Rename ${he.title}`,"data-testid":`rename-list-button-${he.id}`,children:t.jsx(Cs,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon btn-danger todo-icon-btn",onClick:()=>{Oe(he.id)},"aria-label":`Delete ${he.title}`,"data-testid":`delete-list-button-${he.id}`,children:t.jsx(Sn,{})})]})]})},he.id)})})]}),t.jsxs("section",{className:"todo-view-main","aria-label":"Todo items",children:[c&&t.jsxs("div",{className:"todo-error-banner",role:"alert",children:[t.jsx("span",{className:"todo-error-message",children:c}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>window.location.reload(),children:"Retry"})]}),le?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"todo-items-header",children:t.jsx("h3",{children:le.title})}),t.jsxs("div",{className:"todo-add-item-row",children:[t.jsx("input",{className:"input",placeholder:"Add a todo item",value:A,onChange:he=>$(he.target.value),onKeyDown:he=>{he.key==="Enter"&&fe(),he.key==="Escape"&&$("")},"data-testid":"new-item-input"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>{fe()},children:"Add"})]}),ve.length===0?t.jsx("div",{className:"todo-empty-state",children:t.jsx("p",{children:"No items in this list. Add one above."})}):t.jsx("div",{className:"todo-items-list",children:ve.map((he,ue)=>{const Ee=he.id===y;return t.jsxs("div",{className:"todo-item","data-testid":`todo-item-${he.id}`,children:[t.jsxs("div",{className:"todo-item-main-row",children:[t.jsx("input",{type:"checkbox",checked:he.completed,onChange:()=>{x(he.id)},className:"todo-item-checkbox","aria-label":`Toggle ${he.text}`,"data-testid":`toggle-item-${he.id}`}),Ee?t.jsx("input",{className:"input todo-inline-edit-input",value:M,onChange:je=>D(je.target.value),onKeyDown:je=>{je.key==="Enter"&&W(),je.key==="Escape"&&we()},autoFocus:!0,"data-testid":`edit-item-input-${he.id}`}):t.jsx("button",{type:"button",className:`todo-item-text${he.completed?" todo-item-text--completed":""}`,onClick:()=>z(he),children:he.text})]}),t.jsx("div",{className:"todo-item-actions","data-testid":`todo-item-actions-${he.id}`,children:Ee?t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{W()},"aria-label":"Save item edit",children:t.jsx(ts,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:we,"aria-label":"Cancel item edit",children:t.jsx(en,{})})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"todo-item-reorder-btns",children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-item-reorder-btn",onClick:()=>{He(he.id,"up")},disabled:ue===0,"aria-label":`Move ${he.text} up`,"data-testid":`move-up-${he.id}`,children:t.jsx(pi,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-item-reorder-btn",onClick:()=>{He(he.id,"down")},disabled:ue===ve.length-1,"aria-label":`Move ${he.text} down`,"data-testid":`move-down-${he.id}`,children:t.jsx(un,{})})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{s?.(he.text)},"aria-label":`Start planning from ${he.text}`,"data-testid":`planning-from-${he.id}`,children:t.jsx(fi,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{Je(he)},"aria-label":`Create task from ${he.text}`,"data-testid":`create-task-from-${he.id}`,children:t.jsx(Yx,{})}),t.jsxs("div",{className:"todo-agent-picker-trigger",ref:I===he.id?Y:void 0,children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{w(he.id),L()},"aria-label":`Assign ${he.text} to agent`,"data-testid":`assign-agent-for-${he.id}`,children:t.jsx(zn,{})}),P&&I===he.id&&t.jsx("div",{className:"todo-agent-picker-dropdown",onMouseDown:je=>{je.preventDefault()},children:B?t.jsx("div",{className:"todo-agent-picker-loading",children:"Loading agents..."}):T.length>0?T.map(je=>t.jsxs("button",{type:"button",className:"todo-agent-picker-item",onClick:()=>{$e(he,je.id)},children:[t.jsx(zn,{}),t.jsx("span",{children:je.name}),t.jsx("span",{className:"todo-agent-picker-role",children:je.role})]},je.id)):t.jsx("div",{className:"todo-agent-picker-empty",children:"No agents available"})})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>z(he),"aria-label":`Edit ${he.text}`,"data-testid":`edit-item-${he.id}`,children:t.jsx(Cs,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon btn-danger todo-icon-btn",onClick:()=>{Ve(he.id)},"aria-label":`Delete ${he.text}`,"data-testid":`delete-item-${he.id}`,children:t.jsx(Sn,{})})]})})]},he.id)})})]}):t.jsxs("div",{className:"todo-empty-state",children:[t.jsx(pd,{"aria-hidden":"true"}),t.jsx("p",{children:"Select a list from the sidebar"})]})]})]})})}const Ub=Object.freeze(Object.defineProperty({__proto__:null,TodoView:zb},Symbol.toStringTag,{value:"Module"}));function FI({onClose:e,projectId:n,addToast:s,onPlanningMode:a}){const r=Fi(e),l=oi()==="mobile",{keyboardOverlap:c,viewportHeight:d,viewportOffsetTop:u,keyboardOpen:m}=ya({enabled:l});Mi(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(pd,{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(en,{size:20})})]}),t.jsx("div",{className:"todo-modal-body",children:t.jsx(zb,{projectId:n,addToast:s,onPlanningMode:a,onClose:e})})]})})}function zI(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 lk();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:_e(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 UI(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 BI(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const Bb="kb-usage-hidden-windows",Hb="kb-usage-modal-size",qb="kb-usage-provider-order";function Mp(e){const n=ss(Hb,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 Ap(e){const n=ss(Bb,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 HI(e,n){vs(Bb,JSON.stringify(e),n)}function Pp(e){const n=ss(qb,e);if(!n)return[];try{const s=JSON.parse(n);return Array.isArray(s)?s.filter(a=>typeof a=="string"):[]}catch{return[]}}function Rp(e,n){vs(qb,JSON.stringify(e),n)}function Vb(e,n,s){return s[e]?.includes(n)??!1}function qI({window:e,viewMode:n,isHidden:s,onToggleHidden:a}){const r=BI(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 v=new Date(e.resetAt).getTime()-Date.now();if(v>0){const b=Math.floor(v/36e5),k=Math.floor(b/24),S=b%24;k>0&&S>0?u=`resets in ${k}d ${S}h`:k>0?u=`resets in ${k}d`:b>0?u=`resets in ${b}h`:u=`resets in ${Math.floor(v/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(sr,{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:UI(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(Dl,{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(iw,{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 VI(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 WI({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:v,onMoveDown:b}){const k=s[e.name]?.length??0,S=()=>{switch(e.status){case"ok":return null;case"error":return t.jsx("span",{className:"usage-status-badge usage-status-badge--error",children:"Error"});case"no-auth":default:return t.jsx("span",{className:"usage-status-badge usage-status-badge--not-configured",children:"Not configured"})}};return t.jsxs("div",{className:`usage-provider${o?" usage-provider--dragging":""}${l&&c==="before"?" usage-provider--drag-over-before":""}${l&&c==="after"?" usage-provider--drag-over-after":""}`,"data-provider":e.name,"data-status":e.status,draggable:!p,onDragStart:p?void 0:d,onDragOver:p?void 0:u,onDragLeave:p?void 0:m,onDrop:p?void 0:h,onDragEnd:p?void 0:f,children:[t.jsxs("div",{className:"usage-provider-header",children:[t.jsxs("div",{className:"usage-provider-info",children:[t.jsx(Kn,{provider:VI(e.name),size:"md"}),t.jsx("span",{className:"usage-provider-name",children:e.name}),k>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 (",k,")"]})]}),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:v,disabled:!g,"aria-label":`Move ${e.name} up`,children:t.jsx(pi,{size:14})}),t.jsx("button",{className:"btn-icon usage-provider-reorder-btn",type:"button",onClick:b,disabled:!x,"aria-label":`Move ${e.name} down`,children:t.jsx(un,{size:14})})]}),S(),t.jsx("div",{className:"usage-provider-drag-handle","aria-hidden":"true",children:t.jsx(Rl,{size:16})})]})]}),e.error&&t.jsx("div",{className:"usage-provider-error",children:e.error}),e.plan&&t.jsx("div",{className:"usage-provider-meta",children:t.jsx("span",{className:"usage-provider-plan",children:e.plan})}),e.windows.length>0?t.jsx("div",{className:"usage-provider-windows",children:e.windows.map((j,E)=>{const y=Vb(e.name,j.label,s);return t.jsx(qI,{window:j,viewMode:n,isHidden:y,onToggleHidden:()=>a(e.name,j.label)},`${e.name}-${j.label}-${E}`)})}):e.status==="ok"?t.jsx("div",{className:"usage-provider-empty",children:"No usage data available"}):null]})}function KI(){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 GI({isOpen:e,onClose:n,projectId:s,anchorRect:a}){const{providers:r,loading:o,error:l,lastUpdated:c,refresh:d}=zI({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,v]=i.useState("used"),[b,k]=i.useState(()=>Ap(s)),[S,j]=i.useState(()=>Pp(s)),[E,y]=i.useState(null),[N,M]=i.useState(null),[D,C]=i.useState(null),_=i.useRef(null),F=i.useRef(null),U=i.useRef(e),A=i.useRef(!1),[$,T]=i.useState(()=>Mp(s));i.useEffect(()=>{T(Mp(s))},[s]),i.useEffect(()=>{if(!e||!h)return;const Z=F.current;if(!Z||typeof ResizeObserver>"u")return;let fe=null;const Oe=new ResizeObserver(Ve=>{const He=Ve[0];if(!He)return;const{width:Je,height:$e}=He.contentRect;Je<=0||$e<=0||(fe&&clearTimeout(fe),fe=setTimeout(()=>{vs(Hb,JSON.stringify({width:Math.round(Je),height:Math.round($e)}),s)},250))});return Oe.observe(Z),()=>{fe&&clearTimeout(fe),Oe.disconnect()}},[e,h,s]),i.useEffect(()=>{e||(A.current=!1)},[e]),i.useEffect(()=>{r.length>0&&(A.current=!0)},[r.length]),i.useEffect(()=>{if(typeof window>"u")return;const Z=window.matchMedia?.("(pointer: coarse)"),fe=()=>{f(window.innerWidth>=769),g(Z?.matches??!1)};return fe(),window.addEventListener("resize",fe),Z?.addEventListener?.("change",fe),()=>{window.removeEventListener("resize",fe),Z?.removeEventListener?.("change",fe)}},[]),i.useEffect(()=>{!U.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&d(),U.current=e},[e,c,d]),i.useEffect(()=>{const Z=ss("kb-usage-view-mode",s);if(Z==="used"||Z==="remaining"){v(Z);return}v("used")},[s]);const J=i.useCallback(Z=>{v(Z),vs("kb-usage-view-mode",Z,s)},[s]);i.useEffect(()=>{k(Ap(s)),j(Pp(s))},[s]),i.useEffect(()=>{HI(b,s)},[b,s]);const B=i.useCallback((Z,fe)=>{k(Oe=>{if(Vb(Z,fe,Oe)){const Ve=(Oe[Z]??[]).filter(He=>He!==fe);if(Ve.length===0){const{[Z]:He,...Je}=Oe;return Je}return{...Oe,[Z]:Ve}}return{...Oe,[Z]:[...Oe[Z]??[],fe]}})},[]),se=i.useCallback(Z=>{k(fe=>{if(!fe[Z])return fe;const{[Z]:Oe,...Ve}=fe;return Ve})},[]),P=i.useCallback(Z=>{if(S.length===0)return Z;const fe=new Map(Z.map(Ve=>[Ve.name,Ve])),Oe=[];for(const Ve of S){const He=fe.get(Ve);He&&(Oe.push(He),fe.delete(Ve))}return[...Oe,...fe.values()]},[S]),O=i.useCallback((Z,fe)=>{Z.dataTransfer.effectAllowed="move",Z.dataTransfer.setData("text/plain",fe),y(fe)},[]),I=i.useCallback((Z,fe)=>{if(!E||E===fe)return;Z.preventDefault(),Z.dataTransfer.dropEffect="move";const{top:Oe,height:Ve}=Z.currentTarget.getBoundingClientRect(),He=Oe+Ve/2,Je=Z.clientY<He?"before":"after";M(fe),C(Je)},[E]),w=i.useCallback((Z,fe)=>{Z.preventDefault();const Oe=E??Z.dataTransfer.getData("text/plain");if(!Oe||Oe===fe){M(null),C(null);return}const He=P(r).map(he=>he.name).filter(he=>he!==Oe),Je=He.indexOf(fe);if(Je<0){M(null),C(null);return}const $e=D==="after"?Je+1:Je;He.splice($e,0,Oe),Rp(He,s),j(He),M(null),C(null)},[E,D,s,r,P]),Y=i.useCallback(()=>{y(null),M(null),C(null)},[]),re=i.useCallback((Z,fe)=>{const Oe=P(r).map(he=>he.name),Ve=Oe.indexOf(Z),He=Ve+fe;if(Ve<0||He<0||He>=Oe.length)return;const Je=[...Oe],[$e]=Je.splice(Ve,1);Je.splice(He,0,$e),Rp(Je,s),j(Je)},[s,r,P]),le=i.useCallback(async()=>{m(!0),await d(),m(!1)},[d]);i.useEffect(()=>{if(!e)return;const Z=fe=>{fe.key==="Escape"&&n()};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[e,n]);const ve=i.useCallback(Z=>{Z.target===Z.currentTarget&&n()},[n]);if(!e)return null;const de=!!(a&&h),Fe=8,X=12,Q=$?.width??420,ne=de?Math.min((a?.bottom??0)+Fe,window.innerHeight-X):void 0,H=de?Math.max(8,(a?.right??0)-Q):void 0,z=h&&$?{width:$.width,height:$.height}:{},W=P(r),we=t.jsxs("div",{ref:F,className:`usage-modal${de?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:de?{position:"fixed",top:ne,left:H,...z}:z,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Gs,{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:()=>J("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:()=>J("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(en,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:_,children:(o||!A.current&&!l)&&r.length===0?t.jsx(KI,{}):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:le,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:W.map((Z,fe)=>t.jsx(WI,{provider:Z,viewMode:x,hiddenWindows:b,onToggleWindow:B,onShowAllHidden:se,isDragging:E===Z.name,isDragOver:N===Z.name,dragOverPosition:N===Z.name?D:null,onDragStart:Oe=>O(Oe,Z.name),onDragOver:Oe=>I(Oe,Z.name),onDragLeave:()=>{N===Z.name&&(M(null),C(null))},onDrop:Oe=>w(Oe,Z.name),onDragEnd:Y,isTouchReorderMode:p,canMoveUp:fe>0,canMoveDown:fe<W.length-1,onMoveUp:()=>re(Z.name,-1),onMoveDown:()=>re(Z.name,1)},Z.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:le,disabled:o||u,"data-testid":"usage-refresh-btn",children:[t.jsx(us,{size:14,className:u?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]});return de?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"usage-popover-backdrop",onClick:n,"data-testid":"usage-modal-overlay"}),we]}):t.jsx("div",{className:"modal-overlay open",onClick:ve,"data-testid":"usage-modal-overlay",children:we})}function Wb(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 Nl(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 JI={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},Kb={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},YI={cron:yf,webhook:Pf,api:wf,manual:ds},QI={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},XI={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function ZI({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(no,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:Wb(n)})]})}function e4({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"} ${Nl(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(Wn,{size:12}):t.jsx(no,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:Nl(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:Kb[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:Wb(r)}),s?t.jsx(pi,{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 t4({routine:e,onEdit:n,onDelete:s,onRun:a,onToggle:r,running:o,lastRunOutput:l}){const[c,d]=i.useState(!1),{confirm:u}=Qs(),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=JI[e.trigger.type],f=YI[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}),Kb[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(Al,{size:10}):t.jsx(ws,{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(bt,{className:"spinner"}):t.jsx(ns,{})}),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(mi,{}):t.jsx(ns,{})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(Cs,{})}),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(ca,{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(Oi,{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:QI[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:XI[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:Nl(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:Nl(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(ZI,{result:e.lastRunResult}),t.jsxs("div",{className:"routine-meta-item",children:[t.jsx("span",{className:"routine-meta-label",children:"Runs:"}),t.jsx("span",{children:e.runCount})]})]}),l&&t.jsxs("div",{className:`routine-run-output ${l.success?"success":"failure"}`,children:[l.output&&t.jsx("pre",{className:"routine-run-output-text",children:l.output}),l.error&&t.jsx("div",{className:"routine-run-output-error",children:l.error})]}),e.runHistory.length>0&&t.jsxs("div",{className:"routine-card-history",children:[t.jsxs("button",{className:"schedule-history-toggle",onClick:()=>d(g=>!g),"aria-expanded":c,children:[c?t.jsx(pi,{size:12}):t.jsx(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(e4,{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 n4({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(Li,{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(ay,{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(ys,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function Xc(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function s4(e){return e==="command"?{id:Xc(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:Xc(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:Xc(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function i4({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,v]=i.useState(e.taskTitle??""),[b,k]=i.useState(e.taskDescription??""),[S,j]=i.useState(e.taskColumn??"triage"),[E,y]=i.useState(e.timeoutMs),[N,M]=i.useState(e.continueOnFailure??!1),[D,C]=i.useState({}),[_,F]=i.useState([]),[U,A]=i.useState(!1),[$,T]=i.useState(null);i.useEffect(()=>{let O=!1;return A(!0),T(null),Os().then(I=>{O||F(I.models)}).catch(I=>{O||T(I instanceof Error?I.message:"Failed to load models")}).finally(()=>{O||A(!1)}),()=>{O=!0}},[]);const J=i.useCallback(()=>{const O={};return a.trim()||(O.name="Step name is required"),o==="command"&&!c.trim()&&(O.command="Command is required"),o==="ai-prompt"&&!u.trim()&&(O.prompt="Prompt is required"),o==="create-task"&&!b.trim()&&(O.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(h||p)&&(!h||!p)&&(O.modelProvider="Both model provider and model ID must be set together"),E!==void 0&&E<1e3&&(O.timeoutMs="Timeout must be at least 1 second (1000ms)"),C(O),Object.keys(O).length===0},[a,o,c,u,b,h,p,E]),B=h&&p?`${h}/${p}`:"",se=i.useCallback(O=>{if(!O)f(""),g("");else{const I=O.indexOf("/");I!==-1&&(f(O.slice(0,I)),g(O.slice(I+1)))}},[]),P=i.useCallback(()=>{if(!J())return;const O={...e,name:a.trim(),type:o,command:o==="command"?c.trim():void 0,prompt:o==="ai-prompt"?u.trim():void 0,taskTitle:o==="create-task"&&x.trim()?x.trim():void 0,taskDescription:o==="create-task"&&b.trim()?b.trim():void 0,taskColumn:o==="create-task"?S:void 0,modelProvider:(o==="ai-prompt"||o==="create-task")&&h.trim()?h.trim():void 0,modelId:(o==="ai-prompt"||o==="create-task")&&p.trim()?p.trim():void 0,timeoutMs:E||void 0,continueOnFailure:N};o!=="ai-prompt"&&delete O.prompt,o!=="create-task"&&(delete O.taskTitle,delete O.taskDescription,delete O.taskColumn),n(O)},[J,n,e,a,o,c,u,x,b,S,h,p,E,N]);return t.jsxs("div",{className:"step-editor",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-name-${e.id}`,children:"Step Name"}),t.jsx("input",{id:`step-name-${e.id}`,type:"text",placeholder:"e.g. Run tests",value:a,onChange:O=>r(O.target.value),"aria-invalid":!!D.name}),D.name&&t.jsx("small",{className:"field-error",children:D.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:O=>l(O.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:O=>d(O.target.value),rows:2,"aria-invalid":!!D.command}),D.command&&t.jsx("small",{className:"field-error",children:D.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:O=>m(O.target.value),rows:3,"aria-invalid":!!D.prompt}),D.prompt&&t.jsx("small",{className:"field-error",children:D.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:_,value:B,onChange:se,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:O=>v(O.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:O=>k(O.target.value),rows:4,"aria-invalid":!!D.taskDescription}),D.taskDescription&&t.jsx("small",{className:"field-error",children:D.taskDescription})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-column-${e.id}`,children:"Target Column"}),t.jsxs("select",{id:`step-task-column-${e.id}`,value:S,onChange:O=>j(O.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:_,value:B,onChange:se,placeholder:"Use default",disabled:U}),$&&t.jsx("small",{className:"field-error",children:$}),D.modelProvider&&t.jsx("small",{className:"field-error",children:D.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:O=>y(O.target.value?Number(O.target.value):void 0),"aria-invalid":!!D.timeoutMs}),D.timeoutMs&&t.jsx("small",{className:"field-error",children:D.timeoutMs})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:`step-continue-${e.id}`,className:"checkbox-label",children:[t.jsx("input",{id:`step-continue-${e.id}`,type:"checkbox",checked:N,onChange:O=>M(O.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:P,children:"Save Step"})]})]})}function a4({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=s4(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(i4,{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(Rl,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(n4,{type:u.type}),t.jsx("span",{className:"step-card-name",children:u.name}),u.continueOnFailure&&t.jsx("span",{className:"step-card-flag",title:"Continues on failure",children:"⚡"}),t.jsxs("div",{className:"step-card-actions",children:[t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(u.id,"up"),disabled:m===0,title:"Move up","aria-label":`Move ${u.name} up`,children:t.jsx(pi,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(u.id,"down"),disabled:m===e.length-1,title:"Move down","aria-label":`Move ${u.name} down`,children:t.jsx(un,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(u.id),title:"Edit","aria-label":`Edit ${u.name}`,children:t.jsx(Cs,{})}),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 Gb={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},r4={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function o4(e){const n=e.trim();for(const[s,a]of Object.entries(Gb))if(a===n)return s;return"custom"}function l4(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function c4(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 d4(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 u4=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],m4=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function Tp(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function Ip({routine:e,onSubmit:n,onCancel:s,scope:a,projectId:r,onScopeChange:o}){const l=!!e,c=e?d4(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),[v,b]=i.useState(()=>c.triggerType!=="cron"?"custom":o4(c.cronExpression)),[k,S]=i.useState(c.webhookPath),[j,E]=i.useState(c.webhookSecret),[y,N]=i.useState(c.endpoint),[M,D]=i.useState(e?.executionPolicy??"queue"),[C,_]=i.useState(e?.catchUpPolicy??"run_one"),[F,U]=i.useState(e?.enabled??!0),A=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,[T,J]=i.useState(e?.steps&&e.steps.length>0&&!A&&!$?"advanced":"simple"),[B,se]=i.useState(()=>A?"ai-prompt":$?"create-task":"command"),[P,O]=i.useState(e?.command??""),[I,w]=i.useState(e?.steps??[]),[Y,re]=i.useState(!1),[le,ve]=i.useState(e?.timeoutMs??3e5),[de,Fe]=i.useState(A?e.steps?.[0]?.prompt??"":""),[X,L]=i.useState($?e.steps?.[0]?.taskTitle??"":""),[Q,ne]=i.useState($?e.steps?.[0]?.taskDescription??"":""),[H,z]=i.useState($?e.steps?.[0]?.taskColumn??"triage":"triage"),[W,we]=i.useState(A||$?e.steps?.[0]?.modelProvider??"":""),[Z,fe]=i.useState(A||$?e.steps?.[0]?.modelId??"":""),[Oe,Ve]=i.useState([]),[He,Je]=i.useState(!1),[$e,he]=i.useState(null),[ue,Ee]=i.useState(a??"global"),[je,xe]=i.useState({}),[Pe,ie]=i.useState(!1),Me=i.useRef(!0);i.useEffect(()=>()=>{Me.current=!1},[]),i.useEffect(()=>{a&&Ee(a)},[a]),i.useEffect(()=>{let me=!1;return Je(!0),he(null),Os().then(ft=>{me||Ve(ft.models)}).catch(ft=>{me||he(ft instanceof Error?ft.message:"Failed to load models")}).finally(()=>{me||Je(!1)}),()=>{me=!0}},[]);const We=W&&Z?`${W}/${Z}`:"",mt=i.useCallback(me=>{if(!me){we(""),fe("");return}const ft=me.indexOf("/");ft!==-1&&(we(me.slice(0,ft)),fe(me.slice(ft+1)))},[]),st=i.useCallback(()=>{const me={};if(d.trim()||(me.name="Name is required"),ue==="project"&&!r&&(me.scope="Project-specific entries require an active project."),f==="cron"&&v==="custom"&&(g.trim()?l4(g)||(me.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):me.cronExpression="Cron expression is required"),f==="webhook"&&!k.trim()&&(me.webhookPath="Webhook path is required"),f==="api"&&!y.trim()&&(me.endpoint="API endpoint is required"),T==="simple")B==="command"&&!P.trim()&&(me.command="Command is required"),B==="ai-prompt"&&!de.trim()&&(me.prompt="Prompt is required"),B==="create-task"&&!Q.trim()&&(me.taskDescription="Task description is required"),(W.trim()&&!Z.trim()||!W.trim()&&Z.trim())&&(me.model="Both model provider and model ID must be set, or both must be empty");else{I.length===0&&(me.steps="At least one step is required"),Y&&(me.stepsEditing="Please save or cancel all step edits before saving the routine");const ft=[];I.forEach((Et,jt)=>{Et.name?.trim()||ft.push(`Step ${jt+1}: Name is required`),Et.type==="command"&&!Et.command?.trim()&&ft.push(`Step ${jt+1}: Command is required`),Et.type==="ai-prompt"&&!Et.prompt?.trim()&&ft.push(`Step ${jt+1}: Prompt is required`),Et.type==="create-task"&&!Et.taskDescription?.trim()&&ft.push(`Step ${jt+1}: Task description is required`)}),ft.length>0&&(me.steps=ft.join("; "))}return le<1e3&&(me.timeoutMs="Timeout must be at least 1 second (1000ms)"),xe(me),Object.keys(me).length===0},[d,f,g,v,k,y,ue,r,T,B,P,de,Q,W,Z,I,Y,le]),Ze=i.useCallback(async me=>{if(me.preventDefault(),!!st()){ie(!0);try{let ft=e?.scope??ue??(r?"project":"global");ft==="project"&&!r&&(ft="global");const Et=c4(f,g,k,j,y);let jt,$t;T==="simple"?B==="command"?jt=P.trim()||void 0:B==="ai-prompt"?$t=[{id:Tp(),type:"ai-prompt",name:d.trim(),prompt:de.trim(),modelProvider:W.trim()||void 0,modelId:Z.trim()||void 0}]:$t=[{id:Tp(),type:"create-task",name:d.trim(),taskTitle:X.trim()||void 0,taskDescription:Q.trim(),taskColumn:H,modelProvider:W.trim()||void 0,modelId:Z.trim()||void 0}]:$t=I;const Ft={name:d.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:Et,command:jt,steps:$t,timeoutMs:le,executionPolicy:M,catchUpPolicy:C,enabled:F,scope:ft};await n(Ft)}finally{Me.current&&ie(!1)}}},[st,n,d,m,f,g,k,j,y,T,B,P,de,W,Z,X,Q,H,I,le,M,C,F,ue,r,e?.scope,e?.agentId]),dt="routine-name-error",Ae="routine-cron-error",Ue="routine-webhook-error",kt="routine-endpoint-error",De="routine-command-error",be="routine-prompt-error",pe="routine-task-description-error",Re="routine-model-error",Be="routine-timeout-error",at=i.useCallback(me=>{b(me),me!=="custom"&&x(Gb[me])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:Ze,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:me=>u(me.target.value),"aria-invalid":!!je.name,"aria-describedby":je.name?dt:void 0}),je.name&&t.jsx("small",{id:dt,className:"field-error",children:je.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:me=>h(me.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${ue==="global"?" active":""}`,onClick:()=>{Ee("global"),o?.("global")},role:"radio","aria-checked":ue==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:"Global scope",children:[t.jsx(Al,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${ue==="project"?" active":""}`,onClick:()=>{Ee("project"),o?.("project")},role:"radio","aria-checked":ue==="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(ws,{size:12}),"Project"]})]}),t.jsx("small",{children:!r&&!e?.scope?"No active project. Routines will be created at global scope.":ue==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),je.scope&&t.jsx("small",{className:"field-error",children:je.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(yf,{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(Pf,{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(wf,{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(ds,{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:v,onChange:me=>at(me.target.value),children:Object.entries(r4).map(([me,ft])=>t.jsx("option",{value:me,children:ft},me))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:g,onChange:me=>x(me.target.value),disabled:v!=="custom","aria-invalid":!!je.cronExpression,"aria-describedby":je.cronExpression?Ae:void 0}),je.cronExpression?t.jsx("small",{id:Ae,className:"field-error",children:je.cronExpression}):t.jsx("small",{children:v==="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:k,onChange:me=>S(me.target.value),"aria-invalid":!!je.webhookPath,"aria-describedby":je.webhookPath?Ue:void 0}),je.webhookPath?t.jsx("small",{id:Ue,className:"field-error",children:je.webhookPath}):t.jsx("small",{children:"URL path for the webhook endpoint"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-secret",children:"Webhook Secret (optional)"}),t.jsx("input",{id:"routine-webhook-secret",type:"password",placeholder:"Optional — leave empty for unauthenticated webhooks",value:j,onChange:me=>E(me.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:me=>N(me.target.value),"aria-invalid":!!je.endpoint,"aria-describedby":je.endpoint?kt:void 0}),je.endpoint?t.jsx("small",{id:kt,className:"field-error",children:je.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${T==="simple"?" active":""}`,onClick:()=>J("simple"),role:"radio","aria-checked":T==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${T==="advanced"?" active":""}`,onClick:()=>J("advanced"),role:"radio","aria-checked":T==="advanced",children:"Multi-Step"})]}),t.jsx("small",{children:T==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),T==="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${B==="command"?" active":""}`,onClick:()=>se("command"),role:"radio","aria-checked":B==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${B==="ai-prompt"?" active":""}`,onClick:()=>se("ai-prompt"),role:"radio","aria-checked":B==="ai-prompt",children:"AI Prompt"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${B==="create-task"?" active":""}`,onClick:()=>se("create-task"),role:"radio","aria-checked":B==="create-task",children:"Create Task"})]})]}),B==="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:P,onChange:me=>O(me.target.value),"aria-invalid":!!je.command,"aria-describedby":je.command?De:void 0}),je.command?t.jsx("small",{id:De,className:"field-error",children:je.command}):t.jsx("small",{children:"Shell command to execute."})]}):B==="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:de,onChange:me=>Fe(me.target.value),rows:3,"aria-invalid":!!je.prompt,"aria-describedby":je.prompt?be:void 0}),je.prompt?t.jsx("small",{id:be,className:"field-error",children:je.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:Oe,value:We,onChange:mt,placeholder:"Use default",disabled:He}),$e&&t.jsx("small",{className:"field-error",children:$e}),je.model&&t.jsx("small",{id:Re,className:"field-error",children:je.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:me=>L(me.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:Q,onChange:me=>ne(me.target.value),rows:4,"aria-invalid":!!je.taskDescription,"aria-describedby":je.taskDescription?pe:void 0}),je.taskDescription?t.jsx("small",{id:pe,className:"field-error",children:je.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:H,onChange:me=>z(me.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:Oe,value:We,onChange:mt,placeholder:"Use default",disabled:He}),$e&&t.jsx("small",{className:"field-error",children:$e}),je.model&&t.jsx("small",{id:Re,className:"field-error",children:je.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(a4,{steps:I,onChange:w,onEditingChange:re}),je.steps&&t.jsx("small",{className:"field-error",children:je.steps}),je.stepsEditing&&t.jsx("small",{className:"field-error",children:je.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:le,onChange:me=>ve(Number(me.target.value)),"aria-invalid":!!je.timeoutMs,"aria-describedby":je.timeoutMs?Be:void 0}),je.timeoutMs?t.jsx("small",{id:Be,className:"field-error",children:je.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:M,onChange:me=>D(me.target.value),children:u4.map(me=>t.jsx("option",{value:me.value,children:me.label},me.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:C,onChange:me=>_(me.target.value),children:m4.map(me=>t.jsx("option",{value:me.value,children:me.label},me.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:F,onChange:me=>U(me.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:Pe,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:Pe,children:Pe?"Saving…":l?"Save Changes":"Create Routine"})]})]})}const h4=3e4;function p4({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);_i(x,!0,"fusion:automation-modal-size");const v=i.useMemo(()=>({scope:a,projectId:a==="project"?s:void 0}),[a,s]),b=i.useCallback(async()=>{try{const A=await Rj(v);l(A),g($=>{const T={...$};for(const J of A){const B=T[J.id];if(!B||!J.lastRunResult)continue;const se=J.lastRunResult;se.success===B.success&&(se.output||"")===B.output&&(se.error||"")===(B.error||"")&&delete T[J.id]}return T})}catch(A){n(_e(A)||"Failed to load routines","error")}},[n,v]);i.useEffect(()=>{b()},[b]),i.useEffect(()=>{const A=setInterval(()=>{b()},h4);return()=>clearInterval(A)},[b]),i.useEffect(()=>{const A=$=>{$.key==="Escape"&&(c!=="list"?(d("list"),m(void 0)):e())};return document.addEventListener("keydown",A),()=>document.removeEventListener("keydown",A)},[e,c]);const k=Fi(e),S=i.useCallback(async A=>{try{await Tj(A,v),n("Routine created","success"),d("list"),await b()}catch($){n(_e($)||"Failed to create routine","error")}},[n,b,v]),j=i.useCallback(A=>{m(A),d("edit")},[]),E=i.useCallback(async A=>{if(u)try{await Yu(u.id,A,v),n("Routine updated","success"),d("list"),m(void 0),await b()}catch($){n(_e($)||"Failed to update routine","error")}},[u,n,b,v]),y=i.useCallback(async A=>{try{await Ij(A.id,v),n(`Deleted "${A.name}"`,"success"),await b()}catch($){n(_e($)||"Failed to delete routine","error")}},[n,b,v]),N=i.useCallback(async A=>{f(A.id);try{const{result:$}=await $j(A.id,v);g(T=>({...T,[A.id]:{output:$.output||"",error:$.error,success:$.success}})),$.success?n(`"${A.name}" completed successfully`,"success"):n(`"${A.name}" failed: ${$.error||"Unknown error"}`,"error"),await b()}catch($){n(_e($)||"Failed to run routine","error")}finally{f(null)}},[n,b,v]),M=i.useCallback(async A=>{try{await Yu(A.id,{enabled:!A.enabled},v),n(`"${A.name}" ${A.enabled?"disabled":"enabled"}`,"success"),await b()}catch($){n(_e($)||"Failed to toggle routine","error")}},[n,b,v]),D=i.useCallback(()=>{d("list"),m(void 0)},[]);i.useEffect(()=>{c!=="list"&&g({})},[c]);const C=i.useCallback(A=>{r(A),d("list"),m(void 0),g({})},[]),_=()=>c==="create"?t.jsx(Ip,{onSubmit:S,onCancel:D,scope:a,projectId:s}):c==="edit"&&u?t.jsx(Ip,{routine:u,onSubmit:E,onCancel:D,scope:a,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(ds,{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(A=>t.jsx(t4,{routine:A,onEdit:j,onDelete:y,onRun:N,onToggle:M,running:h===A.id,lastRunOutput:p[A.id]??null},A.id))}),F=()=>_(),U=c==="list"&&o.length>0;return t.jsx("div",{className:"modal-overlay open",...k,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(ds,{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(en,{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:()=>C("global"),"aria-pressed":a==="global",title:"Global (user-level) automations",children:[t.jsx(Al,{size:14}),"Global"]}),t.jsxs("button",{type:"button",className:`scope-btn${a==="project"?" active":""}`,onClick:()=>C("project"),"aria-pressed":a==="project",title:"Project-scoped automations",children:[t.jsx(ws,{size:14}),"Project"]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(ds,{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:F()})]})})}const f4=3e4,Bd=new Map,Zc=new Map;function $p(e){return e??"default"}function Dp(e){const n=Bd.get(e);return n?Date.now()>=n.expiresAt?(Bd.delete(e),null):n:null}function g4(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 b4(e){const n=Zc.get(e);if(n)return n;const s=Kr().then(({providers:a,ghCli:r})=>{const l={...g4(a,r),ghCli:r,expiresAt:Date.now()+f4};return Bd.set(e,l),l}).finally(()=>{Zc.delete(e)});return Zc.set(e,s),s}function Jb(e){const n=$p(e),s=Dp(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=$p(e),p=Dp(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 v=await b4(f);if(h)return;r(v.hasAiProvider),l(v.hasGithub),c(v.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 Yb({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(en,{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 x4({isOpen:e,onClose:n,projectId:s,tasks:a,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const{confirm:d}=Qs(),u=oi();Mi(e);const{keyboardOverlap:m,viewportHeight:h,viewportOffsetTop:f,keyboardOpen:p}=ya({enabled:u==="mobile"}),g=p?{"--keyboard-overlap":`${m}px`,"--vv-offset-top":`${f}px`,...h!==null?{"--vv-height":`${h}px`}:{}}:{},[x,v]=i.useState(""),[b,k]=i.useState([]),[S,j]=i.useState([]),[E,y]=i.useState(!1),[N,M]=i.useState(""),[D,C]=i.useState(""),[_,F]=i.useState(""),[U,A]=i.useState(""),[$,T]=i.useState(""),[J,B]=i.useState("default"),[se,P]=i.useState(!1),[O,I]=i.useState([]),[w,Y]=i.useState(!1),[re,le]=i.useState(void 0),[ve,de]=i.useState(Ds),[Fe,X]=i.useState(void 0),[L,Q]=i.useState(null),[ne,H]=i.useState([]),[z,W]=i.useState(!1),[we,Z]=i.useState(!1),fe=i.useRef(null),[Oe,Ve]=i.useState(!1),[He,Je]=i.useState(""),$e=i.useRef(null),{hasAiProvider:he,hasGithub:ue,loading:Ee}=Jb(s),{nodes:je}=Ul(),xe=i.useCallback(De=>{Y(!0),I(De)},[]),Pe=i.useCallback(()=>{Y(!1)},[]),ie=i.useCallback(async()=>{if(ne.length>0){W(!0);return}Z(!0);try{const De=await ba(void 0,s);H(De),W(!0)}catch(De){const be=_e(De);o(be?`Failed to load agents: ${be}`:"Failed to load agents","error"),W(!1)}finally{Z(!1)}},[ne.length,s,o]);i.useEffect(()=>{if(!z)return;const De=be=>{fe.current&&!fe.current.contains(be.target)&&W(!1)};return document.addEventListener("mousedown",De),()=>document.removeEventListener("mousedown",De)},[z]),i.useEffect(()=>{if(!Oe)return;const De=be=>{$e.current&&!$e.current.contains(be.target)&&(Ve(!1),Je(""))};return document.addEventListener("mousedown",De),()=>document.removeEventListener("mousedown",De)},[Oe]);const Me=a.filter(De=>!b.includes(De.id)).sort((De,be)=>{const pe=be.createdAt.localeCompare(De.createdAt);if(pe!==0)return pe;const Re=parseInt(De.id.slice(De.id.lastIndexOf("-")+1),10)||0;return(parseInt(be.id.slice(be.id.lastIndexOf("-")+1),10)||0)-Re}),We=He?Me.filter(De=>De.id.toLowerCase().includes(He.toLowerCase())||De.title&&De.title.toLowerCase().includes(He.toLowerCase())||De.description&&De.description.toLowerCase().includes(He.toLowerCase())):Me,mt=(De,be)=>De.length>be?De.slice(0,be)+"…":De;i.useEffect(()=>{const De=x.trim()!==""||b.length>0||S.length>0||N!==""||D!==""||_!==""||U!==""||O.length>0||L!==null||re!==void 0||ve!==Ds||Fe!==void 0;P(De)},[x,b,S,N,D,_,U,O,L,re,ve,Fe]);const st=i.useCallback(async()=>{se&&!await d({title:"Discard Changes",message:"You have unsaved changes. Discard them?",danger:!0})||(S.forEach(De=>URL.revokeObjectURL(De.previewUrl)),j([]),v(""),k([]),M(""),C(""),F(""),A(""),T(""),B("default"),I([]),Y(!1),Q(null),W(!1),le(void 0),de(Ds),X(void 0),P(!1),n())},[se,n,S,d]),Ze=i.useCallback(async()=>{const De=x.trim();if(!(!De||E)){y(!0);try{const be=N.indexOf("/"),pe=D.indexOf("/"),Re=_.indexOf("/"),Be=await r({title:void 0,description:De,column:"triage",dependencies:b.length?b:void 0,enabledWorkflowSteps:w?O.length>0?O:[]:void 0,...L?{assignedAgentId:L}:{},modelPresetId:J==="preset"&&$||void 0,modelProvider:N&&be!==-1?N.slice(0,be):void 0,modelId:N&&be!==-1?N.slice(be+1):void 0,validatorModelProvider:D&&pe!==-1?D.slice(0,pe):void 0,validatorModelId:D&&pe!==-1?D.slice(pe+1):void 0,planningModelProvider:_&&Re!==-1?_.slice(0,Re):void 0,planningModelId:_&&Re!==-1?_.slice(Re+1):void 0,thinkingLevel:U!==""?U:void 0,reviewLevel:re,priority:ve,nodeId:Fe});if(S.length>0){const at=[];for(const me of S)try{await Ol(Be.id,me.file,s)}catch{at.push(me.file.name)}at.length>0&&o(`Failed to upload: ${at.join(", ")}`,"error")}S.forEach(at=>URL.revokeObjectURL(at.previewUrl)),j([]),v(""),k([]),M(""),C(""),F(""),A(""),T(""),B("default"),I([]),Y(!1),Q(null),W(!1),le(void 0),de(Ds),X(void 0),o(`Created ${Be.id}`,"success"),n()}catch(be){o(_e(be)||"Failed to create task","error")}finally{y(!1)}}},[x,b,S,N,D,_,U,E,r,o,n,s,J,$,O,w,L,re,ve,Fe]),dt=i.useCallback(De=>{De.key==="Escape"&&(De.preventDefault(),st())},[st]),Ue=(L?ne.find(De=>De.id===L):void 0)?.name??L,kt=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:$e,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>Ve(De=>!De),disabled:E,"data-testid":"dep-trigger",children:b.length>0?`${b.length} selected`:"Add dependencies"}),Oe&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:He,onChange:De=>Je(De.target.value),onClick:De=>De.stopPropagation()}),We.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):We.map(De=>t.jsxs("div",{className:`dep-dropdown-item${b.includes(De.id)?" selected":""}`,onClick:()=>{k(b.includes(De.id)?b.filter(be=>be!==De.id):[...b,De.id]),Ve(!1),Je("")},onMouseDown:be=>be.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:De.id}),t.jsx("span",{className:"dep-dropdown-title",children:mt(De.title||De.description||De.id,30)})]},De.id))]})]}),b.length>0&&t.jsx("div",{className:"selected-deps",children:b.map(De=>t.jsxs("span",{className:"dep-chip",children:[De,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>k(b.filter(be=>be!==De)),disabled:E,children:"×"})]},De))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:fe,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{z?W(!1):ie()},disabled:E,"data-testid":"new-task-agent-button",children:[t.jsx(zn,{size:12,style:{verticalAlign:"middle"}}),Ue?` ${Ue}`:" Assign agent"]}),z&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:De=>De.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),we&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!we&&ne.map(De=>t.jsxs("div",{className:`dep-dropdown-item${L===De.id?" selected":""}`,onMouseDown:be=>be.preventDefault(),onClick:()=>{Q(De.id===L?null:De.id),W(!1)},"data-testid":`agent-option-${De.id}`,children:[t.jsx(zn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:De.role}),t.jsx("span",{className:"dep-dropdown-title",children:De.name})]},De.id)),!we&&ne.length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),L&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:De=>De.preventDefault(),onClick:()=>{Q(null),W(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:st,onKeyDown:dt,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:De=>De.stopPropagation(),style:g,children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:st,disabled:E,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!Ee&&t.jsx(Yb,{hasAiProvider:he,hasGithub:ue}),t.jsx(Mb,{mode:"create",description:x,onDescriptionChange:v,dependencies:b,onDependenciesChange:k,executorModel:N,onExecutorModelChange:M,validatorModel:D,onValidatorModelChange:C,presetMode:J,onPresetModeChange:B,selectedPresetId:$,onSelectedPresetIdChange:T,selectedWorkflowSteps:O,onWorkflowStepsChange:xe,onDefaultOnApplied:Pe,pendingImages:S,onImagesChange:j,tasks:a,projectId:s,disabled:E,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:st,planningModel:_,onPlanningModelChange:F,thinkingLevel:U,onThinkingLevelChange:A,reviewLevel:re,onReviewLevelChange:le,priority:ve,onPriorityChange:de,nodeId:Fe,onNodeIdChange:X,nodeOptions:je,renderBelowPrimary:kt,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:st,disabled:E,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Ze,disabled:!x.trim()||E,children:E?"Creating...":"Create Task"})]})]})}):null}function di(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 Lp(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function v4(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function y4(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function w4(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function k4(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 Jo(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function j4(e){if(!e)return"Not yet";const n=new Date(e);return Number.isNaN(n.getTime())?"Not yet":n.toLocaleString()}function N4({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,v]=i.useState(!1),[b,k]=i.useState(null),[S,j]=i.useState(null),[E,y]=i.useState(null),N=i.useCallback(async X=>{l(!0);try{const L=await uN(s);r(L),d(null),y(Date.now()),X?.preserveKillResult||k(null)}catch(L){d(L instanceof Error?L.message:"Failed to load system stats")}finally{l(!1)}},[s]);i.useEffect(()=>{if(!e)return;N();const X=window.setInterval(()=>{N()},5e3);return()=>{window.clearInterval(X)}},[e,N]),i.useEffect(()=>{if(!e)return;(async()=>{try{const L=await ga();m(L.vitestAutoKillEnabled??!0),f(L.vitestKillThresholdPct??90),j(null)}catch(L){j(L instanceof Error?L.message:"Failed to load vitest settings")}})()},[e]),i.useEffect(()=>{if(!e)return;const X=L=>{L.key==="Escape"&&n()};return document.addEventListener("keydown",X),()=>document.removeEventListener("keydown",X)},[e,n]);const M=i.useMemo(()=>{if(!a)return[];const X=a.systemStats,L=Jo(v4(X.heapUsed,X.heapLimit)),Q=Jo(y4(X.rss,X.systemTotalMem));return[{label:"RSS",value:di(X.rss),detail:Lp(X.rss,X.systemTotalMem),className:Q},{label:"Heap Used",value:di(X.heapUsed),detail:`of ${di(X.heapTotal)}`,className:L},{label:"Heap Limit",value:di(X.heapLimit),detail:"V8 limit"},{label:"External",value:di(X.external)},{label:"Array Buffers",value:di(X.arrayBuffers)}]},[a]),D=i.useCallback(async X=>{m(X);try{await Dn({vitestAutoKillEnabled:X}),j(null)}catch(L){j(L instanceof Error?L.message:"Failed to save vitest settings")}},[]),C=i.useCallback(async X=>{const L=Math.min(99,Math.max(50,Number.isFinite(X)?Math.round(X):90));f(L);try{await Dn({vitestKillThresholdPct:L}),j(null)}catch(Q){j(Q instanceof Error?Q.message:"Failed to save vitest settings")}},[]),_=i.useCallback(async()=>{if(!p){if(!x){v(!0);return}g(!0);try{const X=await mN(s);k(X),v(!1),await N({preserveKillResult:!0})}catch(X){d(X instanceof Error?X.message:"Failed to kill vitest processes")}finally{g(!1)}}},[x,p,N,s]);if(!e)return null;const F=a?.systemStats,U=o&&!!a,A=E?`Updated ${new Date(E).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`:"Waiting for first update",$=a?.taskStats,T=F?F.systemTotalMem-F.systemFreeMem:0,J=F?w4(T,F.systemTotalMem):"normal",B=F?Jo(J):"",se=F&&Number.isFinite(F.systemTotalMem)&&F.systemTotalMem>0?Math.max(0,Math.min(100,T/F.systemTotalMem*100)):0,P=F?`System memory used: ${se.toFixed(1)}% (${di(T)} of ${di(F.systemTotalMem)})`:"System memory usage unavailable",O=a?.vitestProcessCount,I=k4(F?.cpuPercent??null,F?.cpuCount??0),w=Jo(I),Y=F?.cpuPercent??null,re=Y===null?0:Math.max(0,Math.min(100,Y)),le=Y===null?"Sampling…":`${Y.toFixed(1)}%`,ve=Y===null?"App CPU usage unavailable: waiting for another sample":`App CPU usage: ${Y.toFixed(1)}%`,de=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":"",Fe=j4(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(qa,{}),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:A})]}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void N(),title:"Refresh","aria-label":"Refresh system stats",children:t.jsx(us,{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(en,{})})]})]}),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:M.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 ${w}`.trim(),children:le}),t.jsx("span",{className:"system-stats-modal__detail",children:Y===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--${I}`,role:"progressbar","aria-valuenow":Math.round(re),"aria-valuemin":0,"aria-valuemax":100,"aria-label":ve,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${I}`,style:{width:`${re}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Load Avg"}),t.jsx("dd",{children:F?.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:F?.cpuCount??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Platform"}),t.jsx("dd",{children:F?.platform??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Node"}),t.jsx("dd",{children:F?.nodeVersion??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"PID"}),t.jsx("dd",{children:F?.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 ${B}`.trim(),children:F?di(T):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:F?`${Lp(T,F.systemTotalMem)} of ${di(F.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--${J}`,role:"progressbar","aria-valuenow":Math.round(se),"aria-valuemin":0,"aria-valuemax":100,"aria-label":P,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${J}`,style:{width:`${se}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Free"}),t.jsx("dd",{children:F?di(F.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,L])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:X}),t.jsx("dd",{children:L})]},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(Vy,{}),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:O??"—"})]})}),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 _(),disabled:p||O===0,children:[t.jsx(Jy,{}),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=>{D(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 L=Number.parseInt(X.target.value,10);C(Number.isNaN(L)?90:L)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:h,"aria-label":"Kill threshold (%)",onChange:X=>{const L=Number.parseInt(X.target.value,10);C(Number.isNaN(L)?90:L)},onBlur:()=>{C(h)}})]})]}),b&&t.jsxs("p",{className:de,children:["Killed ",b.killed," processes"]}),t.jsxs("p",{className:"system-stats-modal__last-kill",children:["Last auto-kill: ",Fe]}),S&&t.jsx("p",{className:"system-stats-modal__kill-result system-stats-modal__kill-result--error",children:S})]})]})]}),c&&a&&t.jsxs("div",{className:"system-stats-modal__footer-error",children:["Latest refresh failed: ",c]})]})})}const S4=5e3;function C4(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),v=i.useCallback(async()=>{try{u(!0),h(null);let S;o?S=await sm({limit:a,projectId:n,type:s}):S=(await Qu({limit:a,type:s,projectId:n})).map(E=>({...E,projectId:n??"",projectName:""})),c(S),p(S.length===a),S.length>0&&(x.current=S[S.length-1].timestamp)}catch(S){h(S instanceof Error?S.message:"Failed to load activity log")}finally{u(!1)}},[a,n,s,o]),b=i.useCallback(async()=>{if(x.current)try{u(!0);let S;o?S=await sm({limit:a,projectId:n,type:s,since:x.current}):S=(await Qu({limit:a,type:s,since:x.current,projectId:n})).map(E=>({...E,projectId:n??"",projectName:""})),c(j=>[...j,...S]),p(S.length===a),S.length>0&&(x.current=S[S.length-1].timestamp)}catch(S){h(S instanceof Error?S.message:"Failed to load more entries")}finally{u(!1)}},[a,n,s,o]),k=i.useCallback(()=>{c([]),p(!1),x.current=void 0},[]);return i.useEffect(()=>{v()},[v]),i.useEffect(()=>{if(r)return g.current=setInterval(()=>{v()},S4),()=>{g.current&&(clearInterval(g.current),g.current=null)}},[r,v]),{entries:l,loading:d,error:m,refresh:v,clear:k,hasMore:f,loadMore:b}}const ed={"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"},E4={"task:created":t.jsx(Cn,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(to,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(us,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(en,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(Wn,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(no,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(Lr,{size:14,className:"activity-icon settings"})};function _4(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 M4({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,v=!c&&o.length>0,{entries:b,loading:k,error:S,refresh:j,hasMore:E}=C4({projectId:x,type:g,limit:100,autoRefresh:e,useCentralFeed:v}),y=b.map(_=>({id:_.id,timestamp:_.timestamp,type:_.type,taskId:_.taskId,taskTitle:_.taskTitle,details:_.details,metadata:_.metadata,projectId:_.projectId,projectName:_.projectName})),N=async()=>{try{await Dj(),j(),p(!1)}catch{p(!1)}},M=_=>{a&&a(_)},D=_=>{h(_),l?.(_==="all"?void 0:_)};i.useEffect(()=>{if(!e)return;const _=F=>{F.key==="Escape"&&(f?p(!1):n())};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[e,n,f]);const C=d!=="all"||m!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:_=>{_.target===_.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(Vr,{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(ws,{size:14}),t.jsxs("select",{value:m,onChange:_=>D(_.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map(_=>t.jsx("option",{value:_.id,children:_.name},_.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(ol,{size:14}),t.jsxs("select",{value:d,onChange:_=>u(_.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(ed).map(([_,F])=>t.jsx("option",{value:_,children:F},_))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>j(),title:"Refresh","data-testid":"activity-refresh",children:k?t.jsx(bt,{size:14,className:"spin"}):t.jsx(us,{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:"×"})]}),C&&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(_=>_.id===m)?.name||m]}),d!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",ed[d]]}),t.jsx("button",{className:"activity-log-clear-filters",onClick:()=>{u("all"),h("all"),l?.(void 0)},children:"Clear all"})]}),t.jsxs("div",{className:"activity-log-content","data-testid":"activity-log-content",children:[S&&t.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[t.jsx(Rs,{size:16}),t.jsx("span",{children:S})]}),y.length===0&&!k&&!S&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(Vr,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:C?"No activity matches the current filters":"No activity recorded yet"}),C&&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(_=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:E4[_.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:ed[_.type]}),t.jsx("span",{className:"activity-log-entry-time",children:_4(_.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[_.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>M(_.taskId),"data-testid":"activity-task-link",children:_.taskId}),_.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:_.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:_.details})]}),_.metadata&&Object.keys(_.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof _.metadata.from=="string"&&typeof _.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[_.metadata.from," → ",_.metadata.to]}),typeof _.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${_.metadata.merged?"success":"error"}`,children:_.metadata.merged?"Merged":"Not merged"})]})]})]},_.id))}),E&&!k&&t.jsx("button",{className:"activity-log-load-more",onClick:j,"data-testid":"activity-load-more",children:"Load More"}),k&&y.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(bt,{size:20,className:"spin"})})]}),f&&t.jsx("div",{className:"activity-log-confirm-overlay",children:t.jsxs("div",{className:"activity-log-confirm-dialog",children:[t.jsx("h3",{children:"Clear Activity Log?"}),t.jsx("p",{children:"This will permanently delete all activity log entries. This action cannot be undone."}),t.jsxs("div",{className:"activity-log-confirm-actions",children:[t.jsx("button",{className:"activity-log-confirm-cancel",onClick:()=>p(!1),children:"Cancel"}),t.jsx("button",{className:"activity-log-confirm-clear",onClick:N,children:"Clear Log"})]})]})})]})}):null}const Cr=[{id:"status",label:"Status",icon:Mf},{id:"changes",label:"Changes",icon:md},{id:"commits",label:"Commits",icon:so},{id:"branches",label:"Branches",icon:Bs},{id:"worktrees",label:"Worktrees",icon:Hv},{id:"stashes",label:"Stashes",icon:Zr},{id:"remotes",label:"Remotes",icon:Cf}];function Op({status:e}){switch(e){case"added":case"untracked":return t.jsx(kv,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(Nf,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(vv,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(Ki,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(Nv,{size:14,className:"gm-file-icon"})}}function Fp({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 A4(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 Xa(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 P4({isOpen:e,onClose:n,tasks:s,addToast:a,projectId:r}){const o=Qs(),[l,c]=i.useState("status"),[d,u]=i.useState(!1),[m,h]=i.useState(null),f=i.useRef(null);_i(f,e,"fusion:git-modal-size");const p=Fi(n),g=A4(a),[x,v]=i.useState(null),[b,k]=i.useState([]),[S,j]=i.useState(new Set),[E,y]=i.useState(""),[N,M]=i.useState(!1),[D,C]=i.useState(null),[_,F]=i.useState(!1),[U,A]=i.useState(null),[$,T]=i.useState(null),J=i.useRef(0),[B,se]=i.useState([]),[P,O]=i.useState(null),[I,w]=i.useState(null),[Y,re]=i.useState(!1),[le,ve]=i.useState(20),[de,Fe]=i.useState(""),[X,L]=i.useState([]),[Q,ne]=i.useState(""),[H,z]=i.useState(""),[W,we]=i.useState(""),[Z,fe]=i.useState(null),[Oe,Ve]=i.useState([]),[He,Je]=i.useState(!1),[$e,he]=i.useState(null),[ue,Ee]=i.useState(null),[je,xe]=i.useState(!1),[Pe,ie]=i.useState([]),[Me,We]=i.useState([]),[mt,st]=i.useState(""),[Ze,dt]=i.useState(null),[Ae,Ue]=i.useState(null),[kt,De]=i.useState(null),be=i.useCallback(async()=>{if(e){u(!0),h(null);try{switch(l){case"status":{const ae=await ci(r);v(ae);break}case"changes":{const[ae,Te]=await Promise.all([ci(r),_a(r)]);v(ae),k(Te),j(new Set),T(null),C(null),A(null);break}case"commits":{const ae=await zk(le,r);se(ae);break}case"branches":{const[ae,Te]=await Promise.all([pr(r),ci(r)]);L(ae),v(Te);break}case"worktrees":{const ae=await qk(r);ie(ae);break}case"stashes":{const ae=await So(r);We(ae);break}case"remotes":{const ae=await ci(r);v(ae);break}}}catch(ae){h(_e(ae)||"Failed to fetch git data"),a(_e(ae)||"Failed to fetch git data","error")}finally{u(!1)}}},[l,e,le,a,r]);i.useEffect(()=>{e&&be()},[be,e]),i.useEffect(()=>{if(!e)return;const ae=Te=>{if(Te.key==="Escape"){n();return}if((Te.key==="ArrowUp"||Te.key==="ArrowDown")&&Te.altKey){Te.preventDefault();const Ne=Cr.findIndex(ee=>ee.id===l);Te.key==="ArrowUp"&&Ne>0?c(Cr[Ne-1].id):Te.key==="ArrowDown"&&Ne<Cr.length-1&&c(Cr[Ne+1].id)}};return document.addEventListener("keydown",ae),()=>document.removeEventListener("keydown",ae)},[e,n,l]);const pe=i.useCallback(async ae=>{try{await Vu(ae,r),a(`Staged ${ae.length} file(s)`,"success");const Te=await _a(r);k(Te),j(new Set),T(null),C(null),A(null)}catch(Te){a(_e(Te)||"Failed to stage files","error")}},[a,r]),Re=i.useCallback(async ae=>{try{await ej(ae,r),a(`Unstaged ${ae.length} file(s)`,"success");const Te=await _a(r);k(Te),j(new Set),T(null),C(null),A(null)}catch(Te){a(_e(Te)||"Failed to unstage files","error")}},[a,r]),Be=i.useCallback(async ae=>{if(await o.confirm({title:"Discard Changes",message:`Discard changes to ${ae.length} file(s)? This cannot be undone.`,danger:!0}))try{await tj(ae,r),a(`Discarded changes to ${ae.length} file(s)`,"success");const[Ne,ee]=await Promise.all([_a(r),ci(r)]);k(Ne),v(ee),j(new Set),T(null),C(null),A(null)}catch(Ne){a(_e(Ne)||"Failed to discard changes","error")}},[a,r,o]),at=i.useCallback(async ae=>{if(ae.preventDefault(),!!E.trim()){M(!0);try{const Te=await Wu(E.trim(),r);a(`Committed: ${Te.hash}`,"success"),y("");const[Ne,ee]=await Promise.all([_a(r),ci(r)]);k(Ne),v(ee),T(null),C(null),A(null)}catch(Te){a(_e(Te)||"Failed to commit","error")}finally{M(!1)}}},[E,a,r]),me=i.useCallback(async()=>{if(E.trim()){M(!0);try{const ae=b.filter(Ie=>!Ie.staged).map(Ie=>Ie.file);ae.length>0&&await Vu(ae,r);const Te=await Wu(E.trim(),r);a(`Committed: ${Te.hash}`,"success"),y("");const[Ne,ee]=await Promise.all([_a(r),ci(r)]);k(Ne),v(ee),T(null),C(null),A(null)}catch(ae){a(_e(ae)||"Failed to commit","error")}finally{M(!1)}}},[E,b,a,r]),ft=i.useCallback(async(ae,Te)=>{T({file:ae,staged:Te}),F(!0),A(null);const Ne=J.current+1;J.current=Ne;try{const ee=await Zk(ae,Te,r);if(J.current!==Ne)return;C(ee)}catch(ee){if(J.current!==Ne)return;const Ie=_e(ee)||"Failed to load file diff";C(null),A(Ie),a(Ie,"error")}finally{J.current===Ne&&F(!1)}},[a,r]),Et=i.useCallback(ae=>{j(Te=>{const Ne=new Set(Te);return Ne.has(ae)?Ne.delete(ae):Ne.add(ae),Ne})},[]),jt=i.useCallback(async ae=>{if(P===ae){O(null),w(null);return}O(ae),re(!0);try{const Te=await hl(ae,r);w(Te)}catch(Te){a(_e(Te)||"Failed to load diff","error"),w(null)}finally{re(!1)}},[P,a,r]),$t=i.useCallback(()=>{ve(ae=>Math.min(ae+20,100))},[]),Ft=i.useMemo(()=>{if(!de.trim())return B;const ae=de.toLowerCase();return B.filter(Te=>Te.message.toLowerCase().includes(ae)||Te.author.toLowerCase().includes(ae)||Te.shortHash.toLowerCase().includes(ae))},[B,de]),Rt=i.useCallback(async ae=>{if(ae.preventDefault(),!!Q.trim()){u(!0);try{await Vk(Q.trim(),H.trim()||void 0,r),a(`Created branch ${Q}`,"success"),ne(""),z("");const Te=await pr(r);L(Te)}catch(Te){a(_e(Te)||"Failed to create branch","error")}finally{u(!1)}}},[Q,H,a,r]),It=i.useCallback(async ae=>{u(!0);try{await Wk(ae,r),a(`Switched to ${ae}`,"success");const[Te,Ne]=await Promise.all([ci(r),pr(r)]);v(Te),L(Ne)}catch(Te){a(_e(Te)||"Failed to checkout branch","error")}finally{u(!1)}},[a,r]),Vt=i.useCallback(async ae=>{if(await o.confirm({title:"Delete Branch",message:`Delete branch "${ae}"?`,danger:!0})){u(!0);try{await qu(ae,void 0,r),a(`Deleted branch ${ae}`,"success");const Ne=await pr(r);L(Ne)}catch(Ne){if(_e(Ne).includes("not fully merged")){if(await o.confirm({title:"Force Delete Branch",message:"Branch has unmerged commits. Force delete?",danger:!0}))try{await qu(ae,!0,r),a(`Force deleted branch ${ae}`,"success");const Ie=await pr(r);L(Ie)}catch(Ie){a(_e(Ie)||"Failed to delete branch","error")}}else a(_e(Ne)||"Failed to delete branch","error")}finally{u(!1)}}},[a,r,o]),Qt=i.useMemo(()=>{if(!W.trim())return X;const ae=W.toLowerCase();return X.filter(Te=>Te.name.toLowerCase().includes(ae))},[X,W]),Jt=i.useCallback(async ae=>{if(Z===ae){fe(null),Ve([]),he(null),Ee(null);return}fe(ae),Ve([]),he(null),Ee(null),Je(!0);try{const Te=await Hk(ae,10,r);Ve(Te)}catch{Ve([])}finally{Je(!1)}},[Z,r]),on=i.useCallback(async ae=>{if($e===ae){he(null),Ee(null);return}he(ae),Ee(null),xe(!0);try{const Te=await hl(ae,r);Ee(Te)}catch{Ee(null)}finally{xe(!1)}},[$e,r]),Kt=i.useCallback(()=>{fe(null),Ve([]),he(null),Ee(null)},[]),qt=i.useCallback(async ae=>{ae.preventDefault(),dt("create");try{await Yk(mt.trim()||void 0,r),a("Changes stashed","success"),st("");const Te=await So(r);We(Te)}catch(Te){a(_e(Te)||"Failed to stash changes","error")}finally{dt(null)}},[mt,a,r]),kn=i.useCallback(async(ae,Te=!1)=>{dt(`apply-${ae}`);try{await Qk(ae,Te,r),a(Te?"Stash popped":"Stash applied","success");const Ne=await So(r);We(Ne)}catch(Ne){a(_e(Ne)||"Failed to apply stash","error")}finally{dt(null)}},[a,r]),nn=i.useCallback(async ae=>{if(await o.confirm({title:"Drop Stash",message:`Drop stash@{${ae}}? This cannot be undone.`,danger:!0})){dt(`drop-${ae}`);try{await Xk(ae,r),a("Stash dropped","success");const Ne=await So(r);We(Ne)}catch(Ne){a(_e(Ne)||"Failed to drop stash","error")}finally{dt(null)}}},[a,r,o]),Xt=i.useCallback(async()=>{Ue("fetch");try{const ae=await Kk(void 0,r);De(ae),a(ae.message||"Fetch completed",ae.fetched?"success":"info");const Te=await ci(r);v(Te)}catch(ae){a(_e(ae)||"Fetch failed","error")}finally{Ue(null)}},[a,r]),Gt=i.useCallback(async()=>{Ue("pull");try{const ae=await Gk(r);De(ae),ae.conflict?a("Merge conflict detected. Resolve manually.","error"):a(ae.message||"Pull completed","success");const Te=await ci(r);v(Te)}catch(ae){a(_e(ae)||"Pull failed","error")}finally{Ue(null)}},[a,r]),ln=i.useCallback(async()=>{Ue("push");try{const ae=await Jk(r);De(ae),a(ae.message||"Push completed","success");const Te=await ci(r);v(Te)}catch(ae){a(_e(ae)||"Push failed","error")}finally{Ue(null)}},[a,r]),ye=i.useMemo(()=>b.filter(ae=>ae.staged),[b]),Le=i.useMemo(()=>b.filter(ae=>!ae.staged),[b]);return e?t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal gm-modal",ref:f,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:be,disabled:d,title:"Refresh",children:t.jsx(us,{size:14,className:d?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(en,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:Cr.map(ae=>{const Te=ae.icon;return t.jsxs("button",{role:"tab","aria-selected":l===ae.id,className:`gm-nav-item${l===ae.id?" active":""}`,onClick:()=>c(ae.id),children:[t.jsx(Te,{size:16}),t.jsx("span",{className:"gm-nav-label",children:ae.label})]},ae.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[d&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(bt,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),m&&!d&&t.jsxs("div",{className:"gm-error",children:[t.jsx(Rs,{size:18}),t.jsx("span",{children:m}),t.jsx("button",{className:"btn btn-sm",onClick:be,children:"Retry"})]}),l==="status"&&!d&&x&&t.jsx(R4,{status:x,copyToClipboard:g}),l==="changes"&&!d&&t.jsx(T4,{status:x,stagedFiles:ye,unstagedFiles:Le,selectedFiles:S,toggleFileSelection:Et,onStageFiles:pe,onUnstageFiles:Re,onDiscardChanges:Be,onSelectDiffFile:ft,selectedDiffTarget:$,changeDiff:D,loadingChangeDiff:_,changeDiffError:U,commitMessage:E,setCommitMessage:y,onCommit:at,onStageAllAndCommit:me,committing:N}),l==="commits"&&!d&&t.jsx(I4,{commits:Ft,commitSearch:de,setCommitSearch:Fe,selectedCommit:P,commitDiff:I,loadingDiff:Y,onCommitClick:jt,onLoadMore:$t,canLoadMore:B.length>=le&&le<100,copyToClipboard:g}),l==="branches"&&!d&&t.jsx($4,{branches:Qt,branchSearch:W,setBranchSearch:we,newBranchName:Q,setNewBranchName:ne,branchBase:H,setBranchBase:z,onCreateBranch:Rt,onCheckoutBranch:It,onDeleteBranch:Vt,loading:d,allBranches:X,selectedBranch:Z,branchCommits:Oe,loadingBranchCommits:He,expandedBranchCommit:$e,branchCommitDiff:ue,loadingBranchCommitDiff:je,onSelectBranch:Jt,onBranchCommitClick:on,onCloseBranchDetails:Kt}),l==="worktrees"&&!d&&t.jsx(D4,{worktrees:Pe}),l==="stashes"&&!d&&t.jsx(L4,{stashes:Me,stashMessage:mt,setStashMessage:st,onCreateStash:qt,onApplyStash:kn,onDropStash:nn,stashLoading:Ze}),l==="remotes"&&!d&&t.jsx(O4,{status:x,remoteLoading:Ae,lastRemoteResult:kt,onFetch:Xt,onPull:Gt,onPush:ln,addToast:a,projectId:r,copyToClipboard:g})]})]})]})}):null}function R4({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(Bs,{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(Wi,{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(Rs,{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(oa,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx(eo,{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 T4({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:v,committing:b}){const k=s.filter(j=>a.has(`unstaged:${j.file}`)),S=n.filter(j=>a.has(`staged:${j.file}`));return t.jsxs("div",{className:"gm-panel","data-testid":"changes-panel",children:[e&&t.jsxs("div",{className:"gm-changes-header",children:[t.jsxs("span",{className:"gm-branch-indicator",children:[t.jsx(Bs,{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:[k.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(k.map(j=>j.file)),title:"Stage selected",children:[t.jsx(Cn,{size:12})," Stage (",k.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(k.map(j=>j.file)),title:"Discard selected",children:t.jsx(no,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(j=>j.file)),title:"Stage all",children:"Stage All"})]})]}),t.jsx("div",{className:"gm-file-list",children:s.length===0?t.jsx("div",{className:"gm-empty",children:"No unstaged changes"}):s.map(j=>{const E=u?.file===j.file&&u.staged===!1;return t.jsxs("div",{className:`gm-file-item${E?" active":""}`,onClick:()=>d(j.file,!1),role:"button",tabIndex:0,onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),d(j.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:y=>y.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`unstaged:${j.file}`),onChange:()=>r(`unstaged:${j.file}`)})}),t.jsx(Op,{status:j.status}),t.jsx("span",{className:"gm-file-name",title:j.file,children:t.jsx("bdo",{dir:"ltr",children:j.file})}),t.jsx(Fp,{status:j.status}),t.jsx("button",{className:"gm-icon-btn",onClick:y=>{y.stopPropagation(),o([j.file])},title:"Stage file",children:t.jsx(Cn,{size:12})})]},`unstaged:${j.file}`)})})]}),t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Staged Changes (",n.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[S.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(S.map(j=>j.file)),title:"Unstage selected",children:["Unstage (",S.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(j=>j.file)),title:"Unstage all",children:"Unstage All"})]})]}),t.jsx("div",{className:"gm-file-list",children:n.length===0?t.jsx("div",{className:"gm-empty",children:"No staged changes"}):n.map(j=>{const E=u?.file===j.file&&u.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${E?" active":""}`,onClick:()=>d(j.file,!0),role:"button",tabIndex:0,onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),d(j.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:y=>y.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`staged:${j.file}`),onChange:()=>r(`staged:${j.file}`)})}),t.jsx(Op,{status:j.status}),t.jsx("span",{className:"gm-file-name",title:j.file,children:t.jsx("bdo",{dir:"ltr",children:j.file})}),t.jsx(Fp,{status:j.status}),t.jsx("button",{className:"gm-icon-btn",onClick:y=>{y.stopPropagation(),l([j.file])},title:"Unstage file",children:t.jsx(en,{size:12})})]},`staged:${j.file}`)})})]})]}),t.jsx("div",{className:"gm-changes-diff",children:u||h||m||f?t.jsxs("div",{className:"gm-diff-section",children:[u&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(md,{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(bt,{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(md,{size:20}),t.jsx("span",{children:"Select a file to view its diff"})]})})]}),t.jsxs("form",{className:"gm-commit-form",onSubmit:x,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:j=>g(j.target.value),rows:3,disabled:b}),t.jsxs("div",{className:"gm-commit-actions",children:[t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:b||!p.trim()||n.length===0,title:n.length===0?"No staged changes to commit":"Commit staged changes",children:[b?t.jsx(bt,{size:14,className:"spin"}):t.jsx(ra,{size:14}),"Commit"]}),s.length>0&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:v,disabled:b||!p.trim(),title:"Stage all and commit",children:"Stage All & Commit"})]})]})]})}function I4({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($i,{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:Xa(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(Wi,{size:12})})}),a===m.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(bt,{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 $4({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:v,loadingBranchCommitDiff:b,onSelectBranch:k,onBranchCommitClick:S,onCloseBranchDetails:j}){return t.jsxs("div",{className:"gm-panel","data-testid":"branches-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Branches"}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx($i,{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:()=>k(E.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[E.isCurrent&&t.jsx(ts,{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:Xa(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(Bs,{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(so,{size:14}),"Commits on ",E.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:j,title:"Close","data-testid":"close-branch-details",children:t.jsx(en,{size:14})})]}),g?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(bt,{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:()=>S(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:Xa(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(bt,{size:16,className:"spin"}),"Loading diff..."]}):v?t.jsxs(t.Fragment,{children:[(y.body||y.message)&&t.jsx("div",{className:"gm-commit-message-full",children:y.body||y.message}),v.stat&&t.jsx("pre",{className:"gm-diff-stat",children:v.stat}),t.jsx("pre",{className:"gm-diff-patch",children:v.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},y.hash))})]})]},E.name))})]})}function D4({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:au(n.path)||n.path})]}),t.jsxs("div",{className:"gm-worktree-detail",children:[n.branch&&t.jsxs("span",{className:"gm-worktree-branch",children:[t.jsx(Bs,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function L4({stashes:e,stashMessage:n,setStashMessage:s,onCreateStash:a,onApplyStash:r,onDropStash:o,stashLoading:l}){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:c=>s(c.target.value),disabled:l!==null}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:l!==null,children:[l==="create"?t.jsx(bt,{size:14,className:"spin"}):t.jsx(Zr,{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(c=>t.jsxs("div",{className:"gm-stash-item",children:[t.jsxs("div",{className:"gm-stash-info",children:[t.jsxs("span",{className:"gm-stash-ref",children:["stash@",`{${c.index}}`]}),t.jsx("span",{className:"gm-stash-message",children:c.message}),t.jsxs("div",{className:"gm-stash-meta",children:[c.branch&&t.jsxs("span",{className:"gm-stash-branch",children:[t.jsx(Bs,{size:12}),c.branch]}),t.jsx("span",{children:Xa(c.date)})]})]}),t.jsxs("div",{className:"gm-stash-actions",children:[t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>r(c.index,!1),disabled:l!==null,title:"Apply stash (keep)",children:l===`apply-${c.index}`?t.jsx(bt,{size:14,className:"spin"}):"Apply"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>r(c.index,!0),disabled:l!==null,title:"Pop stash (apply and drop)",children:"Pop"}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>o(c.index),disabled:l!==null,title:"Drop stash",children:l===`drop-${c.index}`?t.jsx(bt,{size:14,className:"spin"}):t.jsx(Sn,{size:14})})]})]},c.index))})]})}function O4({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:a,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:d}){const u=xe=>{try{return new URL(xe).hostname}catch{return xe.replace(/^git@/,"").split(":")[0]||xe}},[m,h]=i.useState([]),[f,p]=i.useState(!1),[g,x]=i.useState(null),[v,b]=i.useState(""),[k,S]=i.useState(""),[j,E]=i.useState(null),[y,N]=i.useState(""),[M,D]=i.useState(""),[C,_]=i.useState(!1),[F,U]=i.useState([]),[A,$]=i.useState(!1),[T,J]=i.useState(null),[B,se]=i.useState([]),[P,O]=i.useState(!1),[I,w]=i.useState(null),Y=i.useRef(0),re=m.find(xe=>xe.name===T),[le,ve]=i.useState(null),[de,Fe]=i.useState(null),[X,L]=i.useState(!1),[Q,ne]=i.useState(null),[H,z]=i.useState(null),[W,we]=i.useState(!1);i.useEffect(()=>{Z()},[]),i.useEffect(()=>{e&&e.ahead>0?fe():e&&e.ahead===0&&U([])},[e?.ahead]),i.useEffect(()=>{m.length>0&&!T&&J(m[0].name)},[m]),i.useEffect(()=>{T?Oe(T):(se([]),w(null))},[T]),i.useEffect(()=>{!T||!s||Oe(T)},[T,s]),i.useEffect(()=>{T&&!m.find(xe=>xe.name===T)&&J(m.length>0?m[0].name:null)},[m,T]);const Z=async()=>{p(!0);try{const xe=await Pk(c);h(xe)}catch(xe){l(_e(xe)||"Failed to load remotes","error")}finally{p(!1)}},fe=async()=>{$(!0);try{const xe=await Uk(c);U(xe)}catch{U([])}finally{$(!1)}},Oe=async xe=>{const Pe=Y.current+1;Y.current=Pe,O(!0),w(null);try{const ie=await Bk(xe,void 0,10,c);if(Y.current!==Pe)return;se(ie)}catch(ie){if(Y.current!==Pe)return;w(_e(ie)||"Failed to load remote commits"),se([])}finally{Y.current===Pe&&O(!1)}},Ve=Qs(),He=async xe=>{if(xe.preventDefault(),!(!v.trim()||!k.trim())){x("add");try{await Rk(v.trim(),k.trim(),c),l(`Remote '${v}' added successfully`,"success"),b(""),S(""),_(!1),await Z()}catch(Pe){l(_e(Pe)||"Failed to add remote","error")}finally{x(null)}}},Je=async xe=>{if(await Ve.confirm({title:"Remove Remote",message:`Are you sure you want to remove remote '${xe}'?`,danger:!0})){x(`remove-${xe}`);try{await Tk(xe,c),l(`Remote '${xe}' removed`,"success"),await Z()}catch(ie){l(_e(ie)||"Failed to remove remote","error")}finally{x(null)}}},$e=async xe=>{if(M.trim()){x(`rename-${xe}`);try{await Ik(xe,M.trim(),c),l(`Remote renamed to '${M.trim()}'`,"success"),E(null),D(""),await Z()}catch(Pe){l(_e(Pe)||"Failed to rename remote","error")}finally{x(null)}}},he=async xe=>{if(y.trim()){x(`url-${xe}`);try{await $k(xe,y.trim(),c),l("Remote URL updated","success"),E(null),N(""),await Z()}catch(Pe){l(_e(Pe)||"Failed to update remote URL","error")}finally{x(null)}}},ue=i.useCallback(async(xe,Pe)=>{if(Pe==="ahead"){if(le===xe){ve(null),Fe(null);return}ve(xe),Fe(null),L(!0);try{const ie=await hl(xe);Fe(ie)}catch{Fe(null)}finally{L(!1)}}else{if(Q===xe){ne(null),z(null);return}ne(xe),z(null),we(!0);try{const ie=await hl(xe);z(ie)}catch{z(null)}finally{we(!1)}}},[le,Q]),Ee=xe=>{E(`url-${xe.name}`),N(xe.pushUrl||xe.fetchUrl)},je=xe=>{E(`name-${xe.name}`),D(xe.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:()=>_(!C),disabled:g!==null,title:C?"Cancel":"Add Remote",children:C?t.jsx(en,{size:14}):t.jsx(Cn,{size:14})})]}),C&&t.jsxs("form",{className:"gm-remote-form",onSubmit:He,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:v,onChange:xe=>b(xe.target.value),disabled:g==="add",className:"input gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:k,onChange:xe=>S(xe.target.value),disabled:g==="add",className:"input gm-input gm-input-url"}),t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!v.trim()||!k.trim()||g==="add",children:[g==="add"?t.jsx(bt,{size:12,className:"spin"}):t.jsx(Cn,{size:12}),"Add"]})]}),f?t.jsxs("div",{className:"gm-loading",children:[t.jsx(bt,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(xe=>t.jsxs("div",{className:`gm-remote-selector-item${T===xe.name?" selected":""}`,onClick:()=>J(xe.name),role:"button",tabIndex:0,onKeyDown:Pe=>{(Pe.key==="Enter"||Pe.key===" ")&&(Pe.preventDefault(),J(xe.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:xe.name}),xe.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",title:xe.fetchUrl,children:u(xe.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm gm-remote-remove-btn",onClick:Pe=>{Pe.stopPropagation(),Je(xe.name)},disabled:g!==null,title:"Remove remote",children:t.jsx(Sn,{size:14})})]},xe.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[T&&re?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:T}),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(oa,{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(eo,{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(bt,{size:14,className:"spin"}):t.jsx(us,{size:14}),"Fetch"]}),t.jsxs("button",{className:"btn btn-primary",onClick:r,disabled:n!==null||f,children:[n==="pull"?t.jsx(bt,{size:14,className:"spin"}):t.jsx(Ks,{size:14}),"Pull"]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||f,children:[n==="push"?t.jsx(bt,{size:14,className:"spin"}):t.jsx(oa,{size:14}),"Push"]})]})]}),t.jsxs("div",{className:"gm-remote-detail-card","data-testid":"remote-detail-card",children:[t.jsxs("div",{className:"gm-remote-detail-urls",children:[t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Fetch:"}),j===`url-${T}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:y,onChange:xe=>N(xe.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>he(T),disabled:g===`url-${T}`,children:g===`url-${T}`?t.jsx(bt,{size:12,className:"spin"}):t.jsx(ts,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{E(null),N("")},title:"Cancel",children:t.jsx(en,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:re.fetchUrl,children:t.jsx("bdo",{dir:"ltr",children:re.fetchUrl})}),t.jsxs("div",{className:"gm-remote-inline-actions",children:[t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(re.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(Wi,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>Ee(re),disabled:g!==null,title:"Edit remote URL",children:t.jsx(Cs,{size:14})})]})]})]}),re.pushUrl&&re.pushUrl!==re.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:re.pushUrl,children:t.jsx("bdo",{dir:"ltr",children:re.pushUrl})}),t.jsx("div",{className:"gm-remote-inline-actions",children:t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(re.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(Wi,{size:14})})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:j===`name-${T}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:M,onChange:xe=>D(xe.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>$e(T),disabled:g===`rename-${T}`,children:g===`rename-${T}`?t.jsx(bt,{size:12,className:"spin"}):t.jsx(ts,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{E(null),D("")},title:"Cancel",children:t.jsx(en,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>je(re),disabled:g!==null,title:"Edit remote name",children:t.jsx(Cs,{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(oa,{size:14}),"Commits to Push (",e.ahead,")"]})}),A?t.jsxs("div",{className:"gm-loading",children:[t.jsx(bt,{size:14,className:"spin"}),"Loading..."]}):F.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:F.map(xe=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>ue(xe.hash,"ahead"),role:"button",tabIndex:0,onKeyDown:Pe=>{(Pe.key==="Enter"||Pe.key===" ")&&(Pe.preventDefault(),ue(xe.hash,"ahead"))},title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:xe.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:xe.message,children:xe.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:xe.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Xa(xe.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:le===xe.hash?t.jsx(un,{size:14}):t.jsx(Un,{size:14})})]}),le===xe.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:X?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(bt,{size:16,className:"spin"}),"Loading diff..."]}):de?t.jsxs(t.Fragment,{children:[(xe.body||xe.message)&&t.jsx("div",{className:"gm-commit-message-full",children:xe.body||xe.message}),de.stat&&t.jsx("pre",{className:"gm-diff-stat",children:de.stat}),t.jsx("pre",{className:"gm-diff-patch",children:de.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},xe.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(Mf,{size:14}),"Recent commits on ",T]})}),P?t.jsxs("div",{className:"gm-loading",children:[t.jsx(bt,{size:14,className:"spin"}),"Loading commits..."]}):I?t.jsxs("div",{className:"gm-error",children:[t.jsx(Rs,{size:14}),I]}):B.length===0?t.jsxs("div",{className:"gm-empty",children:["No commits found on ",T,". Try fetching first."]}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:B.map(xe=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>ue(xe.hash,"remote"),role:"button",tabIndex:0,onKeyDown:Pe=>{(Pe.key==="Enter"||Pe.key===" ")&&(Pe.preventDefault(),ue(xe.hash,"remote"))},title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:xe.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:xe.message,children:xe.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:xe.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Xa(xe.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:Q===xe.hash?t.jsx(un,{size:14}):t.jsx(Un,{size:14})})]}),Q===xe.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:W?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(bt,{size:16,className:"spin"}),"Loading diff..."]}):H?t.jsxs(t.Fragment,{children:[(xe.body||xe.message)&&t.jsx("div",{className:"gm-commit-message-full",children:xe.body||xe.message}),H.stat&&t.jsx("pre",{className:"gm-diff-stat",children:H.stat}),t.jsx("pre",{className:"gm-diff-patch",children:H.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},xe.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 Ia={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function F4(e,n){return e&&n?`${e}/${n}`:""}function z4(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 zp(e){switch(e){case"file-text":return Ki;case"check-circle":return Wn;case"shield":return Ky;case"zap":return ds;case"eye":return sr;case"globe":return Al;case"layout-grid":return Gi;case"puzzle":return Py;default:return Wn}}function Up(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 U4({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"),[v,b]=i.useState(null),[k,S]=i.useState(!1),[j,E]=i.useState(!1),[y,N]=i.useState(Ia),[M,D]=i.useState(!1),[C,_]=i.useState(!1),[F,U]=i.useState(null),[A,$]=i.useState(null),[T,J]=i.useState({}),[B,se]=i.useState([]),P=i.useRef(null);_i(P,e,"fusion:workflow-steps-modal-size");const O=i.useCallback(async()=>{try{h(!0);const z=await lo(a);o(z)}catch(z){s(_e(z)||"Failed to load workflow steps","error")}finally{h(!1)}},[s,a]),I=i.useCallback(async()=>{try{const z=await Gr(a);J(z||{})}catch{}},[a]),w=i.useCallback(async()=>{try{const z=await Os();se(z.models||[])}catch{}},[]),Y=i.useCallback(async()=>{try{p(!0);const[z,W]=await Promise.all([zj(),Uj()]);c(z.templates);const we=Object.fromEntries(W.templates.map(({pluginId:Z,template:fe})=>[fe.id,Z]));u(we)}catch(z){s(_e(z)||"Failed to load templates","error")}finally{p(!1)}},[s]);i.useEffect(()=>{e&&(O(),Y(),I(),w())},[e,O,Y,I,w]);const re=i.useCallback(()=>{E(!0),S(!1),b(null),N(Ia)},[]),le=i.useCallback(()=>{E(!1),S(!0),b(null),N(Ia)},[]),ve=i.useCallback(z=>{b(z.id),S(!1),N({name:z.name,description:z.description,mode:z.mode||"prompt",phase:z.phase||"pre-merge",prompt:z.prompt,scriptName:z.scriptName||"",enabled:z.enabled,defaultOn:z.defaultOn||!1,modelProvider:z.modelProvider||"",modelId:z.modelId||""})},[]),de=i.useCallback(()=>{b(null),S(!1),E(!1),N(Ia)},[]),Fe=i.useCallback(async()=>{if(!y.name.trim()||!y.description.trim()){s("Name and description are required","error");return}D(!0);try{const z=y.mode==="prompt"&&y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:y.mode==="prompt"?{modelProvider:void 0,modelId:void 0}:{};if(k){const W={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,...z};await Xu(W,a),s("Workflow step created","success")}else v&&(await Lj(v,{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,...z},a),s("Workflow step updated","success"));S(!1),b(null),N(Ia),await O()}catch(z){s(_e(z)||"Failed to save workflow step","error")}finally{D(!1)}},[y,k,v,s,O]),X=i.useCallback(async z=>{try{await Oj(z,a),s("Workflow step deleted","success"),U(null),v===z&&(b(null),N(Ia)),await O()}catch(W){s(_e(W)||"Failed to delete workflow step","error")}},[v,s,O]),L=i.useCallback(async()=>{if(!(!v&&!k)&&y.mode==="prompt"){if(k){if(!y.name.trim()||!y.description.trim()){s("Name and description are required before refining","error");return}D(!0);try{const z=y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:{},W={name:y.name.trim(),description:y.description.trim(),mode:"prompt",prompt:y.prompt.trim()||void 0,enabled:y.enabled,defaultOn:y.defaultOn||void 0,...z},we=await Xu(W,a);S(!1),b(we.id),_(!0);const Z=await Zu(we.id,a);N(fe=>({...fe,prompt:Z.prompt})),s("Prompt refined with AI","success"),await O()}catch(z){s(_e(z)||"Failed to refine prompt","error")}finally{D(!1),_(!1)}return}if(v){_(!0);try{const z=await Zu(v,a);N(W=>({...W,prompt:z.prompt})),s("Prompt refined with AI","success"),await O()}catch(z){s(_e(z)||"Failed to refine prompt","error")}finally{_(!1)}}}},[v,k,y,s,O]),Q=i.useCallback(async z=>{$(z.id);try{await Bj(z.id,a),s(`Added ${z.name} workflow step`,"success"),await O(),x("my-steps"),E(!1)}catch(W){const we=_e(W);we?.includes("already exists")?s(`A workflow step named '${z.name}' already exists`,"error"):s(we||"Failed to add workflow step from template","error")}finally{$(null)}},[s,O]),ne=Fi(n);if(!e)return null;const H=k||v!==null;return t.jsx("div",{className:"modal-overlay open",...ne,"data-testid":"workflow-step-manager",children:t.jsxs("div",{ref:P,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:[!H&&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(Ix,{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(Gi,{size:14}),"Templates (",l.length,")"]})]}),g==="my-steps"&&!H&&!j&&t.jsxs(t.Fragment,{children:[r.length===0&&t.jsx("div",{className:"wfm-empty","data-testid":"empty-state",children:"No workflow steps defined. Create one to get started, or add one from the Templates tab."}),r.length>0&&t.jsx("div",{className:"wfm-step-list",children:r.map(z=>t.jsx("div",{className:"wfm-step-card","data-testid":`workflow-step-${z.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:z.name}),t.jsx("span",{className:`wfm-badge ${z.enabled?"wfm-badge-enabled":"wfm-badge-disabled"}`,children:z.enabled?"Enabled":"Disabled"}),t.jsx("span",{className:`wfm-badge ${(z.mode||"prompt")==="script"?"wfm-badge-script":"wfm-badge-prompt"}`,children:(z.mode||"prompt")==="script"?"Script":"AI Prompt"}),t.jsx("span",{className:`wfm-badge ${(z.phase||"pre-merge")==="post-merge"?"wfm-badge-post-merge":"wfm-badge-pre-merge"}`,children:(z.phase||"pre-merge")==="post-merge"?"Post-merge":"Pre-merge"}),z.defaultOn&&t.jsx("span",{className:"wfm-badge wfm-badge-default-on",children:"Default on"})]}),t.jsx("div",{className:"wfm-step-card-desc",children:z.description})]}),t.jsxs("div",{className:"wfm-step-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>ve(z),title:"Edit","aria-label":`Edit ${z.name}`,children:t.jsx(Cs,{size:14})}),F===z.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>X(z.id),title:"Confirm delete","aria-label":`Confirm delete ${z.name}`,children:t.jsx(ts,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>U(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(en,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>U(z.id),title:"Delete","aria-label":`Delete ${z.name}`,children:t.jsx(Sn,{size:14})})]})]})},z.id))})]}),g==="templates"&&!H&&!j&&t.jsx(t.Fragment,{children:f?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(bt,{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(z=>{const W=zp(z.icon),we=Up(z.category),Z=A===z.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`template-${z.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(W,{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:z.name}),t.jsx("span",{className:we,children:z.category}),d[z.id]&&t.jsx("span",{className:"wfm-badge-category wfm-badge-category-plugin",children:d[z.id]})]}),t.jsx("div",{className:"wfm-template-desc",children:z.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>Q(z),disabled:Z,"data-testid":`add-template-${z.id}`,children:Z?t.jsxs(t.Fragment,{children:[t.jsx(bt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Cn,{size:12}),"Add"]})})]})]})},z.id)})})}),j&&!H&&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:le,"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(bt,{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(z=>{const W=zp(z.icon),we=Up(z.category),Z=A===z.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`chooser-template-${z.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(W,{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:z.name}),t.jsx("span",{className:we,children:z.category}),d[z.id]&&t.jsx("span",{className:"wfm-badge-category wfm-badge-category-plugin",children:d[z.id]})]}),t.jsx("div",{className:"wfm-template-desc",children:z.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>Q(z),disabled:Z,"data-testid":`chooser-add-template-${z.id}`,children:Z?t.jsxs(t.Fragment,{children:[t.jsx(bt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Cn,{size:12}),"Add template"]})})]})]})},z.id)})})]}),H&&t.jsxs("div",{className:"wfm-form","data-testid":"workflow-step-form",children:[t.jsx("h3",{className:"wfm-form-title",children:k?"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:z=>N(W=>({...W,name:z.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:z=>N(W=>({...W,description:z.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:()=>N(z=>({...z,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(Di,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${y.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>N(z=>({...z,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(Li,{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:()=>N(z=>({...z,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:()=>N(z=>({...z,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:L,disabled:!y.description.trim()||C,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[C?t.jsx(bt,{size:12,className:"spin"}):t.jsx(ys,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:y.prompt,onChange:z=>N(W=>({...W,prompt:z.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:()=>N(z=>({...z,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(en,{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:B,value:F4(y.modelProvider,y.modelId),onChange:z=>{const W=z4(z);N(we=>({...we,modelProvider:W.provider,modelId:W.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(T).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:z=>N(W=>({...W,scriptName:z.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(T).map(([z,W])=>t.jsxs("option",{value:z,children:[z," (",W,")"]},z))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:y.enabled,onChange:z=>N(W=>({...W,enabled:z.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:z=>N(W=>({...W,defaultOn:z.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:de,disabled:M,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:Fe,disabled:M||!y.name.trim()||!y.description.trim()||y.mode==="script"&&!y.scriptName.trim(),"data-testid":"save-workflow-step",children:M?"Saving...":k?"Create":"Save"})]})]})]})]})}),!H&&!j&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:re,"data-testid":"add-workflow-step",children:[t.jsx(Cn,{size:14}),"Add Workflow Step"]})})]})})}const B4=36e5,H4=3e5,td=[{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 q4(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 V4(e){return typeof e!="number"||!Number.isFinite(e)?B4:Math.max(H4,Math.round(e))}function tz(e){if(td.some(s=>s.value===e))return[...td];const n={value:e,label:`${q4(e)} (custom)`};return[...td,n].sort((s,a)=>s.value-a.value)}const W4=4,K4=5*6e4;function G4(e){const n=V4(e?.heartbeatIntervalMs);return Math.max(n*W4,K4)}function Bp(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 J4(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 Y4(e){const{state:n,lastHeartbeatAt:s,lastError:a,pauseReason:r,runtimeConfig:o}=e,l=J4(e),c=l||o?.enabled!==!1;if(n==="error")return{label:a??"Error",icon:t.jsx(Gs,{size:14}),color:"var(--state-error-text)",stateDerived:!a};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(mi,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(Gs,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!c)return{label:"Heartbeat Disabled",icon:t.jsx(mi,{size:14}),color:"var(--state-paused-text)",stateDerived:!1};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(zn,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const d=new Date(s).getTime(),u=Date.now()-d,m=G4(o);if(u>m){const h=`No heartbeat for ${Bp(u)} (threshold: ${Bp(m)})`;return{label:"Unresponsive",icon:t.jsx(Gs,{size:14}),color:"var(--state-error-text)",stateDerived:!1,reason:h}}return{label:"Healthy",icon:t.jsx(Vv,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}function Hd({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(zn,{size:Math.max(14,Math.round(n*.55)),"aria-hidden":"true"})})}const Q4="https://github.com/Runfusion/Fusion/issues/new";function X4(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(`
693
- `)});return`${Q4}?${r.toString()}`}function Z4({open:e,onClose:n,errorText:s,issueContext:a}){const[r,o]=i.useState(!1),l=i.useMemo(()=>X4(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(Rs,{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(ts,{size:14}):t.jsx(Wi,{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(jf,{size:14}),"Report on GitHub"]})]})]})}):null}function e$({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(Rs,{size:14}),t.jsx("span",{className:"agent-error-indicator__label",children:s})]}),t.jsx(Z4,{open:a,onClose:()=>r(!1),errorText:e,issueContext:n})]})}const Yo=[{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 t$({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"),[v,b]=i.useState(()=>{if(typeof window>"u")return"list";const I=ss("fn-agent-view",a);return I==="board"||I==="list"?I:"list"});i.useEffect(()=>{const I=ss("fn-agent-view",a);if(I==="board"||I==="list"){b(I);return}b("list")},[a]),i.useEffect(()=>{vs("fn-agent-view",v,a)},[a,v]);const[k,S]=i.useState(null),j=i.useRef(null),[E,y]=i.useState(new Set),[N,M]=i.useState(new Map),{confirm:D}=Qs(),C=i.useMemo(()=>N.size===0?r:r.map(I=>{const w=N.get(I.id);return w?{...I,state:w}:I}),[r,N]),_=i.useMemo(()=>g!=="all"?C:[...C].sort((I,w)=>{const Y=I.state==="paused"?1:0,re=w.state==="paused"?1:0;return Y!==re?Y-re:(w.updatedAt??"").localeCompare(I.updatedAt??"")}),[C,g]),F=i.useCallback(async()=>{c(!0);try{const w=await ba(g!=="all"?{state:g}:void 0,a);o(w)}catch(I){s(`Failed to load agents: ${_e(I)}`,"error")}finally{c(!1)}},[g,s,a]);i.useEffect(()=>{e&&F()},[e,F]),i.useEffect(()=>{if(!e)return;const I=setInterval(()=>{F()},3e4);return()=>{clearInterval(I)}},[e,F]);const U=async()=>{if(m.trim())try{await Qj({name:m.trim(),role:f},a),s(`Agent "${m}" created`,"success"),h(""),u(!1),F()}catch(I){s(`Failed to create agent: ${_e(I)}`,"error")}},A=async(I,w)=>{if(!E.has(I)){y(Y=>new Set(Y).add(I)),M(Y=>{const re=new Map(Y);return re.set(I,w),re});try{await Zj(I,w,a),s(`Agent state updated to ${w}`,"success"),await F(),M(Y=>{const re=new Map(Y);return re.delete(I),re})}catch(Y){M(re=>{const le=new Map(re);return le.delete(I),le}),s(`Failed to update state: ${_e(Y)}`,"error")}finally{y(Y=>{const re=new Set(Y);return re.delete(I),re})}}},$=async(I,w)=>{if(await D({title:"Delete Agent",message:`Delete agent "${w}"? This cannot be undone.`,danger:!0}))try{await eN(I,a),s(`Agent "${w}" deleted`,"success"),F()}catch(re){s(`Failed to delete agent: ${_e(re)}`,"error")}},T=async(I,w)=>{const Y=r.find(re=>re.id===I);if(Y){if(Y.role===w){S(null);return}try{await Xj(I,{role:w},a),s(`Agent role updated to ${Yo.find(re=>re.value===w)?.label??w}`,"success"),S(null),F()}catch(re){s(`Failed to update role: ${_e(re)}`,"error")}}},J=(I,w)=>{I.key==="Escape"&&S(null)},B=I=>Yo.find(w=>w.value===I)?.label??I,se=I=>Y4(I),P=I=>I.color==="var(--state-active-text)"?"active":I.color==="var(--state-paused-text)"?"paused":I.color==="var(--state-error-text)"?"error":"muted",O=(I,w)=>I.state==="error"?{title:void 0,label:"Error"}:{title:w.reason??w.label,label:w.stateDerived?null:w.label};return e?t.jsx("div",{className:"modal-overlay open",onClick:I=>I.target===I.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(zn,{size:20}),"Agents"]}),t.jsxs("div",{className:"modal-actions",children:[t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${v==="board"?" active":""}`,onClick:()=>b("board"),title:"Board view","aria-label":"Board view","aria-pressed":v==="board",children:t.jsx(Gi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${v==="list"?" active":""}`,onClick:()=>b("list"),title:"List view","aria-label":"List view","aria-pressed":v==="list",children:t.jsx(fd,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void F(),title:"Refresh",disabled:l,children:t.jsx(us,{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(ol,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:g,onChange:I=>x(I.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:I=>h(I.target.value),onKeyDown:I=>I.key==="Enter"&&U(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:f,onChange:I=>p(I.target.value),children:Yo.map(I=>t.jsxs("option",{value:I.value,children:[I.icon," ",I.label]},I.value))}),t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:()=>void U(),children:"Create"})]}),t.jsx("div",{className:v==="board"?"agent-board":"agent-list",children:_.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(zn,{size:48,opacity:.3}),t.jsx("p",{children:"No agents found"}),t.jsx("p",{className:"text-secondary",children:"Create an agent to get started"})]}):v==="board"?_.map(I=>{const w=se(I),Y=O(I,w),re=P(w);return t.jsxs("div",{className:"agent-board-card","data-state":I.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:t.jsx(Hd,{agent:I,size:20})}),t.jsx("span",{className:"agent-board-badge","data-state":I.state,children:I.state}),t.jsx("span",{className:"agent-board-health","data-health":re,title:Y.title,children:w.icon})]}),t.jsx("div",{className:"agent-board-name",title:I.name,children:I.name}),t.jsx("div",{className:"agent-board-id",children:I.id}),t.jsxs("div",{className:"agent-board-actions",children:[I.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A(I.id,"active"),disabled:E.has(I.id),title:"Activate",children:t.jsx(ns,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(I.id,I.name),title:"Delete",children:t.jsx(Sn,{size:14})})]}),I.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A(I.id,"paused"),disabled:E.has(I.id),title:"Pause",children:t.jsx(mi,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void A(I.id,"paused"),disabled:E.has(I.id),title:"Stop",children:t.jsx(si,{size:14})})]}),I.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A(I.id,"active"),disabled:E.has(I.id),title:"Resume",children:t.jsx(ns,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void A(I.id,"paused"),disabled:E.has(I.id),title:"Stop",children:t.jsx(si,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(I.id,I.name),title:"Delete",children:t.jsx(Sn,{size:14})})]}),I.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A(I.id,"paused"),disabled:E.has(I.id),title:"Pause",children:t.jsx(mi,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void A(I.id,"paused"),disabled:E.has(I.id),title:"Stop",children:t.jsx(si,{size:14})})]}),I.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A(I.id,"active"),disabled:E.has(I.id),title:"Retry",children:t.jsx(ns,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void A(I.id,"paused"),disabled:E.has(I.id),title:"Stop",children:t.jsx(si,{size:14})})]})]})]},I.id)}):_.map(I=>{const w=se(I),Y=O(I,w),re=P(w);return t.jsxs("div",{className:"agent-card","data-state":I.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[k===I.id?t.jsx("select",{ref:j,className:"select agent-role-select",value:I.role,onChange:le=>void T(I.id,le.target.value),onKeyDown:le=>J(le,I.id),onBlur:()=>S(null),autoFocus:!0,children:Yo.map(le=>t.jsxs("option",{value:le.value,children:[le.icon," ",le.label]},le.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>S(I.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:le=>{(le.key==="Enter"||le.key===" ")&&S(I.id)},children:t.jsx(Hd,{agent:I,size:20})}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:I.name}),t.jsx("span",{className:"agent-id text-secondary",children:I.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":I.state,children:I.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":re,title:Y.title,children:[w.icon,Y.label?` ${Y.label}`:""]}),t.jsx("span",{className:"badge text-secondary",children:B(I.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[I.state==="error"&&I.lastError?t.jsx(e$,{errorText:I.lastError,issueContext:{surface:"AgentListModal list",agentId:I.id,agentName:I.name,agentState:I.state,taskId:I.taskId}}):null,I.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:I.taskId})]}),I.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date(I.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[I.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A(I.id,"active"),disabled:E.has(I.id),title:"Activate",children:[t.jsx(ns,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(I.id,I.name),title:"Delete",children:[t.jsx(Sn,{size:14})," Delete"]})]}),I.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A(I.id,"paused"),disabled:E.has(I.id),title:"Pause",children:[t.jsx(mi,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void A(I.id,"paused"),disabled:E.has(I.id),title:"Stop",children:[t.jsx(si,{size:14})," Stop"]})]}),I.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A(I.id,"active"),disabled:E.has(I.id),title:"Resume",children:[t.jsx(ns,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void A(I.id,"paused"),disabled:E.has(I.id),title:"Stop",children:[t.jsx(si,{size:14})," Stop"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(I.id,I.name),title:"Delete",children:[t.jsx(Sn,{size:14})," Delete"]})]}),I.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A(I.id,"paused"),disabled:E.has(I.id),title:"Pause",children:[t.jsx(mi,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void A(I.id,"paused"),disabled:E.has(I.id),title:"Stop",children:[t.jsx(si,{size:14})," Stop"]})]}),I.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A(I.id,"active"),disabled:E.has(I.id),title:"Retry",children:[t.jsx(ns,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void A(I.id,"paused"),disabled:E.has(I.id),title:"Stop",children:[t.jsx(si,{size:14})," Stop"]})]})]})]},I.id)})})]})]})}):null}function n$({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 ck();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 k=await pk(b);u.current&&d({kind:k.enabled?"enabled":"disabled",restartRequired:k.restartRequired}),n?.(k.enabled),await m()}catch(k){u.current&&d({kind:"error",message:k instanceof Error?k.message:String(k)})}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."]}),v=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(bt,{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(Kn,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(s$,{status:a,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:v})]}),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(Hp,{status:a,authenticated:e}),c&&t.jsx(qp,{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(Kn,{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(Hp,{status:a,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(qp,{action:c})]})}function s$({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 Hp({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(bt,{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 qp({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 i$({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 hk();return c.current&&r(x),x},[]);i.useEffect(()=>{d()},[d]);const u=i.useCallback(async x=>{l(x?"enabling":"disabling");try{const v=await gk(x);n?.(v.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(bt,{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(Kn,{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(Kn,{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 a$(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 nd({instructions:e,"data-testid":n}){const[s,a]=i.useState(!1),r=a$(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(ts,{size:12}):t.jsx(Wi,{size:12})})]})]},u))}):e})}function r$({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 o$=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"]),l$=/^[a-z][a-z0-9-]*$/,Vp=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function Wp(){return{id:"",name:"",reasoning:!1}}function c$({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??""),[v,b]=i.useState(e?.models?.length?e.models:[Wp()]),[k,S]=i.useState(null),j=v.length>1,E=i.useMemo(()=>k??r??null,[k,r]);function y(C,_){b(F=>F.map((U,A)=>A===C?{...U,..._}:U))}function N(C){b(_=>_.length<=1?_:_.filter((F,U)=>U!==C))}function M(){if(!l.trim())return"Provider ID is required.";if(!l$.test(l.trim()))return"Provider ID must be kebab-case.";if(!o&&o$.has(l.trim()))return"Provider ID conflicts with a built-in provider.";if(!m.trim())return"Base URL is required.";try{const C=new URL(m.trim());if(C.protocol!=="http:"&&C.protocol!=="https:")return"Base URL must use http or https."}catch{return"Base URL must be a valid URL."}return Vp.includes(f)?v.length===0?"At least one model is required.":v.some(C=>!C.id?.trim())?"Each model must have a model ID.":null:"API type is required."}async function D(C){C.preventDefault();const _=M();S(_),!_&&await n({id:l.trim(),name:d.trim()||void 0,baseUrl:m.trim(),api:f,apiKey:g.trim()||void 0,models:v.map(F=>({id:F.id.trim(),name:F.name?.trim()||void 0,reasoning:!!F.reasoning,contextWindow:F.contextWindow,maxTokens:F.maxTokens}))})}return t.jsxs("form",{onSubmit:D,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=>c(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:C=>u(C.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:C=>h(C.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:C=>p(C.target.value),disabled:a,children:Vp.map(C=>t.jsx("option",{value:C,children:C},C))})]}),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:C=>x(C.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:v.map((C,_)=>t.jsxs("div",{className:"custom-provider-form__model-row",children:[t.jsx("input",{className:"input","aria-label":`Model ID ${_+1}`,placeholder:"Model ID",value:C.id,onChange:F=>y(_,{id:F.target.value}),disabled:a}),t.jsx("input",{className:"input","aria-label":`Model name ${_+1}`,placeholder:"Display name",value:C.name??"",onChange:F=>y(_,{name:F.target.value}),disabled:a}),t.jsxs("label",{className:"checkbox-label custom-provider-form__toggle",children:[t.jsx("input",{type:"checkbox",checked:!!C.reasoning,onChange:F=>y(_,{reasoning:F.target.checked}),disabled:a}),"Reasoning"]}),t.jsx("input",{className:"input","aria-label":`Context window ${_+1}`,placeholder:"Context window",type:"number",value:C.contextWindow??"",onChange:F=>y(_,{contextWindow:F.target.value?Number(F.target.value):void 0}),disabled:a}),t.jsx("input",{className:"input","aria-label":`Max tokens ${_+1}`,placeholder:"Max tokens",type:"number",value:C.maxTokens??"",onChange:F=>y(_,{maxTokens:F.target.value?Number(F.target.value):void 0}),disabled:a}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>N(_),disabled:a||!j,"aria-label":`Remove model ${_+1}`,children:"×"})]},`${_}-model`))}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>b(C=>[...C,Wp()]),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 d$=new Set(["google-antigravity","antigravity","google-gemini-cli"]);function u$(e){return!d$.has(e)}function Kp(e){return e.filter(n=>u$(n.id))}const pa="fusion_model_onboarding_state",Za=[],er=[],Sl=!1,Cl=!1,tr={},m$=void 0,Hi=["ai-setup","github","project-setup","first-task"],h$={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function Ys(){if(typeof window>"u")return null;try{const e=localStorage.getItem(pa);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?p$(n):null}catch{return null}}function p$(e){const n=e.postOnboardingDismissedAt??m$;return{...e,completedSteps:e.completedSteps??Za,skippedSteps:e.skippedSteps??er,dismissed:e.dismissed??Sl,completed:e.completed??Cl,stepData:e.stepData??tr,...n?{postOnboardingDismissedAt:n}:{}}}function Qo(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:Za,skippedSteps:er,dismissed:Sl,completed:Cl,stepData:tr};try{localStorage.setItem(pa,JSON.stringify(s))}catch{}return}try{const s=Ys(),a=new Date().toISOString(),r=n.completed??Cl;let o=n.dismissed??Sl;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??Za,c=n.skippedSteps??s?.skippedSteps??er,d={...s?.stepData??tr};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(pa,JSON.stringify(u))}catch{}}}function f$(e){if(!(typeof window>"u"))try{const n=Ys(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:Za,skippedSteps:[e],dismissed:Sl,completed:Cl,stepData:tr};localStorage.setItem(pa,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(pa,JSON.stringify(r))}catch{}}function Gp(){if(!(typeof window>"u"))try{const e=Ys(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:Za,skippedSteps:er,dismissed:!1,completed:!0,stepData:tr};localStorage.setItem(pa,JSON.stringify(s))}catch{}}function nr(){const e=Ys();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function g$(){if(!(typeof window>"u"))try{const e=Ys(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:Za,skippedSteps:er,dismissed:!1,completed:!1,stepData:tr,postOnboardingDismissedAt:n};localStorage.setItem(pa,JSON.stringify(s))}catch{}}function Qb(){const e=Ys();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function b$(){const e=Ys();return!e||nr()?!1:e.currentStep!=="complete"}function x$(){const e=Ys();if(!e||nr()||e.currentStep==="complete")return null;const n=e.currentStep,s=h$[n]??w$(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function v$(){const e=Ys();return e?e.skippedSteps:er}function y$(e){const n=Ys();return!n||!n.stepData?null:n.stepData[e]??null}function w$(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const Xb="fusion_onboarding_events",Jp="fusion_onboarding_session_id",k$=200,j$=50;function ni(e,n={}){if(!(typeof window>"u"))try{const s=S$(),a=_$(n.step),r={type:e,timestamp:new Date().toISOString(),...a?{step:a}:{},metadata:n,sessionId:N$()},o=E$([...s,r]);C$(o)}catch{}}function N$(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(Jp);if(e)return e;const n=Yp();return sessionStorage.setItem(Jp,n),n}catch{return Yp()}}function Yp(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function S$(){try{const e=localStorage.getItem(Xb);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(M$):[]}catch{return[]}}function C$(e){try{localStorage.setItem(Xb,JSON.stringify(e))}catch{}}function E$(e){const n=[...e];for(;n.length>k$;)n.splice(0,j$);return n}function _$(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function M$(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 A$=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}))??[]}),P$={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"}}},Zb={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:"..."}},R$={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},Qp={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 qd(e){if(Qp[e])return Qp[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 sd=["anthropic","openai","google","gemini","ollama"],T$=["anthropic","claude-cli","droid-cli","llama-cpp","openai-codex","gemini","minimax","kimi","zai"],I$={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"},$$={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function Vd(e){return I$[e]??e}function Xp(e){const n=Vd(e),s=T$.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function Zp(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=Xp(e.id),a=Xp(n.id);if(s!==a)return s-a;const r=Vd(e.id),o=Vd(n.id);if(r!==o)return r.localeCompare(o);const l=$$[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 D$(e,n){const s=n.trim();if(!s)return"API key is required";const a=Zb[e]??R$;return a.pattern.test(s)?null:`${qd(e)} keys should follow this format: ${a.hint} (e.g. ${a.example})`}const ex={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"},L$={description:"AI provider — connect to start using AI models",apiKeyInfo:ex};function Wd(e){return P$[e]??L$}function O$(e){return Wd(e.id).apiKeyInfo??ex}function F$({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 z$({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=Zb[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(ii,{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(ii,{summary:"Advanced setup details",children:g})]})}const U$=150;function B$({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:a,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const d=Ys(),u=d?.currentStep,m=u==="complete"?"ai-setup":Hi.includes(u)?u:"ai-setup",h=d?.completedSteps??[],f=d?.skippedSteps??v$(),[p,g]=i.useState(!0),[x,v]=i.useState(m),[b,k]=i.useState(h),[S,j]=i.useState(f),[E,y]=i.useState(!1),[N,M]=i.useState(""),[D,C]=i.useState(!1),[_,F]=i.useState(null),[U,A]=i.useState(null),[$,T]=i.useState([]),[J,B]=i.useState(void 0),[se,P]=i.useState(!0),[O,I]=i.useState(null),[w,Y]=i.useState({}),[re,le]=i.useState({}),[ve,de]=i.useState({}),[Fe,X]=i.useState(null),[L,Q]=i.useState([]),[ne,H]=i.useState(""),[z,W]=i.useState(!1),[we,Z]=i.useState({}),[fe,Oe]=i.useState({}),[Ve,He]=i.useState({}),[Je,$e]=i.useState([]),[he,ue]=i.useState(!1),[Ee,je]=i.useState(!1),[xe,Pe]=i.useState(),ie=i.useRef({}),Me=i.useRef(null),We=i.useRef(null),mt=i.useRef(null),[st,Ze]=i.useState({}),[dt,Ae]=i.useState(()=>Ys()?.stepData?.github?.skipped===!0),Ue=i.useRef(0),kt=i.useRef(l),De=i.useRef(!1),be=d?.currentStep,pe=!!d&&d.currentStep!=="complete";_i(We,p,"fusion:model-onboarding-modal-size"),i.useEffect(()=>{const K=Me.current;K&&(K.scrollTop=0)},[x]);const[Re,Be]=i.useState(()=>Ys()?.stepData?.["ai-setup"]?.skippedProviders??{}),at=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],me=at.findIndex(K=>K.key===x),ft=x==="complete"?at.length:me;i.useEffect(()=>{x!=="complete"&&Qo(x,{completedSteps:b,skippedSteps:S})},[x,b,S]),i.useEffect(()=>{De.current||(De.current=!0,ni("onboarding:wizard-opened",{source:pe?"resume":"initial",resumedFromStep:be}))},[pe,be]),i.useEffect(()=>{const K=kt.current!=null,Ke=l!=null;!K&&Ke&&y(!0),Ke||y(!1),kt.current=l},[l]);const Et=i.useRef(m);i.useEffect(()=>{if(Et.current==="ai-setup"&&x!=="ai-setup"&&!$.some(Ke=>Ke.id!=="github"&&Ke.authenticated)){const Ke={};for(const Ye of $)Ye.id!=="github"&&!Ye.authenticated&&!Re[Ye.id]&&(Ke[Ye.id]=!0);if(Object.keys(Ke).length>0){const Ye={...Re,...Ke};Be(Ye),Qo(x,{stepData:{"ai-setup":{skippedProviders:Ye}}})}}Et.current=x},[x,$,Re]);const jt=i.useCallback(async()=>{try{const{providers:K,ghCli:Ke}=await Kr(),Ye=Kp(K);T(Ye),B(Ke),Y(ht=>{const Nt={};for(const[_t,zt]of Object.entries(ht)){const Jn=Ye.find(as=>as.id===_t);Jn&&!Jn.authenticated&&Jn.loginInProgress&&(Nt[_t]=zt)}return Object.keys(Nt).length===Object.keys(ht).length?ht:Nt}),Ze(ht=>{let Nt=!1;const _t={...ht};for(const[zt,Jn]of Object.entries(ht)){if(Jn!=="pending")continue;Ye.find(ce=>ce.id===zt)?.loginInProgress||(delete _t[zt],Nt=!0)}return Nt?_t:ht}),Be(ht=>{const Nt={...ht};for(const _t of Ye)_t.authenticated&&Nt[_t.id]&&delete Nt[_t.id];return Object.keys(Nt).length===Object.keys(ht).length?ht:Nt})}catch{}},[]),$t=i.useCallback(async()=>{try{const K=await bk();$e((K.providers??[]).map(A$))}catch{}},[]),Ft=i.useCallback(async K=>{je(!0),Pe(void 0);try{await vk(K),await $t(),await Os().then(Ke=>Q(Ke.models??[])),ue(!1)}catch(Ke){Pe(_e(Ke)||"Failed to create custom provider")}finally{je(!1)}},[$t]),Rt=i.useRef(!1);i.useEffect(()=>{x==="ai-setup"&&$t(),Rt.current&&jt(),Rt.current=x!=="ai-setup"},[x,jt,$t]),i.useEffect(()=>{if(!$.some(Ye=>Ye.loginInProgress))return;const Ke=setInterval(()=>{jt()},2e3);return()=>clearInterval(Ke)},[$,jt]);const It=$.find(K=>K.id==="github"),Vt=!!It,Qt=It?.authenticated??!1,Jt=It?.loginInProgress??!1,on=J?.authenticated??!1,Kt=Qt||on,qt=!Qt&&on,kn=i.useCallback(K=>{if(K.authenticated)return"connected";const Ke=st?.[K.id];return Ke==="timeout"||Ke==="failed"?"retry":Re[K.id]?"skipped":"not-connected"},[st,Re]);function nn({status:K}){const Ke={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:Ye,className:ht}=Ke[K];return t.jsx("span",{"data-testid":"provider-status-badge",className:ht,"data-status":K,children:Ye})}const Xt=i.useCallback(()=>{if(Kt)return"connected";const K=st.github;return K==="pending"?"pending":K==="failed"||K==="timeout"?"failed":dt?"skipped":"not-connected"},[Kt,st,dt]);function Gt({status:K}){const Ke={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:Ye,className:ht}=Ke[K];return t.jsx("span",{"data-testid":"github-status-badge",className:ht,"data-status":K,children:Ye})}const ln=i.useCallback(async()=>{try{const K=await Os();Q(K.models)}catch{}},[]),ye=i.useCallback(async()=>{try{const K=await ga();if(K.defaultProvider&&K.defaultModelId){const Ke=`${K.defaultProvider}/${K.defaultModelId}`;H(Ke)}}catch{}},[]);i.useEffect(()=>{Promise.all([jt(),ln(),ye()]).finally(()=>P(!1))},[jt,ln,ye]),i.useEffect(()=>{const K=y$("ai-setup");if(K?.loginOutcomes){const Ke=K.loginOutcomes,Ye={};for(const[ht,Nt]of Object.entries(Ke))Nt!=="pending"&&(Ye[ht]=Nt);Object.keys(Ye).length>0&&Ze(Ye)}},[]);const Le=i.useCallback((K,Ke)=>{Qo(x,{completedSteps:b,stepData:{"ai-setup":{loginOutcomes:{[K]:Ke}}}})},[x,b]);i.useEffect(()=>{const K=Object.entries(st).filter(([Ke,Ye])=>Ye!=="pending");for(const[Ke,Ye]of K)Le(Ke,Ye)},[st,Le]),i.useEffect(()=>()=>{mt.current&&clearInterval(mt.current),Object.values(ie.current).forEach(clearTimeout),ie.current={}},[]);const ae=i.useCallback(K=>{Ae(K),Qo(x,{completedSteps:b,stepData:{github:{skipped:K}}})},[x,b]),Te=i.useCallback(K=>K==="complete"?-1:Hi.indexOf(K),[]),Ne=i.useCallback(()=>{k(Ke=>[...new Set([...Ke,x])]),j(Ke=>Ke.filter(Ye=>Ye!==x)),ni("onboarding:step-completed",{step:x}),x==="github"&&!Qt&&ae(!1);const K=Te(x);K>=0&&K<Hi.length-1&&v(Hi[K+1])},[x,Qt,ae,Te]),ee=i.useCallback(()=>{j(Ke=>[...new Set([...Ke,x])]),f$(x),ni("onboarding:step-skipped",{step:x}),x==="github"&&!Qt&&ae(!0);const K=Te(x);K>=0&&K<Hi.length-1&&v(Hi[K+1])},[x,Qt,ae,Te]),Ie=i.useCallback(()=>{const K=x;k(Ye=>Ye.filter(ht=>ht!==K)),j(Ye=>Ye.filter(ht=>ht!==K)),K==="github"&&!Qt&&ae(!1);const Ke=Te(x);Ke>0&&v(Hi[Ke-1])},[x,Qt,ae,Te]),St=i.useCallback(()=>{ee()},[ee]),pt=i.useCallback(async K=>{Ze(Ye=>{const ht=Ye[K];if(ht&&ht!=="pending"){const{[K]:Nt,..._t}=Ye;return _t}return Ye});const Ke=()=>{Y(Ye=>{if(!(K in Ye))return Ye;const ht={...Ye};return delete ht[K],ht}),le(Ye=>{if(!(K in Ye))return Ye;const ht={...Ye};return delete ht[K],ht}),de(Ye=>{if(!(K in Ye))return Ye;const ht={...Ye};return delete ht[K],ht})};Ke(),Ze(Ye=>({...Ye,[K]:"pending"})),I(K),Ue.current=0;try{const{url:Ye,instructions:ht,manualCode:Nt}=await yk(K);ht?.trim()&&Y(_t=>({..._t,[K]:ht})),Nt&&le(_t=>({..._t,[K]:Nt})),window.open(Ni(Ye),"_blank"),mt.current=setInterval(async()=>{if(Ue.current++,Ue.current>=U$){mt.current&&(clearInterval(mt.current),mt.current=null),I(null),T(_t=>_t.map(zt=>zt.id===K?{...zt,loginInProgress:!1}:zt)),Ze(_t=>({..._t,[K]:"timeout"})),Ke(),n("Login timed out. Please try again.","warning");return}try{const{providers:_t,ghCli:zt}=await Kr(),Jn=Kp(_t);T(Jn),B(zt);const as=Jn.find(ce=>ce.id===K);if(as?.authenticated){mt.current&&(clearInterval(mt.current),mt.current=null),I(null),Ze(ce=>({...ce,[K]:"success"})),Ke(),K==="github"&&ae(!1),n("Login successful","success");return}as?.loginInProgress||(mt.current&&(clearInterval(mt.current),mt.current=null),I(null),Ze(ce=>({...ce,[K]:"failed"})),Ke(),n("Login did not complete. Please try again.","error"))}catch{}},2e3)}catch(Ye){Ye instanceof Error&&Ye.message.includes("already in progress")||Ye&&typeof Ye=="object"&&"status"in Ye&&Ye.status===409?(n("Login already in progress. Cancel it to retry.","warning"),Ze(Nt=>({...Nt,[K]:"pending"})),jt()):(n(Ye instanceof Error?Ye.message:"Login failed","error"),Ze(Nt=>({...Nt,[K]:"failed"}))),I(null),Ke()}},[n,jt,ae]),Dt=i.useCallback(async K=>{const Ke=ve[K]?.trim();if(!Ke){n("Paste the full redirect URL or authorization code first.","warning");return}X(K);try{(await wk(K,Ke)).submitted?(de(ht=>{if(!(K in ht))return ht;const Nt={...ht};return delete Nt[K],Nt}),n("Authorization code received. Finishing login…","success")):n("That authorization code was already submitted. Waiting for login…","warning")}catch(Ye){n(_e(Ye)||"Failed to submit authorization code","error")}finally{X(null)}},[n,ve]),Ut=i.useCallback(async K=>{mt.current&&(clearInterval(mt.current),mt.current=null),I(K),Ue.current=0,T(Ke=>Ke.map(Ye=>Ye.id===K?{...Ye,loginInProgress:!1}:Ye)),Ze(Ke=>({...Ke,[K]:"cancelled"}));try{await jk(K),await jt().catch(()=>{}),n("Login cancelled","success")}catch(Ke){n(_e(Ke)||"Failed to cancel login","error")}finally{I(null),Y(Ke=>{if(!(K in Ke))return Ke;const Ye={...Ke};return delete Ye[K],Ye}),le(Ke=>{if(!(K in Ke))return Ke;const Ye={...Ke};return delete Ye[K],Ye}),de(Ke=>{if(!(K in Ke))return Ke;const Ye={...Ke};return delete Ye[K],Ye}),X(Ke=>Ke===K?null:Ke)}},[n,jt]),Ce=i.useCallback((K,Ke)=>{Z(ht=>({...ht,[K]:Ke}));const Ye=ie.current[K];Ye&&(clearTimeout(Ye),delete ie.current[K]),Oe(ht=>{if(!ht[K])return ht;const Nt={...ht};return delete Nt[K],Nt}),He(ht=>{if(!ht[K])return ht;const Nt={...ht};return delete Nt[K],Nt})},[]),et=i.useCallback(()=>{const K=Me.current;if(!K)return;const Ke=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof K.scrollTo=="function"){K.scrollTo({top:0,behavior:Ke?"auto":"smooth"});return}}catch{}K.scrollTop=0},[]),tt=i.useCallback(async(K,Ke)=>{const Ye=(Ke??we[K]??"").trim(),ht=D$(K,Ye);if(ht){Oe(_t=>({..._t,[K]:ht}));return}const Nt=ie.current[K];Nt&&(clearTimeout(Nt),delete ie.current[K]),I(K),Oe(_t=>{const zt={..._t};return delete zt[K],zt}),He(_t=>{if(!_t[K])return _t;const zt={..._t};return delete zt[K],zt});try{await Nk(K,Ye),await jt(),et(),Z(_t=>{const zt={..._t};return delete zt[K],zt}),Oe(_t=>{if(!_t[K])return _t;const zt={..._t};return delete zt[K],zt}),He(_t=>({..._t,[K]:"✓ Key saved"})),ie.current[K]=setTimeout(()=>{He(_t=>{if(!_t[K])return _t;const zt={..._t};return delete zt[K],zt}),delete ie.current[K]},3e3),n("API key saved","success")}catch(_t){const zt=_t instanceof TypeError&&_t.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":_t instanceof Error?_t.message:"Failed to save API key";Oe(Jn=>({...Jn,[K]:zt})),He(Jn=>{if(!Jn[K])return Jn;const as={...Jn};return delete as[K],as}),n(zt,"error")}finally{I(null)}},[we,n,jt,et]),Lt=i.useCallback(async K=>{I(K);try{await Sk(K),await jt(),n("API key removed","success")}catch(Ke){n(Ke instanceof Error?Ke.message:"Failed to clear API key","error")}finally{I(null)}},[n,jt]),Zt=i.useCallback(async K=>{I(K);try{await kk(K),await jt(),n("Logged out","success")}catch(Ke){n(Ke instanceof Error?Ke.message:"Logout failed","error")}finally{I(null)}},[n,jt]),sn=i.useCallback(K=>{H(K)},[]),At=i.useCallback(async()=>{try{const K={modelOnboardingComplete:!0};if(ne){const Ke=ne.indexOf("/"),Ye=Ke!==-1?ne.slice(0,Ke):void 0,ht=Ke!==-1?ne.slice(Ke+1):ne,Nt=L.find(_t=>_t.id===ht);Nt?(K.defaultProvider=Nt.provider,K.defaultModelId=Nt.id):Ye&&ht&&(K.defaultProvider=Ye,K.defaultModelId=ht)}await Dn(K),Gp()}catch{}},[ne,L,Dn,Gp]),cn=i.useCallback(async()=>{const K=[...new Set([...b,"first-task"])];W(!0);try{await At(),ni("onboarding:completed",{completedSteps:K,skippedSteps:S}),k(K),j(Ke=>Ke.filter(Ye=>Ye!=="first-task")),v("complete")}finally{W(!1)}},[At,b,S]),Tn=i.useCallback(async()=>{if(!s)return;const K=N.trim();if(!K){F("Please enter a task description.");return}F(null),C(!0);let Ke=!1;try{const Ye=await ml({description:K,source:{sourceType:"dashboard_ui"}},s);A(Ye),y(!0),ni("onboarding:first-task-created",{taskId:Ye?.id}),n("Task created","success"),Ke=!0}catch(Ye){const ht=Ye instanceof Error?Ye.message:"Something went wrong creating your task. Please try again.";F(ht),n(ht,"error")}finally{C(!1)}Ke&&At()},[s,N,n,At]),En=i.useCallback(async()=>{W(!0);try{await At()}finally{W(!1)}ni("onboarding:open-new-task",{}),r?.()},[At,r]),bn=i.useCallback(async()=>{if(Kt){W(!0);try{await At()}finally{W(!1)}g(!1),e(),ni("onboarding:open-github-import",{}),o?.()}},[At,Kt,e,o]),In=i.useCallback(async()=>{ni("onboarding:dismissed",{currentStep:x,completedSteps:b,skippedSteps:S}),W(!0);try{await Dn({modelOnboardingComplete:!0})}catch{}g(!1),e()},[x,b,S,e]),ge=i.useCallback(()=>{ni("onboarding:finished",{}),g(!1),e()},[e]),ut=i.useCallback(()=>{const K=l??U;K&&(At(),c?.(K),e())},[l,U,At,c,e]),xn=i.useCallback(()=>{At(),e()},[At,e]);if(!p)return null;const oe=Xt(),ct=$.filter(K=>K.id!=="github"),rt=[...ct].sort(Zp),wt=rt.some(K=>!K.type||K.type==="oauth"),ot=rt.some(K=>K.type==="api_key"),vt=ct.filter(K=>K.authenticated),Wt=vt.length>0,an=!!s,pn=x==="github"&&!Wt,Hn=(()=>{if(!ne)return"";const K=ne.indexOf("/"),Ke=K===-1?void 0:ne.slice(0,K),Ye=K===-1?ne:ne.slice(K+1),ht=L.find(Nt=>Nt.id===Ye&&(!Ke||Nt.provider===Ke));return ht?.name?ht.name:Ke?`${qd(Ke)} ${Ye}`:ne})(),Mn=[];if(an?Mn.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):Mn.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),Wt){const K=qd(vt[0]?.id??"");Mn.push({label:"AI Provider",status:"connected",detail:`${K} connected — AI agents can work on tasks`})}else ct.length>0&&ct.some(K=>Re[K.id])?Mn.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):Mn.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});Kt?Mn.push({label:"GitHub",status:"connected",detail:qt?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!Vt||dt?Mn.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):Mn.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),Hn&&Mn.push({label:"Default Model",status:"connected",detail:Hn});const Qn=l??U,ms=Qn?.description?.split(`
694
- `)[0]?.trim()||Qn?.title||"",Xn=new Set(sd),mn=rt.filter(K=>Xn.has(K.id)).sort((K,Ke)=>{const Ye=sd.indexOf(K.id),ht=sd.indexOf(Ke.id);return Ye!==ht?Ye-ht:Zp(K,Ke)}),Pt=rt.filter(K=>K.authenticated&&!Xn.has(K.id)),is=rt.filter(K=>!K.authenticated&&!Xn.has(K.id)),Gn=K=>{const Ke=st[K.id]==="timeout"||st[K.id]==="failed"||st[K.id]==="cancelled",Ye=K.loginInProgress&&!Ke;if(K.id==="llama-cpp"&&K.type==="cli")return t.jsx(i$,{authenticated:K.authenticated,onToggled:()=>{jt()}},K.id);if(K.id==="claude-cli"&&K.type==="cli")return t.jsx(n$,{authenticated:K.authenticated,onToggled:()=>{jt()}},K.id);if(K.type==="api_key"){const ht=Wd(K.id),Nt=O$(K);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${K.id}`,className:`onboarding-provider-card${K.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${K.id}`,"aria-hidden":"true",children:t.jsx(Kn,{provider:K.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(Ef,{size:14,className:"onboarding-provider-key-icon"}),K.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:ht.description}),t.jsx(nn,{status:kn(K)}),K.authenticated&&K.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",K.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(z$,{provider:K,apiKeyInfo:Nt,inputValue:we[K.id]??"",isSaving:O===K.id,error:fe[K.id],success:Ve[K.id],isConnected:K.authenticated,onInputChange:Ce,onSave:tt,onClear:Lt})})]},K.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${K.id}`,className:`onboarding-provider-card${K.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${K.id}`,"aria-hidden":"true",children:t.jsx(Kn,{provider:K.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:K.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:Wd(K.id).description}),t.jsx(nn,{status:kn(K)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:O===K.id?K.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 Ut(K.id),children:"Cancel"})]}):Ye?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 Ut(K.id),children:"Cancel"})]}):K.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>Zt(K.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>pt(K.id),children:"Login"})}),(O===K.id||Ye)&&w[K.id]&&t.jsx(nd,{instructions:w[K.id],"data-testid":`onboarding-login-instructions-${K.id}`}),(O===K.id||Ye)&&re[K.id]&&t.jsx(r$,{value:ve[K.id]??"",onChange:ht=>de(Nt=>({...Nt,[K.id]:ht})),onSubmit:()=>void Dt(K.id),prompt:re[K.id].prompt,placeholder:re[K.id].placeholder,helpText:re[K.id].helpText,disabled:Fe===K.id,submitLabel:Fe===K.id?"Submitting…":"Submit code","data-testid":`onboarding-manual-code-${K.id}`}),st[K.id]==="timeout"&&O!==K.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),st[K.id]==="failed"&&O!==K.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},K.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:We,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(ds,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(Ks,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Tu,{size:24})," Set Up Your Project"]}),x==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(Tu,{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:In,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(en,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:at.map((K,Ke)=>{const Ye=ft>Ke,ht=b.includes(K.key)&&Ye,Nt=S.includes(K.key)&&!b.includes(K.key)&&Ye,_t=ht||Nt;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[Ke>0&&t.jsx("div",{className:`model-onboarding-step-connector ${Ke<=ft?"done":""}`}),_t?t.jsxs("button",{className:`model-onboarding-step-indicator ${x===K.key?"active":""} ${ht?"done":""} ${Nt?"skipped":""}`,onClick:()=>v(K.key),"aria-label":`Go back to ${K.label}`,title:`Review ${K.label}`,children:[t.jsx("span",{className:"step-number",children:ht?t.jsx(Wn,{size:14}):Nt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Ke+1}),t.jsx("span",{className:"step-label",children:K.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${x===K.key?"active":""} ${ht?"done":""} ${Nt?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:ht?t.jsx(Wn,{size:14}):Nt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Ke+1}),t.jsx("span",{className:"step-label",children:K.label})]})]},K.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:Me,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."}),!se&&$.length>0&&(()=>{const K=$.filter(_t=>_t.id!=="github"&&_t.authenticated).length,Ke=$.filter(_t=>_t.id!=="github").length,Ye=Object.keys(Re).filter(_t=>!$.find(zt=>zt.id===_t)?.authenticated).length;if(Ke===0)return null;let ht="onboarding-provider-summary",Nt="";return K>0?(ht+=" onboarding-provider-summary--connected",Nt=`✓ ${K} of ${Ke} provider${Ke!==1?"s":""} connected`):Ye>0?(ht+=" onboarding-provider-summary--skipped",Nt=`${Ye} provider${Ye!==1?"s":""} skipped`):(ht+=" onboarding-provider-summary--none",Nt="No providers connected yet"),t.jsx("div",{className:ht,"data-testid":"provider-summary",children:Nt})})(),t.jsx(qi,{slotId:"onboarding-recommendation-card",projectId:s}),t.jsx(ii,{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(K=>K.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),se?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(bt,{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(qi,{slotId:"onboarding-provider-card",projectId:s,renderPlaceholder:!1,actions:{refreshAuthProviders:()=>{jt()}}}),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"}),mn.length>0?t.jsx("div",{className:"model-onboarding-providers",children:mn.map(K=>Gn(K))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),Pt.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:Pt.map(K=>Gn(K))})]}),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(ii,{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."})}),L.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:L,value:ne,onChange:sn,placeholder:"Select a default model…",label:"Default model"})}),ne&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",L.find(K=>K.id===ne)?.name??ne]})})]}),t.jsx(ii,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsxs("div",{"data-testid":"onboarding-advanced-provider-settings",children:[is.length>0?t.jsx("div",{className:"model-onboarding-providers",children:is.map(K=>Gn(K))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."}),Je.length>0?t.jsx("div",{className:"onboarding-custom-provider-list",children:Je.map(K=>t.jsxs("div",{className:"onboarding-custom-provider-item",children:[t.jsx(Kn,{provider:K.id,size:"sm"}),t.jsx("span",{children:K.name||K.id})]},K.id))}):null,he?t.jsx(c$,{onSave:Ft,onCancel:()=>{ue(!1),Pe(void 0)},saving:Ee,error:xe}):t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>ue(!0),children:"Add custom provider"})]})}),wt&&t.jsx(ii,{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."})}),ot&&t.jsx(ii,{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(qi,{slotId:"onboarding-setup-help",projectId:s})]})]}),x==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[Kt?t.jsx("p",{className:"model-onboarding-description",children:qt?"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."}),!Kt&&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"})]})}),pn&&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(ii,{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."})}),Vt?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(Ks,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(Gt,{status:oe})})]}),Qt&&(O==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>Zt("github"),children:"Disconnect"}))]}),(oe==="not-connected"||oe==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[O==="github"||Jt?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 Ut("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>pt("github"),children:[t.jsx(Ks,{size:16}),"Connect"]}),(O==="github"||Jt)&&w.github&&t.jsx(nd,{instructions:w.github,"data-testid":"onboarding-login-instructions-github"})]}),oe==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:qt?"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."}),oe==="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:()=>pt("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:St,children:"Skip for now"})]})]}),oe==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),oe==="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:()=>pt("github"),children:"Connect anyway"})})]}),oe==="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(Kn,{provider:"github",size:"lg"})}),qt?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:()=>v("project-setup"),children:qt?"Continue with gh CLI auth →":"Continue without GitHub →"}),qt&&(O==="github"||Jt?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(bt,{size:14,className:"onboarding-spinner"}),"Waiting for OAuth login…"]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>pt("github"),children:[t.jsx(Kn,{provider:"github",size:"sm"}),"Connect OAuth (optional)"]}))]}),qt&&(O==="github"||Jt)&&w.github&&t.jsx(nd,{instructions:w.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."}),an?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(ii,{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&&Qn?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:Qn.id}),ms&&t.jsx("p",{className:"onboarding-task-created__description",children:ms}),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:ut,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:xn,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[an?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"onboarding-first-task-form",children:[t.jsx("label",{className:"onboarding-first-task-form__label",htmlFor:"onboarding-first-task-input",children:"Describe your first task"}),t.jsx("textarea",{id:"onboarding-first-task-input",className:"input onboarding-first-task-form__input","data-testid":"onboarding-first-task-input",value:N,onChange:K=>{M(K.target.value),F(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:Tn,disabled:D,"data-testid":"onboarding-first-task-submit",children:D?t.jsxs(t.Fragment,{children:[t.jsx(bt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),_&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:_}),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(F$,{items:Mn}),an&&t.jsxs(t.Fragment,{children:[t.jsx(ii,{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:En,disabled:z,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${Kt?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:bn,disabled:z||!Kt,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Ks,{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"}),!Kt&&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:In,disabled:z,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:ee,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:Ne,children:"Next →"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Ie,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:ee,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:Ne,children:"Next →"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Ie,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:Ne,disabled:!an,children:"Next →"})]}),x==="first-task"&&!E&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Ie,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:cn,disabled:z,children:z?t.jsxs(t.Fragment,{children:[t.jsx(bt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),x==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:ge,children:[t.jsx(Wn,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function tx({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 H$=i.lazy(()=>Rn(()=>import("./SetupWizardModal-tG_MF_nA.js"),__vite__mapDeps([11,1,12,13,14,5,6,15])).then(e=>({default:e.SetupWizardModal}))),q$=i.lazy(()=>Rn(()=>import("./SettingsModal-WGCF_pk8.js"),__vite__mapDeps([16,1,17,18,19,2,5,6,20])).then(e=>({default:e.SettingsModal})));function V$(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{Rn(()=>import("./SettingsModal-WGCF_pk8.js"),__vite__mapDeps([16,1,17,18,19,2,5,6,20]))},{timeout:1500})}function W$({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,v]=i.useState(null),b=c.detailTask?(()=>{const N=n.find(M=>M.id===c.detailTask?.id);return N?"prompt"in c.detailTask?{...c.detailTask,...N,prompt:c.detailTask.prompt,log:c.detailTask.log}:N:c.detailTask})():null,k=p??c.closeSettings,S=i.useCallback(()=>{c.openNewTask()},[c]),j=i.useCallback(()=>{c.openGitHubImport()},[c]),E=i.useCallback(N=>{v(null),c.closeModelOnboarding(),c.openDetailTask(N)},[c]),y=i.useCallback(async N=>{const M=await u.handleModalCreate(N);return c.modelOnboardingOpen&&v(M),M},[u.handleModalCreate,c.modelOnboardingOpen]);return i.useEffect(()=>{!c.modelOnboardingOpen&&x&&v(null)},[c.modelOnboardingOpen,x]),i.useEffect(()=>{V$()},[]),t.jsxs(t.Fragment,{children:[b&&t.jsx(na,{children:t.jsx(wR,{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(na,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(q$,{onClose:k,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(MT,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:u.handleGitHubImport,tasks:n,projectId:e}),t.jsx(na,{children:t.jsx(TT,{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(na,{children:t.jsx(HT,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:u.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(uI,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(hI,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx($I,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),c.todosOpen&&t.jsx(FI,{isOpen:!0,onClose:c.closeTodos,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan}),t.jsx(GI,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e,anchorRect:c.usageAnchorRect}),t.jsx(N4,{isOpen:c.systemStatsOpen,onClose:c.closeSystemStats,projectId:e}),c.schedulesOpen&&t.jsx(p4,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(na,{children:t.jsx(x4,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:y,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(M4,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:a,onOpenTaskDetail:N=>{const M=n.find(D=>D.id===N);M&&c.openDetailTask(M)}}),t.jsx(na,{children:t.jsx(P4,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(na,{children:t.jsx(U4,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(t$,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(i.Suspense,{fallback:null,children:t.jsx(H$,{onProjectRegistered:d.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(B$,{onComplete:d.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:d.handleAddProject,onOpenNewTask:S,onOpenGitHubImport:j,firstCreatedTask:x,onViewTask:E}),t.jsx(tx,{toasts:o,onRemove:l})]})}function K$({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 Kd=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function G$(e,n){if(n==="ready")return"done";const s=Kd.findIndex(r=>r.id===n),a=Kd.findIndex(r=>r.id===e);return a<s?"done":a===s?"active":"pending"}function J$({stage:e}){const[n]=i.useState(()=>hw());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:Kd.map(s=>{const a=G$(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(bt,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:s.label})]},s.id)})})]})})}const Y$=5e3;function Q$(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function X$(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++,bl(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 Z$(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 v=await dN(n);o(v)}catch(v){if(v instanceof Error&&v.name==="AbortError")return;u(v instanceof Error?v.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()},Y$),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[f]);const p=X$(e,s,a),g=Q$(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:g,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:d,refresh:f}}const eD={planning:fi,subtask:ca,mission_interview:As,milestone_interview:As,slice_interview:As},tD={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function nD({sessions:e,generating:n,needsInput:s,onOpenSession:a,onDismissSession:r}){const{confirm:o}=Qs(),[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}=lr(),g=i.useMemo(()=>va(),[]);if(i.useEffect(()=>{if(!l)return;const b=k=>{m.current&&!m.current.contains(k.target)&&c(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[l]),i.useEffect(()=>{const b=new Set,k=new Map;for(const S of e){const j=p.get(S.id),E=[S.status,S.updatedAt,j?.tabId??S.lockedByTab??"",j?.stale?"stale":"fresh"].join("|"),y=h.current.get(S.id);y&&y!==E&&b.add(S.id),k.set(S.id,E)}if(h.current=k,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,v=s>0;return t.jsxs("div",{ref:m,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${v?" 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(bt,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(dd,{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 k=eD[b.type],S=b.status==="generating",j=b.status==="awaiting_input",E=b.status==="error",y=p.get(b.id),N=y?.tabId??b.lockedByTab??null,M=!!(N&&N!==g&&!y?.stale),D=d.has(b.id);return t.jsxs("div",{className:`background-tasks-indicator__item${D?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:D?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:D?"translateY(-1px)":void 0},onClick:async()=>{M&&!await o({title:"Open Active Session",message:"This session is active in another tab. Open anyway?"})||(a(b),c(!1))},children:[E?t.jsx(Rs,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):t.jsx(k,{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":tD[b.type],S&&" — generating...",j&&!M&&" — needs input",j&&M&&" — active in another tab"]})]}),S&&t.jsx(bt,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),j&&!M&&t.jsx(dd,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),j&&M&&t.jsx(Il,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:C=>{C.stopPropagation(),r(b.id)},title:"Dismiss",children:t.jsx(en,{size:12})})]},b.id)})})]})]})}function sD(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 iD(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:ns};case"paused":return{label:"Paused",color:"var(--triage)",icon:mi};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:ds}}}function aD({tasks:e,projectId:n,taskStuckTimeoutMs:s,backgroundSessions:a,backgroundGenerating:r,backgroundNeedsInput:o,onOpenBackgroundSession:l,onDismissBackgroundSession:c,lastFetchTimeMs:d,currentProjectPath:u,onOpenProjectDirectory:m}){const{stats:h,loading:f,error:p}=Z$(e,n,s,d),[g,x]=i.useState(!1),v=i.useMemo(()=>iD(h.executorState),[h.executorState]),b=i.useMemo(()=>sD(h.lastActivityAt),[h.lastActivityAt]),k=v.icon;return p?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(Dl,{size:14}),p]})}):f&&h.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 ${h.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(nD,{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:h.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 ${h.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:h.runningTaskCount}),t.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),t.jsx("span",{className:"executor-status-bar__max",children:h.maxConcurrent})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),h.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:h.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 ${h.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 ${h.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:h.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:h.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${g?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>x(S=>!S),"aria-label":g?"Hide project directory":"Show project directory","aria-expanded":g,"data-testid":"executor-project-path-toggle",title:g?"Hide project directory":"Show project directory",children:t.jsx(ws,{size:12,"aria-hidden":"true"})}),g&&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(Oi,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:b})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx(k,{size:12,style:{color:v.color},"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__state",style:{color:v.color},children:v.label})]})]})}const rD={planning:fi,subtask:ca,mission_interview:As,milestone_interview:As,slice_interview:As},oD={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},nx="fusion:session-banner-dismissed";function Dr(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function lD(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(nx);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:Dr(r);s.set(a,o)}return s}catch{return new Map}}function cD(e){if(!(typeof window>"u"))try{const n={};for(const[s,a]of e)n[s]=a;window.localStorage.setItem(nx,JSON.stringify(n))}catch{}}const Ii=lD();function dD({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:a}){const[r,o]=i.useState(0),l=()=>{cD(Ii),o(g=>g+1)};i.useEffect(()=>{if(Ii.size===0)return;const g=new Map(e.map(v=>[v.id,v]));let x=!1;for(const[v,b]of Ii){const k=g.get(v);if(!k)continue;if(!(k.status==="awaiting_input"||k.status==="error")){Ii.delete(v),x=!0;continue}Dr(k.updatedAt)>b&&(Ii.delete(v),x=!0)}x&&l()},[e]);const c=i.useMemo(()=>e.filter(g=>{if(g.status!=="awaiting_input"&&g.status!=="error")return!1;const x=Ii.get(g.id);return x===void 0?!0:Dr(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=>{Ii.set(g.id,Math.max(Dr(g.updatedAt),Date.now())),l()},f=g=>{Ii.delete(g.id),l(),n(g)},p=()=>{const g=Date.now();for(const x of c)Ii.set(x.id,Math.max(Dr(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(Rs,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(en,{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=rD[g.type],v=g.status==="error";return t.jsxs("article",{className:`session-notification-banner__item${v?" 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:[v?t.jsx(Rs,{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:v?"Failed":oD[g.type]})]})]}),t.jsxs("div",{className:"session-notification-banner__actions",children:[t.jsx("button",{className:"session-notification-banner__resume",onClick:()=>f(g),children:v?"Retry":"Resume"}),t.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{h(g),s(g.id)},"aria-label":`Dismiss ${g.title}`,children:t.jsx(en,{size:14,"aria-hidden":"true"})})]})]},g.id)})})]})}const sx="fusion:cli-binary-banner-dismissed";function uD(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(sx)==="1"}catch{return!1}}function mD(){if(!(typeof window>"u"))try{window.localStorage.setItem(sx,"1")}catch{}}function hD({onOpenSettings:e}){const[n,s]=i.useState(null),[a,r]=i.useState(()=>uD()),[o,l]=i.useState(!1),[c,d]=i.useState(null);i.useEffect(()=>{if(a)return;let k=!1;return dk().then(S=>{k||s(S)}).catch(()=>{}),()=>{k=!0}},[a]);const u=i.useCallback(async()=>{l(!0),d(null);try{const k=await uk();s({binary:k.binary,expectedVersion:k.expectedVersion,state:k.state,install:k.install}),k.installResult.success||d(k.installResult.permissionsHint||k.installResult.stderr||`Install failed (exit ${k.installResult.exitCode??"n/a"})`)}catch(k){d(k instanceof Error?k.message:String(k))}finally{l(!1)}},[]),m=i.useCallback(()=>{mD(),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."]}),v=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:v}),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(en,{size:16})})]})}function pD({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(en,{size:16,"aria-hidden":"true"})})]})}function fD({onResume:e}){const n=x$();if(!n)return null;const s=n.completedSteps.length,a=Hi.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(ys,{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:()=>{ni("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(ns,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function gD({onOpenSettings:e,onOpenModelOnboarding:n}){const s=nr(),a=Qb(),[r,o]=i.useState(!0),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[m,h]=i.useState({needsAiProvider:!1,needsDefaultModel:!1,needsGitHub:!1});i.useEffect(()=>{if(!s||a){o(!1);return}let b=!1;return(async()=>{try{o(!0),c(!1);const[S,j]=await Promise.all([Kr(),ga()]);if(b)return;const E=S.providers??[],y=E.find(_=>_.id==="github"),M=!E.some(_=>_.id!=="github"&&_.authenticated),D=!j.defaultProvider&&!j.defaultModelId,C=y?!y.authenticated:!1;h({needsAiProvider:M,needsDefaultModel:D,needsGitHub:C})}catch{b||c(!0)}finally{b||o(!1)}})(),()=>{b=!0}},[s,a]);const f=i.useCallback(()=>{g$(),u(!0)},[]),p=i.useCallback(()=>{n()},[n]),g=i.useCallback(()=>{e("global-models")},[e]),x=i.useCallback(()=>{e("authentication")},[e]),v=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:ds}),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:Ef}),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:Ks}),b},[m.needsAiProvider,m.needsDefaultModel,m.needsGitHub,x,g,p]);return!s||a||d||r||l||v.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(fi,{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:v.map(b=>{const k=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(k,{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(qi,{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(en,{size:16,"aria-hidden":!0})})]})}function bD({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 id(e){return e>99?"99+":String(e)}function xD({view:e,onChangeView:n,footerVisible:s,modalOpen:a=!1,keyboardOpen:r=!1,onOpenSettings:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:d,mailboxUnreadCount:u=0,onOpenGitManager:m,onOpenWorkflowSteps:h,onOpenSchedules:f,onOpenScripts:p,onToggleTerminal:g,onOpenFiles:x,onOpenTodos:v,todosOpen:b=!1,onOpenGitHubImport:k,onOpenPlanning:S,onResumePlanning:j,activePlanningSessionCount:E=0,onOpenUsage:y,onRunScript:N,projectId:M,onViewAllProjects:D,showSkillsTab:C,experimentalFeatures:_,onOpenNodes:F,pluginDashboardViews:U=[],shellConnectionControl:A}){const $=oi(),[T,J]=i.useState(!1),[B,se]=i.useState(!1),[P,O]=i.useState({}),[I,w]=i.useState(!1),Y=i.useMemo(()=>Object.entries(P).sort(([$e],[he])=>$e.localeCompare(he)),[P]);i.useEffect(()=>{if(!B)return;let $e=!1;return w(!0),Gr(M).then(he=>{$e||O(he)}).catch(()=>{$e||O({})}).finally(()=>{$e||w(!1)}),()=>{$e=!0}},[B,M]);const re=i.useCallback(()=>J(!1),[]),le=i.useCallback($e=>{re(),$e?.()},[re]);if(i.useEffect(()=>{if(!T)return;const $e=he=>{he.key==="Escape"&&J(!1)};return document.addEventListener("keydown",$e),()=>document.removeEventListener("keydown",$e)},[T]),$!=="mobile"||a||r)return null;const ve=E>0&&j?j:S,de=U.some($e=>$e.pluginId==="fusion-plugin-roadmap"),Fe=!!_?.roadmap&&!de,X=!!C,L=!!_?.todoView,Q=Fe&&(!X||e==="roadmaps"),ne=X&&(!Fe||e!=="roadmaps"),H=X&&!ne,z=$e=>$e.pluginId==="fusion-plugin-dependency-graph"&&$e.view.viewId==="graph",W=U.filter($e=>$e.view.placement==="primary").sort(($e,he)=>($e.view.order??Number.MAX_SAFE_INTEGER)-(he.view.order??Number.MAX_SAFE_INTEGER)),we=U.find(z)??null,Oe=(we?[we,...W.filter($e=>!z($e))]:W).slice(0,1),Ve=new Set(Oe.map($e=>`${$e.pluginId}:${$e.view.viewId}`)),He=U.filter($e=>!Ve.has(`${$e.pluginId}:${$e.view.viewId}`)).sort(($e,he)=>($e.view.order??Number.MAX_SAFE_INTEGER)-(he.view.order??Number.MAX_SAFE_INTEGER)),Je=e==="documents"||e==="research"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||b&&L||e==="roadmaps"&&!Q||e==="skills"&&!ne||za(e)&&!Oe.some($e=>Fr($e.pluginId,$e.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(Gi,{}),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(zn,{}),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(As,{}),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.jsx(Di,{}),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.jsx(da,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:id(u)})]}),ne&&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(ds,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),Q&&t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="roadmaps"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-roadmaps",role:"tab","aria-selected":e==="roadmaps",onClick:()=>n("roadmaps"),children:[t.jsx(gd,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Roadmaps"})]}),Oe.map($e=>{const he=Fr($e.pluginId,$e.view.viewId),ue=fl($e.view.icon);return t.jsxs("button",{type:"button",className:`mobile-nav-tab${e===he?" mobile-nav-tab--active":""}`,"data-testid":`mobile-nav-tab-plugin-${$e.pluginId}-${$e.view.viewId}`,role:"tab","aria-selected":e===he,onClick:()=>n(he),children:[t.jsx(ue,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:$e.view.label})]},`${$e.pluginId}:${$e.view.viewId}`)}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${Je?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>J($e=>!$e),children:[t.jsx(ud,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),T&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:re}),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"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-mailbox",onClick:()=>le(d),children:[t.jsx(da,{}),t.jsx("span",{children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:id(u)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>le(l),children:[t.jsx(Gs,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>le(c),children:[t.jsx(qa,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>le(m),children:[t.jsx(Bs,{}),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:()=>le(g),children:[t.jsx(Li,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>se($e=>!$e),"aria-expanded":B,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(Un,{size:14,className:`mobile-more-chevron${B?" mobile-more-chevron--open":""}`})})]}),B&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:I?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(bt,{className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):Y.length>0?t.jsxs(t.Fragment,{children:[Y.map(([$e,he])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${$e}`,onClick:()=>{N&&N($e,he),re(),se(!1)},children:[t.jsx(ns,{}),t.jsx("span",{children:$e})]},$e)),p&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{re(),se(!1),p()},children:[t.jsx(ui,{}),t.jsx("span",{children:"Manage Scripts…"})]})]}):p&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":"mobile-more-scripts-manage",onClick:()=>{re(),se(!1),p()},children:[t.jsx(ui,{}),t.jsx("span",{children:"No scripts — add one…"})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>le(x),children:[t.jsx(ws,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>le(ve),children:[t.jsx(fi,{}),t.jsx("span",{children:"Planning"}),E>0&&t.jsx("span",{className:"mobile-more-item-badge",children:id(E)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>le(h),children:[t.jsx(dl,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>le(f),children:[t.jsx(Oi,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>le(k),children:[t.jsx(bD,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>le(y),children:[t.jsx(Gs,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>le(D),children:[t.jsx(Pl,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>le(()=>n("documents")),children:[t.jsx(Ki,{}),t.jsx("span",{children:"Documents"})]}),H&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>le(()=>n("skills")),children:[t.jsx(ds,{}),t.jsx("span",{children:"Skills"})]}),Fe&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-roadmaps",onClick:()=>le(()=>n("roadmaps")),children:[t.jsx(gd,{}),t.jsx("span",{children:"Roadmaps"})]}),_?.researchView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-research",onClick:()=>le(()=>n("research")),children:[t.jsx($i,{}),t.jsx("span",{children:"Research"})]}),_?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>le(()=>n("insights")),children:[t.jsx(ys,{}),t.jsx("span",{children:"Insights"})]}),_?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>le(()=>n("memory")),children:[t.jsx(qr,{}),t.jsx("span",{children:"Memory"})]}),_?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{le(()=>n("dev-server"))},children:[t.jsx(qa,{}),t.jsx("span",{children:"Dev Server"})]}),_?.nodesView&&F&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-nodes",onClick:()=>le(F),children:[t.jsx(jy,{}),t.jsx("span",{children:"Nodes"})]}),L&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>le(()=>v?.()),children:[t.jsx(ll,{}),t.jsx("span",{children:"Todos"})]}),He.map($e=>{const he=Fr($e.pluginId,$e.view.viewId),ue=fl($e.view.icon);return t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":`mobile-more-item-plugin-${$e.pluginId}-${$e.view.viewId}`,onClick:()=>le(()=>n(he)),children:[t.jsx(ue,{}),t.jsx("span",{children:$e.view.label})]},`${$e.pluginId}:${$e.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:()=>le(o),children:[t.jsx(Lr,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function vD({agents:e,filter:n,highlightedIndex:s,visible:a,onSelect:r,position:o="below"}){const l=i.useMemo(()=>{const c=n.trim().toLowerCase();return c?e.filter(d=>d.name.toLowerCase().includes(c)):e},[e,n]);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:l.length===0?t.jsx("div",{className:"agent-mention-empty",children:"No agents found"}):l.map((c,d)=>t.jsxs("button",{type:"button",className:`agent-mention-item${d===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${c.id}`,onMouseDown:u=>u.preventDefault(),onClick:()=>r(c),role:"option","aria-selected":d===s,children:[t.jsx(Hd,{agent:c,size:20}),t.jsx("span",{className:"agent-mention-name",children:c.name}),t.jsx("span",{className:"agent-mention-role",children:c.role})]},c.id))}):null}function yD(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,v=null;const b=()=>{x=null,a(h)},k=()=>{v=null,r(f)},S=()=>{x!==null&&(cancelAnimationFrame(x),x=null),v!==null&&(cancelAnimationFrame(v),v=null)};return l.current=S,{handlers:{onThinking:E=>{f+=E,v===null&&(v=requestAnimationFrame(k))},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 N=y.length-1;N>=0;N--){const M=y[N];if(M?.toolName===E.toolName&&M.status==="running"){y[N]={...M,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=>{S(),d({messageId:E.messageId,message:E.message,accumulated:{text:h,thinking:f,toolCalls:p,fallbackInfo:g}})},onError:E=>{S(),u(E,s)}},cancelFlushes:S}}const Fa="__fn_agent__";function ix(e,n){const s=typeof e=="string"?e.trim():"",a=typeof n=="string"?n.trim():"";return!s||!a?{}:{modelProvider:s,modelId:a}}function Xo(e,n,s){const a=typeof e=="string"?e.trim():"",r=ix(n,s),o=a||(r.modelProvider&&r.modelId?Fa:"");return o?{agentId:o,...r}:null}function Zo(e,n,s){const a=ix(n,s),r=a.modelProvider??"",o=a.modelId??"";return`${e}::${r}/${o}`}function wD(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 kD(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 jD(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 el(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:kD(e.metadata),fallbackInfo:jD(e.metadata),createdAt:e.createdAt}}function ND(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(""),[v,b]=i.useState(""),[k,S]=i.useState([]),[j,E]=i.useState(""),y=i.useRef(null),N=i.useRef(!1),M=i.useRef(null),D=i.useRef(""),C=i.useRef(f);C.current=f;const _=i.useRef(null),F=i.useRef(""),U=i.useRef(null),A=i.useRef(s);A.current=s;const $=i.useRef(0),T=3,J=i.useRef(!1);i.useEffect(()=>{D.current=j},[j]);const B=i.useCallback(async()=>{c(!0);try{const L=await rm(e);o(L.sessions)}catch(L){console.error("[useQuickChat] Failed to refresh sessions:",L)}finally{c(!1)}},[e]),se=i.useCallback(async L=>{const Q={agentId:L.agentId};return L.modelProvider&&L.modelId&&(Q.modelProvider=L.modelProvider,Q.modelId=L.modelId),(await O1(Q,e)).session},[e]),P=i.useCallback(async(L,Q,ne)=>{const H=Xo(L,Q,ne);if(!H)return;const z=Zo(H.agentId,H.modelProvider,H.modelId);c(!0);try{const{session:W}=await L1({agentId:H.agentId,modelProvider:H.modelProvider,modelId:H.modelId},e);if(W)a(W),F.current=z,W.isGenerating&&(p(!0),x(""));else{const we=await se(H);a(we),F.current=z}$.current=0}catch(W){console.error("[useQuickChat] Failed to initialize session:",W),$.current+=1,$.current<=T&&n?.("Failed to initialize chat","error")}finally{c(!1)}},[e,n,se]),O=i.useCallback(async()=>{if(s){h(!0);try{const L=await ic(s.id,{limit:50},e);u(L.messages.map(el))}catch(L){console.error("[useQuickChat] Failed to load messages:",L)}finally{h(!1)}}},[s,e]);i.useEffect(()=>{s?O():u([])},[s,O]),i.useEffect(()=>{if(!f||y.current||!s)return;const L=setInterval(async()=>{if(!C.current||y.current||!s){clearInterval(L);return}try{if(!(await F1(s.id,e)).session.isGenerating){clearInterval(L);const ne=await ic(s.id,{limit:50},e);u(ne.messages.map(el)),x(""),b(""),S([]),p(!1)}}catch{}},3e3);return()=>clearInterval(L)},[f,s,e]);const I=i.useCallback(async()=>{if(s){h(!0);try{const L=await ic(s.id,{limit:50},e);u(L.messages.map(el))}catch(L){console.error("[useQuickChat] Failed to reload messages:",L)}finally{h(!1)}}},[s,e]),w=i.useCallback(()=>{M.current?.(),M.current=null,D.current="",E(""),x(""),b(""),S([]),p(!1)},[]),Y=i.useCallback(async(L,Q,ne)=>{const H=Xo(L,Q,ne);if(!H)return;const z=Zo(H.agentId,H.modelProvider,H.modelId);U.current=H;const W=z===F.current&&A.current;if(W||(y.current&&(y.current.close(),y.current=null),w()),W){await I();return}a(null),u([]),F.current=z,await P(H.agentId,H.modelProvider,H.modelId)},[P,I,w]),re=i.useCallback(async L=>{const Q=Xo(L.agentId,L.modelProvider??void 0,L.modelId??void 0);Q&&(U.current=Q,F.current=Zo(Q.agentId,Q.modelProvider,Q.modelId),y.current&&(y.current.close(),y.current=null),w(),a(L))},[w]),le=i.useCallback(async(L,Q)=>{await Y(Fa,L,Q)},[Y]),ve=i.useCallback(async(L,Q,ne)=>{const z=Xo(L??"",Q,ne)??U.current;if(!z)return;U.current=z;const W=Zo(z.agentId,z.modelProvider,z.modelId);J.current=!0,$.current=0,y.current&&(y.current.close(),y.current=null),w(),u([]),a(null),c(!0);try{const we=await se(z);a(we),F.current=W;const Z=await rm(e);o(Z.sessions)}catch(we){console.error("[useQuickChat] Failed to start a fresh session:",we),n?.("Failed to start a new chat","error")}finally{J.current=!1,c(!1)}},[n,se,e,w]),de=i.useCallback(()=>{s&&(N.current=!0,M.current?.(),M.current=null,y.current?.close(),y.current=null,z1(s.id,e).catch(()=>{}),p(!1),x(""),b(""),S([]))},[s,e]),Fe=i.useCallback(()=>{D.current="",E("")},[]),X=i.useCallback((L,Q)=>{if(!s||!L.trim()&&(!Q||Q.length===0))return Promise.resolve();if(f)return Q&&Q.length>0?Promise.reject(new Error("Cannot send attachments while a response is streaming")):(D.current=L,E(L),Promise.resolve());const ne=new Promise((H,z)=>{_.current={resolve:H,reject:z},N.current=!1,y.current&&(y.current.close(),y.current=null);const W=`temp-${Date.now()}`,we={id:W,sessionId:s.id,role:"user",content:L,createdAt:new Date().toISOString()};u(fe=>[...fe,we]),x(""),b(""),S([]),p(!0);const{handlers:Z}=yD({sessionId:s.id,tempUserMessageId:W,setStreamingText:x,setStreamingThinking:b,setStreamingToolCalls:S,cancelStreamingFlushesRef:M,addToast:n,onFallbackSession:(fe,Oe)=>{const Ve=wD(fe.fallbackModel);o(He=>He.map(Je=>Je.id===Oe?{...Je,...Ve}:Je)),a(He=>He&&He.id===Oe?{...He,...Ve}:He)},onDone:({messageId:fe,message:Oe,accumulated:Ve})=>{const He=Oe?el(Oe):{id:fe||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:Ve.text,thinkingOutput:Ve.thinking||void 0,toolCalls:Ve.toolCalls.length>0?Ve.toolCalls:void 0,fallbackInfo:Ve.fallbackInfo,createdAt:new Date().toISOString()};u($e=>[...$e,He]),x(""),b(""),S([]),p(!1),y.current=null,_.current?.resolve(),_.current=null;const Je=D.current.trim();Je&&(D.current="",E(""),X(Je))},onError:fe=>{if(x(""),b(""),S([]),p(!1),y.current=null,console.error("[useQuickChat] Stream error:",fe),n?.(typeof fe=="string"&&fe.trim()?fe:"Failed to get response","error"),_.current?.reject(new Error(typeof fe=="string"?fe:"Failed to get response")),_.current=null,!N.current){const Oe=D.current.trim();Oe&&(D.current="",E(""),X(Oe))}I()}});y.current=U1(s.id,L,Z,Q,e)});return ne.catch(()=>{}),ne},[s,f,e,n,I]);return 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:v,streamingToolCalls:k,pendingMessage:j,sendMessage:X,stopStreaming:de,clearPendingMessage:Fe,switchSession:Y,selectSession:re,startModelChat:le,startFreshSession:ve,refreshSessions:B,loadMessages:O,reloadMessages:I,skipNextSessionInitRef:J}),[s,r,l,d,m,f,g,v,k,j,X,de,Fe,Y,re,le,ve,B,O,I])}function SD(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,v=n?.showSystemAgents??!1,b=await ba({...x,...p,includeEphemeral:p?.includeEphemeral??v},e),k=Array.from(new Map(b.map(S=>[S.id,S])).values());a(k)}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 tN(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 gi(`/api/events${p}`,{events:{"agent:created":g,"agent:updated":g,"agent:deleted":g,"agent:stateChanged":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||!MS(p));return{agents:s,activeAgents:f,stats:r,isLoading:l,loadAgents:d,loadStats:u,refreshAgents:m}}function CD({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=cS(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(Sf,{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 ED=200;function _D(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),v=i.useRef(null);i.useEffect(()=>()=>{x.current&&clearTimeout(x.current),v.current?.abort()},[]);const b=i.useCallback((y,N)=>{if(N<0||N>y.length){r(!1);return}const M=D=>/[a-zA-Z0-9/_.-]/.test(D);for(let D=N-1;D>=0;D--){if(y[D]==="#")if(D===0){const C=y.slice(D+1,N);d(D),l(C),g(0),r(!0);return}else{const C=y[D-1];if(/[\s,.;:!?'"()[\]{}]/.test(C)){const _=y.slice(D+1,N);d(D),l(_),g(0),r(!0);return}r(!1);return}if(!M(y[D])){r(!1);return}}r(!1)},[]),k=i.useCallback(()=>{r(!1),l(""),d(-1),m([]),g(0),f(!1)},[]),S=i.useCallback(async y=>{if(!y.trim()){m([]),f(!1);return}v.current?.abort(),v.current=new AbortController;try{f(!0);const N=await rj(y,s,n);m(N.files),g(0)}catch(N){N.name!=="AbortError"&&m([])}finally{f(!1)}},[s,n]);i.useEffect(()=>{if(a)return x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{S(o)},ED),()=>{x.current&&clearTimeout(x.current)}},[o,a,S]);const j=i.useCallback((y,N)=>{if(!a||c<0)return N;const M=N.slice(0,c),D=N.slice(c+1),C=D.match(/[\s]|$/),_=C?C.index:D.length,F=D.slice(_);return`${M}#${y.path}${F}`},[a,c]),E=i.useCallback((y,N)=>{if(!a||u.length===0)return!1;switch(y.key){case"ArrowDown":return y.preventDefault(),g(M=>Math.min(M+1,u.length-1)),!0;case"ArrowUp":return y.preventDefault(),g(M=>Math.max(M-1,0)),!0;case"Enter":case"Tab":return u[p]?(y.preventDefault(),!0):!1;case"Escape":return y.preventDefault(),k(),!0;default:return!1}},[a,u,p,k]);return{mentionActive:a,files:u,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:g,detectMention:b,selectFile:j,dismissMention:k,handleKeyDown:E}}function MD(e){return`${e.name?.trim()||e.id} (${e.role})`}function Er(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 AD(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 al(e,n){return e.length<=n?e:`${e.slice(0,n)}…`}function PD(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}=${al(r,50)}`}).join(", ")}function RD(e){if(e===void 0)return null;if(typeof e=="string")return al(e,200);try{return al(JSON.stringify(e),200)}catch{return al(String(e),200)}}function ax(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,v=PD(f.args),b=RD(f.result),k=g?v:b?`result: ${b}`:v?`args: ${v}`:null,S=n?null:k,j=g?"running":x?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${g?" chat-tool-call--running":""}${x?" chat-tool-call--error":""}`,open:g,children:[t.jsxs("summary",{children:[t.jsx("span",{className:"chat-tool-call-status-dot","aria-hidden":"true"}),t.jsx("span",{className:"chat-tool-call-name",title:f.toolName,children:f.toolName}),S&&t.jsx("span",{className:"chat-tool-call-preview",title:S,children:S}),t.jsx("span",{className:"chat-tool-call-status-text",children:j})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[v&&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:v})]}),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($u,{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($u,{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 rx={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 ef(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 TD(e,n){const s=e.slice(0,n),a=/(^|[\s])@([\w-]*)$/.exec(s);if(!a)return null;const r=a[2]??"",o=s.length-r.length-1;return{filter:r,start:o,end:n}}const tl={width:320,height:400},ID=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"]),$D=[".png",".jpg",".jpeg",".gif",".webp",".txt",".json",".yaml",".yml",".log",".csv",".xml",".md"];function DD(e){return e.type.startsWith("image/")}function LD(e){if(ID.has(e.type))return!0;const n=e.name.toLowerCase();return $D.some(s=>n.endsWith(s))}const $a={width:280,height:260},Ms=768,Da=8;function OD(e,n){const s=i.useCallback(()=>{if(typeof window>"u")return 0;const j=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return j&&parseFloat(j)||0},[]),a=i.useCallback(()=>typeof window<"u"&&window.innerWidth<=768?{x:4,y:4+s()}:{x:24,y:24+s()},[s]),[r,o]=i.useState(()=>{if(typeof window>"u")return a();const j=`fusion-quick-chat-position-${e||"default"}`;try{const E=localStorage.getItem(j);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(j=>{if(typeof window>"u")return j;const E=48,y=window.innerWidth<=768?4:8,N=window.innerWidth<=768?44:0,M=window.innerWidth>768?s():0,D=window.innerWidth-E-y,C=window.innerHeight-E-y-N-M;return{x:Math.max(y,Math.min(D,j.x)),y:Math.max(y,Math.min(C,j.y))}},[s]),g=i.useCallback(j=>{if(typeof window>"u")return;const E=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(E,JSON.stringify(j))}catch{}},[e]),x=i.useCallback(()=>{if(!d.current)return;const j=h.current,E=m.current;j&&E!==null&&typeof j.releasePointerCapture=="function"&&j.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",v),document.removeEventListener("pointerup",b),document.removeEventListener("pointercancel",k)},[g]),v=i.useCallback(j=>{if(!d.current||m.current!==null&&j.pointerId!==m.current)return;const E=j.clientX-d.current.pointerX,y=j.clientY-d.current.pointerY;if((Math.abs(E)>=5||Math.abs(y)>=5)&&(f.current=!0),!f.current)return;const N=d.current.x-E,M=d.current.y-y,D=p({x:N,y:M});u.current=D,o(D)},[p]),b=i.useCallback(j=>{m.current!==null&&j.pointerId!==m.current||x()},[x]),k=i.useCallback(j=>{m.current!==null&&j.pointerId!==m.current||x()},[x]),S=i.useCallback(j=>{if(j.button!==0&&j.pointerType==="mouse")return;const E=j.currentTarget;j.preventDefault(),typeof E.setPointerCapture=="function"&&E.setPointerCapture(j.pointerId);const y=u.current;d.current={x:y.x,y:y.y,pointerX:j.clientX,pointerY:j.clientY},m.current=j.pointerId,h.current=E,f.current=!1,c(!0),document.body.style.userSelect="none",document.addEventListener("pointermove",v,{passive:!0}),document.addEventListener("pointerup",b),document.addEventListener("pointercancel",k)},[k,v,b]);return i.useEffect(()=>()=>{document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b),document.removeEventListener("pointercancel",k),document.body.style.userSelect=""},[k,v,b]),{position:r,isDragging:l,handlePointerDown:S}}function FD(e,n,s){const a=`fusion:quick-chat-size-${e||"default"}`,r=i.useCallback(()=>typeof window<"u"&&window.innerWidth>Ms,[]),o=i.useCallback((f,p,g)=>{if(typeof window>"u")return f;const x=Math.max($a.width,window.innerWidth-p-Da),v=Math.max($a.height,window.innerHeight-g-Da);return{width:Math.max($a.width,Math.min(x,f.width)),height:Math.max($a.height,Math.min(v,f.height))}},[]),l=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=Ms)return tl;try{const f=localStorage.getItem(a);if(!f)return tl;const p=JSON.parse(f);return typeof p.width!="number"||typeof p.height!="number"?tl:{width:p.width,height:p.height}}catch{return tl}},[a]),[c,d]=i.useState(l),[u,m]=i.useState({right:0,bottom:0});i.useEffect(()=>{if(!r())return;const f={right:n+u.right,bottom:s+u.bottom};d(p=>o(p,f.right,f.bottom))},[o,r,n,s,u]),i.useEffect(()=>{if(r())try{localStorage.setItem(a,JSON.stringify(c))}catch{}},[r,c,a]);const h=i.useCallback(f=>{if(!r())return;const p=f.currentTarget.dataset.resizeDirection;if(!p)return;f.preventDefault(),f.stopPropagation();const g=f.currentTarget;typeof g.setPointerCapture=="function"&&g.setPointerCapture(f.pointerId);const x={pointerX:f.clientX,pointerY:f.clientY,width:c.width,height:c.height,anchorRight:u.right,anchorBottom:u.bottom};document.body.style.userSelect="none";const v=k=>{const S=k.clientX-x.pointerX,j=k.clientY-x.pointerY;let E=x.width,y=x.height,N=x.anchorRight,M=x.anchorBottom;if(p.includes("w")&&(E=x.width-S),p.includes("e")){const A=S;E=x.width+A,N=x.anchorRight-A}if(p.includes("n")&&(y=x.height-j),p.includes("s")){const A=j;y=x.height+A,M=x.anchorBottom-A}const D=n+N,C=s+M,_=o({width:E,height:y},D,C),F=Math.max(Da-n,Math.min(window.innerWidth-n-$a.width-Da,N)),U=Math.max(Da-s,Math.min(window.innerHeight-s-$a.height-Da,M));d(_),m({right:F,bottom:U})},b=k=>{typeof g.releasePointerCapture=="function"&&g.releasePointerCapture(k.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b);try{localStorage.setItem(a,JSON.stringify({width:c.width,height:c.height}))}catch{}};document.addEventListener("pointermove",v),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 tf=i.memo(function({message:n,forcePlain:s,mentionAgentsByName:a,onToggleRender:r}){const o=n.role==="user",l=i.useMemo(()=>{if(!o)return null;const d=n.content,u=/@([\w-]+)/g,m=[];let h=0,f=u.exec(d);for(;f;){const[p,g=""]=f,x=f.index;x>h&&m.push(d.slice(h,x));const v=g.replace(/_/g," ").toLowerCase(),b=a.get(v);b?m.push(t.jsxs("span",{className:"chat-mention-chip",children:["@",b.name.replace(/\s+/g,"_")]},`${b.id}-${x}`)):m.push(p),h=x+p.length,f=u.exec(d)}return h<d.length&&m.push(d.slice(h)),m.length===0?d:m},[o,n.content,a]),c=i.useMemo(()=>o?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(Ci,{remarkPlugins:[Ei],components:rx,children:n.content})}),[o,s,n.content]);return t.jsxs("div",{className:`quick-chat-panel-message ${o?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${n.id}`,children:[o?t.jsx("p",{children:l}):t.jsxs(t.Fragment,{children:[c,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:()=>r(n.id),children:s?t.jsx(Qd,{size:14}):t.jsx(sr,{size:14})})]}),ax(n.toolCalls,!0)]})});function zD({projectId:e,addToast:n,showFAB:s=!0,open:a,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:d}){const{agents:u}=SD(e),[m,h]=i.useState(!1),f=a!==void 0,p=f?a:m,g=f?ce=>{r?.(typeof ce=="function"?ce(p):ce)}:h;ya({enabled:p});const x=oi(),[v,b]=i.useState("agent"),[k,S]=i.useState(""),[j,E]=i.useState(!1),[y,N]=i.useState("model"),[M,D]=i.useState(""),[C,_]=i.useState(""),[F,U]=i.useState([]),[A,$]=i.useState(!1),[T,J]=i.useState(""),[B,se]=i.useState(""),[P,O]=i.useState(""),[I,w]=i.useState([]),[Y,re]=i.useState(!1),[le,ve]=i.useState(!1),[de,Fe]=i.useState(""),[X,L]=i.useState(0),[Q,ne]=i.useState(""),[H,z]=i.useState(!1),[W,we]=i.useState(0),[Z,fe]=i.useState(-1),[Oe,Ve]=i.useState(()=>new Set),[He,Je]=i.useState(!1),[$e,he]=i.useState([]),[ue,Ee]=i.useState(!1),[,je]=i.useState(!1),[xe,Pe]=i.useState({top:0,left:0}),ie=_D({projectId:e}),Me=i.useCallback(ce=>{if(!ce||!ie.mentionActive)return;const Ge=ce.getBoundingClientRect();Pe({top:Ge.top-260,left:Ge.left+8})},[ie.mentionActive]),We=i.useRef(!1),mt=i.useRef(!1),st=i.useRef(""),Ze=i.useRef(0),dt=i.useRef(null),Ae=i.useRef(null),Ue=i.useRef(0),{position:kt,isDragging:De,handlePointerDown:be}=OD(e,We),pe=kt.y+60,{panelSize:Re,anchorOffset:Be,handleResizeStart:at}=FD(e,kt.x,pe),me=typeof window<"u"&&window.innerWidth>Ms,{activeSession:ft,messages:Et,isStreaming:jt,streamingText:$t,streamingThinking:Ft,streamingToolCalls:Rt,sessions:It,sessionsLoading:Vt,messagesLoading:Qt,sendMessage:Jt,stopStreaming:on,pendingMessage:Kt,clearPendingMessage:qt,switchSession:kn,selectSession:nn,startModelChat:Xt,startFreshSession:Gt,refreshSessions:ln,skipNextSessionInitRef:ye}=ND(e,n),Le=i.useRef(null),ae=i.useRef(null),Te=i.useRef(null),Ne=i.useRef(null),ee=i.useRef(null),Ie=i.useRef([]),St=i.useRef(!1),pt=i.useRef(!1),Dt=i.useRef(!1),Ut=i.useRef(null),Ce=i.useRef(!1);i.useEffect(()=>{if(!p||typeof window>"u"||typeof document>"u"||window.innerWidth>Ms)return;const ce=window.scrollY,Ge=document.documentElement,lt=document.body,tn={htmlOverflow:Ge.style.overflow,bodyOverflow:lt.style.overflow};return window.scrollTo(0,0),Ge.style.overflow="hidden",lt.style.overflow="hidden",()=>{Ge.style.overflow=tn.htmlOverflow,lt.style.overflow=tn.bodyOverflow,window.scrollTo(0,ce)}},[p]),i.useLayoutEffect(()=>{if(!p||typeof window>"u"||!window.visualViewport)return;const ce=Le.current;if(!ce)return;const Ge=window.visualViewport,lt=()=>{Ce.current||(ce.style.setProperty("--vv-height",`${Ge.height}px`),ce.style.setProperty("--vv-offset-top",`${Ge.offsetTop||0}px`))};return lt(),Ge.addEventListener("resize",lt),Ge.addEventListener("scroll",lt),()=>{Ge.removeEventListener("resize",lt),Ge.removeEventListener("scroll",lt)}},[p]);const et=T||B,tt=i.useMemo(()=>Er(et),[et]),Lt=i.useMemo(()=>v==="model"&&ft?.modelProvider&&ft?.modelId?`${ft.modelProvider}/${ft.modelId}`:et,[ft?.modelId,ft?.modelProvider,v,et]),Zt=i.useMemo(()=>Er(Lt),[Lt]),sn=i.useMemo(()=>F.find(ce=>`${ce.provider}/${ce.id}`===Lt)??null,[Lt,F]),At=i.useMemo(()=>AD(sn,Zt),[sn,Zt]),cn=i.useMemo(()=>v==="model"?tt?`${Fa}::${tt.modelProvider}/${tt.modelId}`:"":k?`${k}::`:"",[v,k,tt]),En=!(v==="agent"?!!k:!!tt)||!ft;i.useEffect(()=>{if(u.length===0){S(""),b("model");return}u.some(Ge=>Ge.id===k)||S(u[0]?.id??"")},[u,k]),i.useEffect(()=>{!p||mt.current||(mt.current=!0,$(!0),Os().then(ce=>{const Ge=ce.models??[];if(U(Ge),T||Ge.length===0)return;const lt=ce.defaultProvider,tn=ce.defaultModelId;if(lt&&tn){const Se=`${lt}/${tn}`;if(Ge.some(Ct=>`${Ct.provider}/${Ct.id}`===Se)){se(Se),J(Se),b("model");return}}se("");const G=Ge[0];G&&J(`${G.provider}/${G.id}`)}).catch(ce=>{console.error("[QuickChatFAB] Failed to load models:",ce),U([]),se("")}).finally(()=>{$(!1)}))},[p,u.length,T]),i.useEffect(()=>{!p||!e||(re(!0),D1(e).then(ce=>{w(ce)}).catch(()=>{w([])}).finally(()=>{re(!1)}))},[p,e]),i.useEffect(()=>{p&&ln()},[p,ln]),i.useEffect(()=>{if(!p){st.current="";return}if(!cn){st.current="";return}if(ye.current){st.current=cn;return}const ce=cn===st.current&&!ft&&!Vt;if(!(cn===st.current&&!ce)){if(st.current=cn,v==="model"&&tt){Xt(tt.modelProvider,tt.modelId);return}v==="agent"&&k&&kn(k)}},[p,v,tt,k,cn,ft,Vt,Xt,kn,ye]),i.useEffect(()=>{p||(z(!1),ne(""),fe(-1),ve(!1),Fe(""),L(0),Ie.current.forEach(ce=>{ce.previewUrl&&URL.revokeObjectURL(ce.previewUrl)}),he([]))},[p]),i.useEffect(()=>{Ie.current=$e},[$e]),i.useEffect(()=>{if(!p){St.current=!1;return}typeof window>"u"||(St.current=window.innerWidth<=Ms)},[p]),i.useEffect(()=>{if(!p||En||!St.current)return;const ce=Ne.current;if(!ce)return;const Ge=document.activeElement,lt=Ge?Le.current?.contains(Ge):!1,tn=Ge===document.body,G=Ge===Ut.current;if(!lt&&!tn&&!G){St.current=!1;return}if(G){ce.focus({preventScroll:!0}),St.current=!1;return}const Se=requestAnimationFrame(()=>{ce.focus(),St.current=!1});return()=>cancelAnimationFrame(Se)},[p,En]),i.useEffect(()=>()=>{Ie.current.forEach(ce=>{ce.previewUrl&&URL.revokeObjectURL(ce.previewUrl)})},[]);const bn=i.useCallback(()=>{E(!0),N("model"),D(u[0]?.id??""),_(T||B||"")},[u,B,T]),In=i.useMemo(()=>u.find(ce=>ce.id===k)??null,[u,k]),ge=i.useMemo(()=>{const ce=de.trim().toLowerCase();return(ce?I.filter(lt=>lt.name.toLowerCase().includes(ce)):I).slice(0,10)},[I,de]),ut=i.useMemo(()=>{const ce=Q.trim().toLowerCase();return ce?u.filter(Ge=>Ge.name.toLowerCase().includes(ce)):u},[u,Q]),xn=i.useMemo(()=>{const ce=new Map;for(const Ge of u)ce.set(Ge.name.toLowerCase(),Ge);return ce},[u]);i.useEffect(()=>{L(0)},[ge]),i.useEffect(()=>{we(0)},[Q,H]),i.useEffect(()=>()=>{dt.current!==null&&(window.clearTimeout(dt.current),dt.current=null),Ae.current!==null&&(window.clearTimeout(Ae.current),Ae.current=null)},[]),i.useEffect(()=>{if(!p)return;const ce=lt=>{const tn=lt.target;Le.current?.contains(tn)||ae.current?.contains(tn)||tn.closest(".model-combobox-dropdown--portal")||g(!1)},Ge=lt=>{lt.key==="Escape"&&g(!1)};return document.addEventListener("mousedown",ce),document.addEventListener("keydown",Ge),()=>{document.removeEventListener("mousedown",ce),document.removeEventListener("keydown",Ge)}},[p,g]),i.useEffect(()=>{if(!p)return;const ce=Te.current;ce&&(ce.scrollTop=ce.scrollHeight)},[Et,$t,Ft,jt,p]);const oe=i.useMemo(()=>{const ce=new Map(u.map(lt=>[lt.id,lt.name?.trim()||lt.id])),Ge=new Map(F.map(lt=>[`${lt.provider}/${lt.id}`,lt.name?.trim()||""]));return It.map((lt,tn)=>{const G=lt.title?.trim()||`Session ${tn+1}`;let Se=null;if(lt.agentId&&lt.agentId!==Fa)Se=ce.get(lt.agentId)||lt.agentId;else if(lt.modelProvider&&lt.modelId){const it=`${lt.modelProvider}/${lt.modelId}`,Ct=Ge.get(it);Se=Ct?`${Ct} [${it}]`:it}return{id:lt.id,label:Se?`${G} — ${Se}`:G}})},[u,F,It]),ct=i.useMemo(()=>v==="agent"?In?`Message ${In.name||In.id}`:"Select an agent to start chatting":At?`Message ${At}`:"Select a model to start chatting",[v,In,At]),rt=i.useCallback(ce=>{const Ge=It.find(lt=>lt.id===ce);Ge&&(Ge.modelProvider&&Ge.modelId?(b("model"),J(`${Ge.modelProvider}/${Ge.modelId}`)):(b("agent"),S(Ge.agentId)),nn(Ge))},[nn,It]),wt=i.useCallback(async()=>{if(!Vt){if(y==="agent"){if(!M)return;b("agent"),S(M),await Gt(M)}else{const ce=Er(C||T||B);if(!ce)return;b("model"),J(`${ce.modelProvider}/${ce.modelId}`),await Gt(Fa,ce.modelProvider,ce.modelId)}await ln(),E(!1),N("model")}},[B,M,y,C,ln,T,Vt,Gt]),ot=Kt.length>50?`${Kt.slice(0,50)}…`:Kt,vt=i.useCallback(ce=>{if(!ce||ce.length===0)return;const Ge=[];for(let lt=0;lt<ce.length;lt+=1){const tn=ce[lt];LD(tn)&&Ge.push({file:tn,previewUrl:DD(tn)?URL.createObjectURL(tn):""})}Ge.length>0&&he(lt=>[...lt,...Ge])},[]),Wt=i.useCallback(ce=>{he(Ge=>{const lt=Ge[ce];return lt?.previewUrl&&URL.revokeObjectURL(lt.previewUrl),Ge.filter((tn,G)=>G!==ce)})},[]),an=i.useCallback(ce=>{vt(ce.clipboardData?.files)},[vt]),pn=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth>Ms)return;const ce=Ne.current;!ce||ce.disabled||ce.focus({preventScroll:!0})},[]),Hn=i.useCallback(()=>{typeof window>"u"||window.innerWidth>Ms||(Dt.current=!0)},[]),Mn=i.useCallback(async()=>{const ce=P.trim(),Ge=Ie.current;if(!(!ce&&Ge.length===0)&&!En){if(O(""),z(!1),ne(""),fe(-1),ce==="/help"){Je(!0),pn(),Dt.current=!1;return}if(ce==="/clear"){on(),qt(),Ge.forEach(lt=>{lt.previewUrl&&URL.revokeObjectURL(lt.previewUrl)}),he(lt=>lt.filter(tn=>!Ge.includes(tn)));try{if(v==="model"){const lt=Er(et);if(!lt)return;await Gt(Fa,lt.modelProvider,lt.modelId)}else k&&await Gt(k)}catch{n("Failed to clear conversation","error")}finally{pn(),Dt.current=!1}return}try{Je(!1),await Jt(ce,Ge.map(lt=>lt.file)),Ge.forEach(lt=>{lt.previewUrl&&URL.revokeObjectURL(lt.previewUrl)}),he(lt=>lt.filter(tn=>!Ge.includes(tn)))}catch{}finally{pn(),Dt.current=!1}}},[n,v,qt,pn,En,P,et,k,Jt,Gt,on]),Qn=i.useCallback(ce=>{ce.preventDefault(),Ue.current+=1,Ee(!0)},[]),ms=i.useCallback(ce=>{ce.preventDefault(),ce.dataTransfer.dropEffect="copy",Ee(!0)},[]),Xn=i.useCallback(ce=>{ce.preventDefault(),Ue.current=Math.max(0,Ue.current-1),Ue.current===0&&Ee(!1)},[]),mn=i.useCallback(ce=>{ce.preventDefault(),Ue.current=0,Ee(!1),vt(ce.dataTransfer?.files)},[vt]),Pt=i.useCallback((ce,Ge)=>{const lt=TD(ce,Ge);if(lt){z(!0),ne(lt.filter),fe(lt.start);return}z(!1),ne(""),fe(-1)},[]),is=i.useCallback(ce=>{O(Ge=>{const lt=ef(Ge);if(!lt)return Ge;const tn=`/skill:${ce.name} `,G=Ge.slice(0,lt.start)+tn+Ge.slice(lt.end);return window.requestAnimationFrame(()=>{Ne.current&&Ne.current.focus()}),G}),ve(!1),Fe(""),L(0)},[]),Gn=i.useCallback(ce=>{const Ge=Ne.current;if(!Ge||Z<0)return;const lt=Ge.selectionStart??Ze.current,tn=Ge.selectionEnd??lt,G=Math.max(lt,tn),Se=Math.min(Z,G),Ct=`${`@${ce.name.replace(/\s+/g,"_")}`} `,Tt=P.slice(0,Se)+Ct+P.slice(G),An=Se+Ct.length;O(Tt),z(!1),ne(""),we(0),fe(-1),window.requestAnimationFrame(()=>{Ne.current&&(Ne.current.focus(),Ne.current.setSelectionRange(An,An))})},[Z,P]),K=i.useCallback(ce=>{const Ge=ce.target.value,lt=ce.target.selectionStart??Ge.length;Ze.current=lt,O(Ge),He&&Ge.trim().length>0&&Je(!1),Pt(Ge,lt);const tn=ef(Ge);tn?(ve(!0),Fe(tn.filter)):(ve(!1),Fe("")),ie.detectMention(Ge,lt),je(ie.mentionActive),ie.mentionActive&&Me(ce.target)},[He,Pt,ie,Me]),Ke=i.useCallback(()=>{if(Dt.current){window.requestAnimationFrame(()=>{pn()});return}typeof window<"u"&&window.innerWidth<=Ms&&Le.current&&(Ce.current=!0,Le.current.style.removeProperty("--vv-height"),Le.current.style.removeProperty("--vv-offset-top"),window.setTimeout(()=>{Ce.current=!1},450)),dt.current!==null&&window.clearTimeout(dt.current),dt.current=window.setTimeout(()=>{z(!1),ne(""),fe(-1),je(!1),ie.dismissMention(),dt.current=null},120),Ae.current!==null&&window.clearTimeout(Ae.current),Ae.current=window.setTimeout(()=>{ve(!1),Ae.current=null},120)},[ie,pn]),Ye=i.useCallback(()=>{Ce.current=!1,dt.current!==null&&(window.clearTimeout(dt.current),dt.current=null),Ae.current!==null&&(window.clearTimeout(Ae.current),Ae.current=null)},[]),ht=i.useCallback(ce=>{const Ge=ce.currentTarget,lt=Ge.selectionStart??Ge.value.length;Ze.current=lt,Pt(Ge.value,lt),ie.detectMention(Ge.value,lt),je(ie.mentionActive),ie.mentionActive&&Me(Ge)},[Pt,ie,Me]),Nt=i.useCallback(ce=>{ce.key!=="Escape"&&ht(ce)},[ht]),_t=i.useCallback(ce=>{Ve(Ge=>{const lt=new Set(Ge);return lt.has(ce)?lt.delete(ce):lt.add(ce),lt})},[]),zt=i.useCallback((ce,Ge=!1)=>Ge?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:ce}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(Ci,{remarkPlugins:[Ei],components:rx,children:ce})}),[]),Jn=i.useCallback(ce=>{if(Ze.current=ce.currentTarget.selectionStart??Ze.current,ie.mentionActive&&ie.files.length>0){if(ie.handleKeyDown(ce,P),ce.key==="Enter"||ce.key==="Tab"){const Ge=ie.files[ie.selectedIndex];if(Ge){const lt=ie.selectFile(Ge,P);O(lt),ie.dismissMention(),je(!1)}}return}if(H&&ce.key==="ArrowDown"){ce.preventDefault(),ut.length>0&&we(Ge=>(Ge+1)%ut.length);return}if(H&&ce.key==="ArrowUp"){ce.preventDefault(),ut.length>0&&we(Ge=>Ge===0?ut.length-1:Ge-1);return}if(H&&ce.key==="Enter"){ce.preventDefault();const Ge=ut[W]??ut[0];Ge&&Gn(Ge);return}if(H&&ce.key==="Escape"){ce.preventDefault(),ce.stopPropagation(),z(!1),ne(""),fe(-1);return}if(le&&ge.length>0&&ce.key==="ArrowDown"){ce.preventDefault(),L(Ge=>(Ge+1)%ge.length);return}if(le&&ge.length>0&&ce.key==="ArrowUp"){ce.preventDefault(),L(Ge=>Ge===0?ge.length-1:Ge-1);return}if(le&&(ce.key==="Enter"||ce.key==="Tab")){ce.preventDefault();const Ge=ge[X]??ge[0];Ge&&is(Ge);return}if(le&&ce.key==="Escape"){ce.preventDefault(),ve(!1),Fe("");return}ce.key!=="Enter"||ce.shiftKey||(ce.preventDefault(),Mn())},[H,ut,W,Gn,Mn,ie,P,le,ge,X,is]),as=i.useCallback(()=>{if(We.current){We.current=!1;return}if(p){g(!1);return}typeof window<"u"&&window.innerWidth<=Ms&&Ut.current?.focus({preventScroll:!0}),g(!0)},[p,g]);return t.jsxs(t.Fragment,{children:[t.jsx("input",{ref:Ut,type:"text",className:"quick-chat-stealth-input","aria-hidden":"true",tabIndex:-1}),s&&t.jsx("button",{ref:ae,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":De?"true":"false",style:{right:kt.x,bottom:kt.y},onPointerDown:be,onClick:as,children:t.jsx(Di,{size:24})}),p&&t.jsxs("div",{className:"quick-chat-panel",ref:Le,"data-testid":"quick-chat-panel",style:{...me?{right:kt.x+Be.right,bottom:pe+Be.bottom,width:Re.width,height:Re.height}:{}},children:[me&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:at,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:at,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:at,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:at,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:at,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:at,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:at,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:at,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"}),v==="model"&&At&&(()=>{const ce=sn?.provider??Zt?.modelProvider??"";return x==="mobile"&&At.length>12&&ce?t.jsx("span",{className:"quick-chat-model-tag quick-chat-model-tag--icon","data-testid":"quick-chat-model-tag",title:At,"aria-label":At,children:t.jsx(Kn,{provider:ce,size:"sm"})}):t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:At,children:At})})()]}),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:bn,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:()=>g(!1),children:t.jsx(en,{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:ft?.id??"",onChange:ce=>rt(ce.target.value),"data-testid":"quick-chat-session-dropdown",children:[t.jsx("option",{value:"",disabled:!0,children:Vt?"Loading sessions…":"Select a session"}),oe.map(ce=>t.jsx("option",{value:ce.id,children:ce.label},ce.id))]})]}),j&&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${y==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-model",onClick:()=>N("model"),children:"Model"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${y==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-agent",onClick:()=>N("agent"),children:"Agent"})]}),y==="agent"?t.jsxs("div",{className:"quick-chat-panel-agent-select",children:[t.jsx("label",{htmlFor:"quick-chat-new-agent-select",className:"visually-hidden",children:"Select agent for new chat"}),t.jsx("select",{id:"quick-chat-new-agent-select",value:M,onChange:ce=>D(ce.target.value),"data-testid":"quick-chat-new-agent-select",children:u.map(ce=>t.jsx("option",{value:ce.id,children:MD(ce)},ce.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:F,value:C,onChange:_,label:"Select model override",placeholder:A?"Loading models…":"Select a model",disabled:A||F.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:()=>{E(!1),N("model")},children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary","data-testid":"quick-chat-new-session-submit",onClick:()=>void wt(),disabled:Vt||(y==="agent"?!M:!Er(C||T||B)),children:"Create"})]})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:Te,"data-testid":"quick-chat-messages",children:Vt?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):jt?t.jsxs(t.Fragment,{children:[Et.map(ce=>t.jsx(tf,{message:ce,forcePlain:ce.role!=="user"&&Oe.has(ce.id),mentionAgentsByName:xn,onToggleRender:_t},ce.id)),He&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:zt("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:[$t?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:zt($t,Oe.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${Oe.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":Oe.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>_t("__streaming__"),children:Oe.has("__streaming__")?t.jsx(Qd,{size:14}):t.jsx(sr,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:Ft?"Thinking…":"Connecting…"}),ax(Rt,!0),Ft&&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:Ft})]})]})]}):Qt?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):Et.length===0&&!$t&&!Ft&&!jt&&!He?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[Et.map(ce=>t.jsx(tf,{message:ce,forcePlain:ce.role!=="user"&&Oe.has(ce.id),mentionAgentsByName:xn,onToggleRender:_t},ce.id)),He&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:zt("Available commands:\n- `/clear` — Clear conversation and start fresh\n- `/skill:{name}` — Use a specific skill\n- `/help` — Show this help")})]})}),$e.length>0&&t.jsx("div",{className:"quick-chat-attachment-previews","data-testid":"quick-chat-attachment-previews",children:$e.map((ce,Ge)=>t.jsxs("div",{className:"quick-chat-attachment-preview","data-testid":`quick-chat-attachment-preview-${Ge}`,children:[ce.previewUrl?t.jsx("img",{src:ce.previewUrl,alt:ce.file.name}):t.jsx("span",{className:"quick-chat-attachment-preview-name",children:ce.file.name}),t.jsx("button",{type:"button",className:"quick-chat-attachment-remove","data-testid":`quick-chat-attachment-remove-${Ge}`,"aria-label":`Remove ${ce.file.name}`,onClick:()=>Wt(Ge),children:"×"})]},`${ce.file.name}-${Ge}`))}),t.jsx("div",{className:"quick-chat-panel-input",children:t.jsxs("div",{className:`quick-chat-input-wrapper${ue?" quick-chat-input-wrapper--dragover":""}`,onDragEnter:Qn,onDragOver:ms,onDragLeave:Xn,onDrop:mn,children:[t.jsx("input",{ref:ee,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:ce=>{vt(ce.target.files),ce.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:()=>ee.current?.click(),children:t.jsx(_f,{size:16})}),t.jsx("input",{ref:Ne,type:"text",value:P,onChange:K,onKeyDown:Jn,onKeyUp:Nt,onClick:ht,onBlur:Ke,onFocus:Ye,onPaste:an,onTouchStart:ce=>{typeof window>"u"||window.innerWidth>Ms||document.activeElement!==ce.currentTarget&&(ce.preventDefault(),ce.currentTarget.focus({preventScroll:!0}))},placeholder:ct,disabled:En,"data-testid":"quick-chat-input"}),jt?t.jsx("button",{type:"button",className:"chat-input-stop quick-chat-send-btn",onPointerDown:ce=>{typeof window>"u"||window.innerWidth>Ms||(ce.preventDefault(),ce.pointerType&&ce.pointerType!=="mouse"&&(pt.current=!0,on()))},onTouchStart:ce=>{typeof window>"u"||window.innerWidth>Ms||(ce.preventDefault(),pt.current=!0,on())},onMouseDown:ce=>{typeof window>"u"||window.innerWidth>Ms||ce.preventDefault()},onClick:()=>{if(pt.current){pt.current=!1;return}on()},"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(si,{size:14})}):t.jsx("button",{type:"button",className:"quick-chat-send-btn",onPointerDown:ce=>{typeof window>"u"||window.innerWidth>Ms||(ce.preventDefault(),ce.pointerType&&ce.pointerType!=="mouse"&&(pt.current=!0,Hn(),pn(),Mn()))},onTouchStart:ce=>{typeof window>"u"||window.innerWidth>Ms||(ce.preventDefault(),pt.current=!0,Hn(),pn(),Mn())},onMouseDown:ce=>{typeof window>"u"||window.innerWidth>Ms||ce.preventDefault()},onClick:()=>{if(pt.current){pt.current=!1;return}Mn()},disabled:En||P.trim().length===0&&$e.length===0,"data-testid":"quick-chat-send",children:t.jsx(ra,{size:16})})]}),t.jsx(vD,{agents:u,filter:Q,highlightedIndex:W,visible:H,onSelect:Gn,position:"above"}),t.jsx(CD,{visible:ie.mentionActive&&!H,position:xe,files:ie.files,selectedIndex:ie.selectedIndex,onSelect:ce=>{const Ge=ie.selectFile(ce,P);O(Ge),ie.dismissMention(),je(!1),Ne.current?.focus()},loading:ie.loading}),le&&t.jsx("div",{className:"chat-skill-menu","data-testid":"quick-chat-skill-menu",role:"listbox","aria-label":"Skill suggestions",children:Y?t.jsx("div",{className:"chat-skill-menu-empty",children:"Loading skills…"}):ge.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:de?"No skills found":"No skills available"}):ge.map((ce,Ge)=>t.jsxs("button",{type:"button",role:"option","aria-selected":Ge===X,className:`chat-skill-menu-item${Ge===X?" chat-skill-menu-item--highlighted":""}`,onMouseDown:lt=>lt.preventDefault(),onMouseEnter:()=>L(Ge),onClick:()=>is(ce),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:ce.name}),t.jsx("span",{className:"chat-skill-menu-item-description",title:ce.relativePath,children:ce.relativePath})]},ce.id))}),Kt&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${ot}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:qt,children:"×"})]})]})})]})]})}function _r(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function nf(e){return e.status==="generating"||e.status==="awaiting_input"}function Mr(e){return e==="complete"||e==="error"}function UD(e){const[n,s]=i.useState([]),a=i.useRef(new Map),r=i.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:d}=lr(),u=i.useCallback(()=>{nu(e).then(p=>{const g=p.filter(v=>{const b=_r(v.updatedAt),k=r.current.get(v.id);return k===void 0?!0:b<=k?!1:(r.current.delete(v.id),!0)}),x=new Map;for(const v of g)x.set(v.id,_r(v.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(v=>[v.id,v]));for(const v of o.values()){if(e&&v.projectId&&v.projectId!==e)continue;const b=v.lastEventTimestamp,k=a.current.get(v.sessionId)??0;if(b<k)continue;const S=r.current.get(v.sessionId);if(S!==void 0&&b<=S)continue;if(S!==void 0&&b>S&&!Mr(v.status)&&r.current.delete(v.sessionId),Mr(v.status)){x.delete(v.sessionId)&&(g=!0),a.current.set(v.sessionId,b);continue}const j=x.get(v.sessionId),E=v.type??j?.type,y=v.title??j?.title;if(!j&&(!E||!y))continue;const N={id:v.sessionId,type:E??"planning",status:v.status,title:y??"AI Session",projectId:v.projectId??j?.projectId??e??null,lockedByTab:v.owningTabId??j?.lockedByTab??null,updatedAt:v.updatedAt??j?.updatedAt??new Date(b).toISOString()},M=x.get(v.sessionId);(!M||M.status!==N.status||M.title!==N.title||M.type!==N.type||M.projectId!==N.projectId||M.lockedByTab!==N.lockedByTab||M.updatedAt!==N.updatedAt)&&(x.set(v.sessionId,N),a.current.set(v.sessionId,b),g=!0)}return g?[...x.values()].sort((v,b)=>_r(b.updatedAt)-_r(v.updatedAt)):p})},[e,o]),i.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",g=v=>{try{const b=JSON.parse(v.data),k=_r(b.updatedAt)||Date.now();s(S=>{const j=a.current.get(b.id)??0;if(k<j)return S;const E=r.current.get(b.id);if(E!==void 0&&k<=E)return S;if(E!==void 0&&k>E&&!Mr(b.status)&&r.current.delete(b.id),a.current.set(b.id,k),Mr(b.status))return S.filter(N=>N.id!==b.id);const y=S.findIndex(N=>N.id===b.id);if(y>=0){const N=[...S];return N[y]=b,N}return nf(b)?[b,...S]:S}),l({sessionId:b.id,status:b.status,needsInput:b.status==="awaiting_input",type:b.type,title:b.title,projectId:b.projectId,owningTabId:b.lockedByTab,updatedAt:b.updatedAt,timestamp:k}),Mr(b.status)&&c({sessionId:b.id,status:b.status,timestamp:k})}catch{}},x=v=>{try{const b=JSON.parse(v.data),k=Date.now();r.current.set(b,k),a.current.set(b,Math.max(a.current.get(b)??0,k)),c({sessionId:b,status:"complete",timestamp:k}),s(S=>S.filter(j=>j.id!==b))}catch{}};return gi(`/api/events${p}`,{events:{"ai_session:updated":g,"ai_session:deleted":x},onReconnect:()=>{u()}})},[c,l,e,u]);const m=i.useCallback(async p=>{const x=n.find(S=>S.id===p)?.type,v=va();let b=!1;if(x==="planning")try{await Lf(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of planning session ${p} despite lock by another tab`)}else if(x==="subtask")try{await zf(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of subtask session ${p} despite lock by another tab`)}else if(x==="mission_interview")try{await qf(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of mission interview session ${p} despite lock by another tab`)}b&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${p}, attempting delete anyway`);const k=Date.now();r.current.set(p,k),a.current.set(p,Math.max(a.current.get(p)??0,k)),c({sessionId:p,status:"complete",timestamp:k});try{await Vf(p)}catch{}s(S=>S.filter(j=>j.id!==p))},[c,e,n]),h=i.useMemo(()=>n.filter(p=>nf(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 El="fusion:hide-session-banners",Gd="fusion:session-banner-pref-changed";function BD(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(El)==="1"}catch{return!1}}function HD(e){if(typeof window>"u")return()=>{};const n=a=>{a.key===El&&e()},s=()=>e();return window.addEventListener("storage",n),window.addEventListener(Gd,s),()=>{window.removeEventListener("storage",n),window.removeEventListener(Gd,s)}}function nz(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(El,"1"):window.localStorage.removeItem(El),window.dispatchEvent(new Event(Gd))}catch{}}function qD(){return i.useSyncExternalStore(HD,BD,()=>!1)}function js(e){return{...e,dependencies:Array.isArray(e.dependencies)?e.dependencies:[],steps:Array.isArray(e.steps)?e.steps:[],log:Array.isArray(e.log)?e.log:[]}}function sf(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function VD(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 ad(e,n){if(sf(n.updatedAt,e.updatedAt)<0)return e;if(e.column===n.column)return VD(e,n);const a=sf(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 WD(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),v=i.useRef(n);u.current=r,f.current=s,v.current!==n&&(v.current=n,x.current++);const b=1e3,k=i.useCallback(async B=>{const se=++m.current,P=n,O=B?.searchQueryOverride??f.current,I=B?.includeArchivedOverride??d.current;try{const w=await Dw(void 0,void 0,P,O,I);if(m.current!==se||n!==P)return;o(w.map(js)),g.current=Date.now()}catch{if(m.current!==se||n!==P)return;if(B?.clearOnError){o([]);return}o(w=>w)}},[n]);p.current=k;const S=i.useCallback(async()=>{d.current||(c(!0),d.current=!0,await p.current({includeArchivedOverride:!0}))},[]),j=i.useRef(s);i.useEffect(()=>{if(s===void 0&&j.current===void 0)return;j.current=s;const B=setTimeout(()=>{k({searchQueryOverride:s})},300);return()=>clearTimeout(B)},[s]),i.useEffect(()=>{k({clearOnError:!0});const B=()=>{if(document.visibilityState!=="visible")return;const se=Date.now();se-h.current<b||(h.current=se,k())};return document.addEventListener("visibilitychange",B),()=>{document.removeEventListener("visibilitychange",B)}},[k]),i.useEffect(()=>{if(a===!1)return;const B=x.current,se=n?`?projectId=${encodeURIComponent(n)}`:"",P=()=>x.current!==B;let O=!0;const I=de=>{if(P())return;const Fe=js(JSON.parse(de.data));if(f.current){p.current({searchQueryOverride:f.current});return}o(X=>{const L=X.findIndex(z=>z.id===Fe.id);if(L===-1)return[...X,Fe];const Q=X[L],ne=ad(Q,Fe);if(ne===Q)return X;const H=[...X];return H[L]=ne,H}),g.current=Date.now()},w=de=>{if(P())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:Fe,to:X}=JSON.parse(de.data),L=js(Fe);o(Q=>Q.map(ne=>ne.id===L.id?{...L,column:X}:ne)),g.current=Date.now()},Y=de=>{if(P())return;if(f.current){p.current({searchQueryOverride:f.current});return}const Fe=js(JSON.parse(de.data));o(X=>X.map(L=>L.id!==Fe.id?L:ad(L,Fe))),g.current=Date.now()},re=de=>{if(P())return;if(f.current){p.current({searchQueryOverride:f.current});return}const Fe=js(JSON.parse(de.data));o(X=>X.filter(L=>L.id!==Fe.id))},le=de=>{if(P())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:Fe}=JSON.parse(de.data),X=js(Fe);o(L=>L.map(Q=>Q.id===X.id?{...X,column:"done"}:Q))},ve=gi(`/api/events${se}`,{events:{"task:created":I,"task:moved":w,"task:updated":Y,"task:deleted":re,"task:merged":le},onReconnect:()=>{O&&(P()||p.current())}});return()=>{O=!1,ve()}},[n,a]);const E=i.useCallback(async B=>{const se=js(await ml(B,n));return o(P=>P.some(O=>O.id===se.id)?P:[...P,se]),se},[n]),y=i.useCallback(async(B,se,P)=>js(await Ow(B,se,n,P)),[n]),N=i.useCallback(async B=>js(await If(B,n)),[n]),M=i.useCallback(async(B,se)=>js(await Fw(B,n,se)),[n]),D=i.useCallback(async B=>zw(B,n),[n]),C=i.useCallback(async B=>js(await Uw(B,n)),[n]),_=i.useCallback(async B=>js(await Bw(B,n)),[n]),F=i.useCallback(async B=>{const se=js(await Hw(B,n));return o(P=>P.some(O=>O.id===se.id)?P:[...P,se]),se},[n]),U=i.useCallback(async(B,se)=>{const P=u.current.find(I=>I.id===B),O=P?{...P,...se,updatedAt:new Date().toISOString()}:void 0;O&&o(I=>I.map(w=>w.id===B?O:w));try{const I=js(await ki(B,se,n));return o(w=>w.map(Y=>Y.id===B?I:Y)),I}catch(I){throw P&&o(w=>w.map(Y=>Y.id===B?P:Y)),I}},[n]),A=i.useCallback(async B=>{const se=js(await Vw(B,n));return o(P=>P.map(O=>O.id===B?se:O)),se},[n]),$=i.useCallback(async B=>{const se=js(await Ww(B,n));return o(P=>P.map(O=>O.id===B?se:O)),se},[n]),T=i.useCallback(async()=>{const se=(await Kw(n)).map(js);return o(P=>P.map(O=>se.find(w=>w.id===O.id)||O)),se},[n]),J=i.useCallback(B=>{if(B.length===0)return;if(f.current){p.current({searchQueryOverride:f.current});return}const se=B.map(js);o(P=>{let O=P;for(const I of se){const w=O.findIndex(le=>le.id===I.id);if(w===-1){O===P&&(O=[...P]),O.push(I);continue}const Y=O[w],re=ad(Y,I);re!==Y&&(O===P&&(O=[...P]),O[w]=re)}return O}),g.current=Date.now()},[]);return{tasks:r,createTask:E,moveTask:y,pauseTask:N,deleteTask:M,mergeTask:D,retryTask:C,resetTask:_,duplicateTask:F,updateTask:U,archiveTask:A,unarchiveTask:$,archiveAllDone:T,loadArchivedTasks:S,includeArchived:l,ingestCreatedTasks:J,lastFetchTimeMs:g.current}}const KD=5e3,GD=1e3;function JD(){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 tm();n(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 v=await tm(),k=`initial fetchProjectsAcrossNodes took ${Math.round(performance.now()-x)}ms (${v.length} projects)`;console.log(`[useProjects] ${k}`),Or("[useProjects]",k),f||(n(v),o(null))}catch(v){const k=`initial fetch failed after ${Math.round(performance.now()-x)}ms: ${v instanceof Error?v.message:String(v)}`;console.warn(`[useProjects] ${k}`),Or("[useProjects]",k),f||o(v instanceof Error?v.message:"Failed to fetch projects")}finally{f||a(!1)}}p();const g=()=>{if(document.visibilityState!=="visible")return;const x=Date.now();x-c.current<GD||(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()},KD),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,d]);const u=i.useCallback(async f=>{const p=await cN(f);return n(g=>[...g,p]),p},[]),m=i.useCallback(async(f,p)=>{const g=await fN(f,p);return n(x=>x.map(v=>v.id===f?g:v)),g},[]),h=i.useCallback(async f=>{await Uf(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 YD="kb-dashboard-current-project";function QD(e){return e??"local"}function XD(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=QD(s);i.useEffect(()=>{let p=!1;async function g(){try{const x=await ga();if(p)return;u.current=x.dashboardCurrentProjectIdByNode??{};const v=u.current[m];if(v){const b=e.find(k=>k.id===v);b&&(r(b),c.current=!0)}if(!v)try{const b=localStorage.getItem(YD);if(b){const k=JSON.parse(b);k?.id&&e.some(j=>j.id===k.id)&&(r(k),c.current=!0,u.current={...u.current,[m]:k.id},await Dn({dashboardCurrentProjectIdByNode:u.current}).catch(()=>{}))}}catch{}}catch{}finally{p||l(!1)}}return g(),()=>{p=!0}},[m,e]),i.useEffect(()=>{if(!o){if(a){if(!e.some(x=>x.id===a.id)&&e.length>0){const x=e.find(v=>v.status==="active");r(x||e[0]||null);return}const g={...u.current,[m]:a.id};u.current=g,Dn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}else if(e.length>0&&!d.current){const p=e.find(g=>g.status==="active");p&&r(p)}}},[a,e,o,m]);const h=i.useCallback(p=>{if(d.current=!1,r(p),p){const g={...u.current,[m]:p.id};u.current=g,Dn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}},[m]),f=i.useCallback(()=>{d.current=!0,r(null);const p={...u.current};delete p[m],u.current=p,Dn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:a,setCurrentProject:h,clearCurrentProject:f,loading:o}}const ox=i.createContext(null);function ZD({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()},[]),rl.createElement(ox.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function eL(){const e=i.useContext(ox);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const lx="kb-dashboard-theme-mode",cx="kb-dashboard-color-theme",dx="kb-dashboard-font-scale-pct",Jd=100,tL=85,nL=125,ux=[...ES],Yd="theme-data",rd="theme-data.css";function sL(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.endsWith("/")?e.slice(0,-1)+`/${rd}`:e.replace(/\/[^/]+$/,`/${rd}`):`/${rd}`}const Us=typeof window<"u",iL=Us?i.useLayoutEffect:i.useEffect;function mx(e){return e==="dark"||e==="light"||e==="system"}function af(){if(!Us)return"dark";try{const e=localStorage.getItem(lx);if(mx(e))return e}catch{}return"dark"}function rf(){if(!Us)return"default";try{const e=localStorage.getItem(cx);if(e&&ux.includes(e))return e}catch{}return"default"}function of(e){if(Us)try{localStorage.setItem(lx,e)}catch{}}function lf(e){if(Us)try{localStorage.setItem(cx,e)}catch{}}function Xr(e){return typeof e!="number"||!Number.isFinite(e)?Jd:Math.min(nL,Math.max(tL,Math.round(e)))}function cf(){if(!Us)return Jd;try{const e=Number(localStorage.getItem(dx));return Xr(e)}catch{return Jd}}function df(e){if(Us)try{localStorage.setItem(dx,String(Xr(e)))}catch{}}function aL(e,n){return e==="system"?n?"dark":"light":e}function rL(e,n,s,a){if(!Us)return;const r=aL(e,a);document.documentElement.setAttribute("data-theme",r),document.documentElement.setAttribute("data-color-theme",n),document.documentElement.style.fontSize=`${Xr(s)}%`}function uf(){if(!Us)return;const e=sL(),n=document.getElementById(Yd);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=Yd,document.head.appendChild(s)}function mf(){if(!Us)return;const e=document.getElementById(Yd);e&&e.remove()}function oL(){const[e,n]=i.useState(()=>af()),[s,a]=i.useState(()=>rf()),[r,o]=i.useState(()=>cf()),[l,c]=i.useState(!0),[d,u]=i.useState(()=>Us?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(!Us||!l)return;let S=!1;return ga().then(j=>{if(!S&&(mx(j.themeMode)&&!p.current&&(m.current!==j.themeMode&&(m.current=j.themeMode,n(j.themeMode)),af()!==j.themeMode&&of(j.themeMode)),j.colorTheme&&ux.includes(j.colorTheme)&&!g.current&&(h.current!==j.colorTheme&&(h.current=j.colorTheme,a(j.colorTheme)),rf()!==j.colorTheme&&lf(j.colorTheme)),!x.current)){const E=Xr(j.dashboardFontScalePct);f.current!==E&&(f.current=E,o(E)),cf()!==E&&df(E)}}).catch(j=>{console.warn("[useTheme] Failed to hydrate theme from global settings",j)}).finally(()=>{S||c(!1)}),()=>{S=!0}},[l]),i.useEffect(()=>{if(!Us)return;const S=window.matchMedia("(prefers-color-scheme: dark)"),j=E=>{u(E.matches)};return S.addEventListener("change",j),()=>S.removeEventListener("change",j)},[]),iL(()=>{rL(e,s,r,d)},[e,s,r,d]),i.useEffect(()=>{!Us||l||(s!=="default"?uf():mf())},[s,l]);const v=i.useCallback(S=>{p.current=!0,m.current=S,n(S),of(S),Dn({themeMode:S}).catch(j=>{console.warn("[useTheme] Failed to persist themeMode to global settings",j)})},[]),b=i.useCallback(S=>{g.current=!0,h.current=S,a(S),lf(S),S!=="default"?uf():mf(),Dn({colorTheme:S}).catch(j=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",j)})},[]),k=i.useCallback(S=>{const j=Xr(S);x.current=!0,f.current=j,o(j),df(j),Dn({dashboardFontScalePct:j}).catch(E=>{console.warn("[useTheme] Failed to persist dashboardFontScalePct to global settings",E)})},[]);return{themeMode:e,colorTheme:s,dashboardFontScalePct:r,setThemeMode:v,setColorTheme:b,setDashboardFontScalePct:k,isSystemDark:d}}function lL(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),[v,b]=i.useState(null),[k,S]=i.useState("definition"),[j,E]=i.useState(null),[y,N]=i.useState(!1),[M,D]=i.useState(void 0),[C,_]=i.useState(!1),[F,U]=i.useState(!1),[A,$]=i.useState(!1),[T,J]=i.useState(null),[B,se]=i.useState(!1),[P,O]=i.useState(!1),[I,w]=i.useState(void 0),[Y,re]=i.useState(!1),[le,ve]=i.useState(!1),[de,Fe]=i.useState("project"),[X,L]=i.useState(!1),[Q,ne]=i.useState(!1),[H,z]=i.useState(!1),[W,we]=i.useState(!1),[Z,fe]=i.useState(!1),[Oe,Ve]=i.useState(!1),[He,Je]=i.useState(!1),$e=!!(v||y||s||r||m||P||Y||le||X||Q||H||Z||W||A||B||C||F||Oe||He),he=i.useCallback(()=>a(!0),[]),ue=i.useCallback(()=>a(!1),[]),Ee=i.useCallback(()=>o(!0),[]),je=i.useCallback(pt=>{c(pt),o(!0)},[]),xe=i.useCallback(()=>{const pt=n[0];pt&&(u(pt.id),o(!0))},[n]),Pe=i.useCallback(pt=>{u(pt),o(!0)},[]),ie=i.useCallback(()=>{o(!1),c(null),u(void 0)},[]),Me=i.useCallback(pt=>{p(pt),h(!0)},[]),We=i.useCallback(pt=>{x(pt),h(!0)},[]),mt=i.useCallback(()=>{h(!1),p(null),x(void 0)},[]),st=i.useCallback((pt,Dt="definition",Ut)=>{b(pt),S(Dt),E(Ut?.origin??null)},[]),Ze=i.useCallback(pt=>{b(pt),S("changes"),E(null)},[]),dt=i.useCallback(pt=>{b(Dt=>Dt&&{...Dt,...pt})},[]),Ae=i.useCallback(()=>{b(null),E(null)},[]),Ue=i.useCallback(pt=>{D(pt),N(!0)},[]),kt=i.useCallback(()=>{N(!1),D(void 0)},[]),De=i.useCallback(()=>_(!0),[]),be=i.useCallback(()=>_(!1),[]),pe=i.useCallback(()=>U(!0),[]),Re=i.useCallback(()=>U(!1),[]),Be=i.useCallback(pt=>{J(pt??null),$(!0)},[]),at=i.useCallback(()=>{$(!1),J(null)},[]),me=i.useCallback(()=>se(!0),[]),ft=i.useCallback(()=>se(!1),[]),Et=i.useCallback(()=>{O(pt=>!pt)},[]),jt=i.useCallback(()=>{O(!1),w(void 0)},[]),$t=i.useCallback(()=>re(!0),[]),Ft=i.useCallback(()=>re(!1),[]),Rt=i.useCallback(()=>ve(!0),[]),It=i.useCallback(()=>ve(!1),[]),Vt=i.useCallback(pt=>{Fe(pt)},[]),Qt=i.useCallback(()=>L(!0),[]),Jt=i.useCallback(()=>L(!1),[]),on=i.useCallback(()=>ne(!0),[]),Kt=i.useCallback(()=>ne(!1),[]),qt=i.useCallback(()=>z(!0),[]),kn=i.useCallback(()=>z(!1),[]),nn=i.useCallback(()=>we(!0),[]),Xt=i.useCallback(()=>we(!1),[]),Gt=i.useCallback(()=>fe(!0),[]),ln=i.useCallback(()=>fe(!1),[]),ye=i.useCallback(async(pt,Dt)=>{fe(!1),w(Dt),O(!0)},[]),Le=i.useCallback(()=>Ve(!0),[]),ae=i.useCallback(()=>Ve(!1),[]),Te=i.useCallback(()=>Je(!0),[]),Ne=i.useCallback(()=>Je(!1),[]),ee=i.useCallback((pt,Dt)=>{Dt(`Created ${pt.id} from planning mode`,"success"),o(!1),c(null)},[]),Ie=i.useCallback((pt,Dt)=>{const Ut=pt.map(Ce=>Ce.id).join(", ");Dt(`Created ${Ut} from planning mode`,"success"),o(!1),c(null)},[]),St=i.useCallback((pt,Dt)=>{const Ut=pt.map(Ce=>Ce.id).join(", ");Dt(`Created ${Ut} from subtask breakdown`,"success"),h(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:l,planningResumeSessionId:d,isSubtaskOpen:m,subtaskInitialDescription:f,subtaskResumeSessionId:g,detailTask:v,detailTaskInitialTab:k,detailTaskOrigin:j,settingsOpen:y,settingsInitialSection:M,schedulesOpen:C,githubImportOpen:F,usageOpen:A,usageAnchorRect:T,systemStatsOpen:B,terminalOpen:P,terminalInitialCommand:I,filesOpen:Y,todosOpen:le,fileBrowserWorkspace:de,activityLogOpen:X,gitManagerOpen:Q,workflowStepsOpen:H,agentsOpen:W,scriptsOpen:Z,setupWizardOpen:Oe,modelOnboardingOpen:He,anyModalOpen:$e,openNewTask:he,closeNewTask:ue,openPlanning:Ee,openPlanningWithInitialPlan:je,resumePlanning:xe,openPlanningWithSession:Pe,closePlanning:ie,openSubtaskBreakdown:Me,openSubtaskWithSession:We,closeSubtask:mt,openDetailTask:st,openDetailWithChangesTab:Ze,updateDetailTask:dt,closeDetailTask:Ae,openSettings:Ue,closeSettings:kt,openSchedules:De,closeSchedules:be,openGitHubImport:pe,closeGitHubImport:Re,openUsage:Be,closeUsage:at,openSystemStats:me,closeSystemStats:ft,toggleTerminal:Et,closeTerminal:jt,openFiles:$t,closeFiles:Ft,openTodos:Rt,closeTodos:It,setFileWorkspace:Vt,openActivityLog:Qt,closeActivityLog:Jt,openGitManager:on,closeGitManager:Kt,openWorkflowSteps:qt,closeWorkflowSteps:kn,openAgents:nn,closeAgents:Xt,openScripts:Gt,closeScripts:ln,runScript:ye,openSetupWizard:Le,closeSetupWizard:ae,openModelOnboarding:Te,closeModelOnboarding:Ne,onPlanningTaskCreated:ee,onPlanningTasksCreated:Ie,onSubtaskTasksCreated:St}}function cL(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,v]=i.useState(!1),[b,k]=i.useState(!1),[S,j]=i.useState({}),[E,y]=i.useState(!1),[N,M]=i.useState(!1),[D,C]=i.useState(!1),[_,F]=i.useState(!1),[U,A]=i.useState(!1),[$,T]=i.useState(!0),J=i.useCallback(async()=>{const[w,Y]=await Promise.allSettled([Yw(e),Ll(e)]);if(w.status==="fulfilled"&&(s(w.value.maxConcurrent),r(w.value.rootDir)),Y.status==="fulfilled"){const re=Y.value;l(!!re.autoMerge),d(!!re.globalPause),m(!!re.enginePaused),v(!!re.prAuthAvailable),f(re.taskStuckTimeoutMs),g(re.showQuickChatFAB===!0),j(re.experimentalFeatures??{});const le=re.experimentalFeatures??{};y(le.insights===!0),M(le.roadmap===!0),C(le.memoryView===!0),F(le.devServerView===!0||le.devServer===!0),A(le.todoView===!0);const ve=re.autoReloadOnVersionChange!==!1;T(ve),Zl(ve)}k(!0)},[e]);i.useEffect(()=>{k(!1),j({}),y(!1),M(!1),C(!1),F(!1),A(!1),J()},[J]);const B=i.useCallback(async()=>{const w=!o;l(w);try{await jo({autoMerge:w},e)}catch{l(!w)}},[o,e]),se=i.useCallback(async()=>{const w=!c;d(w);try{await jo({globalPause:w,globalPauseReason:w?"manual":void 0},e)}catch{d(!w)}},[c,e]),P=i.useCallback(async()=>{const w=!u;m(w);try{await jo({enginePaused:w},e)}catch{m(!w)}},[u,e]),O=i.useCallback(async()=>{const w=!p;g(w);try{await jo({showQuickChatFAB:w},e)}catch{g(!w)}},[p,e]),I=i.useCallback(async()=>{const w=!$;T(w),Zl(w);try{await Dn({autoReloadOnVersionChange:w})}catch{T(!w),Zl(!w)}},[$]);return{maxConcurrent:n,rootDir:a,autoMerge:o,globalPaused:c,enginePaused:u,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:x,settingsLoaded:b,experimentalFeatures:S,insightsEnabled:E,roadmapEnabled:N,memoryEnabled:D,devServerEnabled:_,todosEnabled:U,autoReloadOnVersionChange:$,toggleAutoMerge:B,toggleGlobalPause:se,toggleEnginePause:P,toggleShowQuickChatFAB:O,toggleAutoReloadOnVersionChange:I,refresh:J}}function dL(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(null);return i.useEffect(()=>{const f=new URLSearchParams(window.location.search),p=f.get("project"),g=f.get("task");if(!g||a)return;if(p){const v=s.find(b=>b.id===p);if(!v){l(`Project '${p}' not found`,"error");return}r?.id!==v.id&&o(v)}if(u.current)return;u.current=!0,Wa(g,p??n).then(v=>{c(v),m.current=g}).catch(()=>{l(`Task ${g} not found`,"error")})},[n,s,a,r,o,l,c]),{handleDetailClose:i.useCallback(()=>{if(m.current){const f=new URLSearchParams(window.location.search);f.delete("task");const p=f.toString(),g=window.history.state??{};window.history.replaceState(g,"",p?`${window.location.pathname}?${p}`:window.location.pathname),m.current=null}d()},[d])}}function uL(){const[e,n]=i.useState([]),[s,a]=i.useState([]),[r,o]=i.useState([]),l=i.useRef(s),c=i.useRef(r);i.useEffect(()=>{Os().then(m=>{n(m.models),l.current=m.favoriteProviders,c.current=m.favoriteModels,a(m.favoriteProviders),o(m.favoriteModels)}).catch(()=>{})},[]),i.useEffect(()=>{l.current=s},[s]),i.useEffect(()=>{c.current=r},[r]);const d=i.useCallback(async m=>{const h=l.current,p=h.includes(m)?h.filter(g=>g!==m):[m,...h];l.current=p,a(()=>p);try{await Dn({favoriteProviders:p,favoriteModels:c.current})}catch(g){throw l.current=h,a(()=>h),g}},[]),u=i.useCallback(async m=>{const h=c.current,p=h.includes(m)?h.filter(g=>g!==m):[m,...h];c.current=p,o(()=>p);try{await Dn({favoriteProviders:l.current,favoriteModels:p})}catch(g){throw c.current=h,o(()=>h),g}},[]);return{availableModels:e,favoriteProviders:s,favoriteModels:r,toggleFavoriteProvider:d,toggleFavoriteModel:u}}function mL({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;Kr().then(({providers:d})=>{const u=d.some(h=>h.authenticated);if(d.length>0&&!u||d.length>0&&u)return ga().then(h=>{const f=!!(h.defaultProvider&&h.defaultModelId);(h.modelOnboardingComplete===!1||h.modelOnboardingComplete===void 0)&&(!u||!f)&&!nr()?l=!0:!u&&!nr()&&(c=!0)})}).then(()=>{if(o.current){r.current=!1;return}l?(ni("onboarding:auto-triggered",{trigger:"first-run"}),s()):c&&(ni("onboarding:auto-triggered",{trigger:"missing-provider"}),a("authentication"))}).catch(()=>{})},[e,n,s,a])}const hf="kb-update-banner-dismissed";function hL(){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(hf)==="true";u(h);let f=!1;return Qw().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(hf,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:d,dismiss:m}}const pL=["board","list","agents","missions","chat","documents","research","roadmaps","skills","mailbox","insights","memory","devserver","dev-server"];function fL(e){return e!==null&&pL.includes(e)}function pf(e){return e!==null&&(fL(e)||za(e))}function gL(e){return e==="devserver"?"dev-server":e}function bL(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=ss("kb-dashboard-task-view");return pf(b)?b:"board"}),g=i.useRef(!1);i.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),i.useEffect(()=>{const b=ss("kb-dashboard-task-view",r?.id);if(pf(b)){const k=!g.current&&b==="devserver";p(k?"devserver":gL(b))}else p("board");r?.id&&(g.current=!0)},[r?.id]),i.useEffect(()=>{vs("kb-dashboard-task-view",f,r?.id)},[r?.id,f]),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)},[]),v=i.useCallback(()=>{const b=["dark","light","system"],k=b.indexOf(d),S=b[(k+1)%b.length];u(S)},[d,u]);return{viewMode:m,setViewMode:h,taskView:f,setTaskView:p,handleChangeTaskView:x,handleToggleTheme:v}}function xL(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 od=new Map,vL=6e4;function yL(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";od.delete(h),d(f=>f+1)},[e]);return i.useEffect(()=>{const h=e??"default";let f=!1;async function p(){const g=od.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 $1(e);if(f)return;od.set(h,{views:x,expiresAt:Date.now()+vL}),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 wL({taskView:e}){return t.jsx(pS,{viewId:e})}function kL(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(M=>{n(M),a("project")},[n,a]),g=i.useCallback(()=>{s(),a("overview")},[s,a]),x=i.useCallback(()=>{u()},[u]),v=i.useCallback(()=>{m()},[m]),b=i.useCallback(M=>{h(),n(M),a("project"),d(`Project ${M.name} registered successfully`,"success"),o()},[h,n,a,d,o]),k=i.useCallback(()=>{f()},[f]),S=i.useCallback(async M=>{try{await hN(M.id),d(`Project ${M.name} paused`,"success"),await o()}catch{d(`Failed to pause project ${M.name}`,"error")}},[d,o]),j=i.useCallback(async M=>{try{await pN(M.id),d(`Project ${M.name} resumed`,"success"),await o()}catch{d(`Failed to resume project ${M.name}`,"error")}},[d,o]),E=i.useCallback(async M=>{try{await Uf(M.id),d(`Project ${M.name} removed`,"success"),r?.id===M.id&&(s(),a("overview")),await o()}catch{d(`Failed to remove project ${M.name}`,"error")}},[r,s,a,d,o]),y=i.useCallback(async M=>{try{await l(M)}catch{d("Failed to update favorites","error")}},[l,d]),N=i.useCallback(async M=>{try{await c(M)}catch{d("Failed to update model favorites","error")}},[c,d]);return{handleSelectProject:p,handleViewAllProjects:g,handleOpenSettings:x,handleAddProject:v,handleSetupComplete:b,handleModelOnboardingComplete:k,handlePauseProject:S,handleResumeProject:j,handleRemoveProject:E,handleToggleFavorite:y,handleToggleModelFavorite:N}}function jL(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}}async function NL(e){return Fl("/health",{nodeId:e})}async function SL(e){return Fl("/projects",{nodeId:e})}async function CL(e,n,s){const a=new URLSearchParams({projectId:n});return s&&s.trim()&&a.set("q",s.trim()),Fl(`/tasks?${a.toString()}`,{nodeId:e})}async function EL(e,n){return Fl(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function sz(e){return R(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function iz(e){return R(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function az(e){return R(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function rz(e){return R(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}function _L(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 k=[NL(e),SL(e)];s&&(k.push(CL(e,s,a)),k.push(EL(e,s)));const S=await Promise.allSettled(k);if(b.signal.aborted)return;const j=S[0],E=S[1];if(j.status==="rejected"){p(`Failed to fetch node health: ${j.reason}`),h(!1);return}if(u(j.value),E.status==="rejected"){p(`Failed to fetch projects: ${E.reason}`),h(!1);return}if(o(E.value),s&&S[2]){const y=S[2];if(y.status==="rejected"){p(`Failed to fetch tasks: ${y.reason}`),h(!1);return}y.status==="fulfilled"&&c(y.value)}h(!1)}catch(k){b.signal.aborted||(p(k instanceof Error?k.message:"Unknown error"),h(!1))}},[e,s,a]);i.useEffect(()=>(x(),()=>{g.current?.abort()}),[x]);const v=i.useCallback(()=>{x()},[x]);return{projects:r,tasks:l,health:d,loading:m,error:f,refresh:v}}function ML(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 gi(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 AL="fusion-dashboard-current-node",hx=i.createContext(null);function PL({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 ga();if(m)return;l.current=f.dashboardCurrentNodeId;const p=f.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const g=localStorage.getItem(AL);if(g){const x=JSON.parse(g);x?.id&&x?.type==="remote"&&(l.current=x.id,await Dn({dashboardCurrentNodeId:x.id}).catch(()=>{}))}}catch{}}catch{}finally{m||r(!1)}}return h(),()=>{m=!0}},[]),i.useEffect(()=>{if(!a)if(n&&n.type==="remote"&&n.id){const m=n.id;l.current!==m&&(l.current=m,Dn({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,Dn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,a]);const c=i.useCallback(m=>{s(m)},[]),d=i.useCallback(()=>{s(null),l.current=void 0,Dn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),u={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:d};return t.jsx(hx.Provider,{value:u,children:e})}function RL(){const e=i.useContext(hx);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}const px={host:"web",activeProfileId:null,profiles:[]},fx=i.createContext({shellApi:null,state:px,ready:!0});function TL({children:e}){const n=i.useMemo(()=>typeof window<"u"?window.fusionShell??null:null,[]),[s,a]=i.useState(px),[r,o]=i.useState(!n);return i.useEffect(()=>{if(!n)return;let l=!1;n.getState().then(d=>{l||(a(d),o(!0))});const c=n.subscribe(d=>{a(d)});return()=>{l=!0,c()}},[n]),t.jsx(fx.Provider,{value:{shellApi:n,state:s,ready:r},children:e})}function IL(){return i.useContext(fx)}function $L(){return IL()}function DL(e,n){const s=new URL(e);return n&&s.searchParams.set("token",n),s.toString()}function LL({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=s.host==="desktop-shell";i.useEffect(()=>{g&&o(s.desktopMode??"remote")},[g,s.desktopMode]);const x=i.useMemo(()=>g&&r==="local"?!0:d.trim().length>0,[g,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."}),g&&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"})]}),(!g||r==="remote")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn",onClick:async()=>{p(null);try{const v=await n.startQrScan();u(v.serverUrl),h(v.authToken??"")}catch(v){p(v.message)}},children:"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:v=>c(v.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:v=>u(v.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",value:m,onChange:v=>h(v.target.value)})]}),f&&t.jsx("p",{className:"form-error",children:f})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{type:"button",className:"btn btn-primary",disabled:!x,onClick:async()=>{p(null);try{if(g&&r==="local"){await n.setDesktopMode("local"),a();return}const v=await n.saveProfile({name:l.trim()||"Remote Server",serverUrl:d,authToken:m||null});if(g&&await n.setDesktopMode("remote"),await n.setActiveProfile(v.id),typeof window<"u"&&s.host!=="web"){window.location.href=DL(v.serverUrl,v.authToken??null);return}a()}catch(v){p(v.message)}},children:"Continue"})})]})}):null}function OL({open:e,shellApi:n,shellState:s,onClose:a}){const r=i.useMemo(()=>s.profiles.find(p=>p.id===s.activeProfileId)??null,[s.activeProfileId,s.profiles]),[o,l]=i.useState({}),[c,d]=i.useState(null);if(!e)return null;const u=o.name??r?.name??"",m=o.serverUrl??r?.serverUrl??"",h=o.authToken??r?.authToken??"",f=async()=>{d(null);try{const p=await n.saveProfile({id:r?.id,name:u||"Remote Server",serverUrl:m,authToken:h||null});await n.setActiveProfile(p.id),l({})}catch(p){d(p.message)}};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.map(p=>t.jsxs("div",{className:"card native-shell-connection-manager__profile",children:[t.jsxs("div",{children:[t.jsx("strong",{children:p.name}),t.jsx("div",{className:"settings-muted",children:p.serverUrl})]}),t.jsxs("div",{className:"native-shell-connection-manager__profile-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>l(p),children:"Edit"}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void n.setActiveProfile(p.id),children:"Use"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>void n.deleteProfile(p.id),children:"Delete"})]})]},p.id))}),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:u,onChange:p=>l(g=>({...g,name:p.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:m,onChange:p=>l(g=>({...g,serverUrl:p.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",value:h??"",onChange:p=>l(g=>({...g,authToken:p.target.value}))}),c&&t.jsx("p",{className:"form-error",children:c})]}),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 btn-primary",onClick:()=>void f(),disabled:!m.trim(),children:"Save"})]})]})})}function ff({state:e,onManage:n}){const s=e.profiles.find(r=>r.id===e.activeProfileId)??null,a=e.host==="desktop-shell"&&e.desktopMode==="local"?"Local Fusion":s?.name??"Disconnected";return t.jsxs("button",{type:"button",className:"btn native-shell-status",onClick:n,"data-testid":"native-shell-status-btn",children:[t.jsx("span",{className:`status-dot ${s||e.desktopMode==="local"?"status-dot--online":"status-dot--error"}`,"aria-hidden":"true"}),t.jsx("span",{className:"native-shell-status__label",children:a})]})}function FL({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&&(Cw(l),window.location.reload())},[n]),o=i.useCallback(()=>{Ew(),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 zL=200,UL=i.lazy(()=>Rn(()=>import("./AgentsView-BRXFmrcJ.js"),__vite__mapDeps([21,1,3,4,22,13,5,6,23])).then(e=>({default:e.AgentsView}))),BL=i.lazy(()=>Rn(()=>import("./DocumentsView-DmthQWDZ.js"),__vite__mapDeps([24,1,5,6,25])).then(e=>({default:e.DocumentsView}))),HL=i.lazy(()=>Rn(()=>import("./InsightsView-DvXpMKmH.js"),__vite__mapDeps([26,1,19,5,6,27])).then(e=>({default:e.InsightsView}))),qL=i.lazy(()=>Rn(()=>import("./ResearchView-D9DNJYDq.js"),__vite__mapDeps([28,1,5,6,29])).then(e=>({default:e.ResearchView}))),VL=i.lazy(()=>Rn(()=>import("./NodesView-BLlfUfsy.js"),__vite__mapDeps([30,1,22,5,6,31])).then(e=>({default:e.NodesView}))),WL=i.lazy(()=>Rn(()=>import("./ChatView-D7L2e_qu.js"),__vite__mapDeps([32,1,5,6])).then(e=>({default:e.ChatView}))),KL=i.lazy(()=>Rn(()=>import("./RoadmapsView-Djc_X35v.js"),__vite__mapDeps([33,1,5,6,34])).then(e=>({default:e.RoadmapsView}))),GL=i.lazy(()=>Rn(()=>import("./SkillsView-Ddf0YL8z.js"),__vite__mapDeps([35,1,5,6,36])).then(e=>({default:e.SkillsView}))),JL=i.lazy(()=>Rn(()=>import("./MemoryView-CPwlKnUI.js"),__vite__mapDeps([37,1,17,18,5,6,38])).then(e=>({default:e.MemoryView}))),YL=i.lazy(()=>Rn(()=>import("./DevServerView-l8RCyL2k.js"),__vite__mapDeps([39,1,5,6,40])).then(e=>({default:e.DevServerView})));i.lazy(()=>Rn(()=>Promise.resolve().then(()=>Ub),void 0).then(e=>({default:e.TodoView})));function QL(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{Rn(()=>import("./AgentsView-BRXFmrcJ.js"),__vite__mapDeps([21,1,3,4,22,13,5,6,23])),Rn(()=>import("./DocumentsView-DmthQWDZ.js"),__vite__mapDeps([24,1,5,6,25])),Rn(()=>import("./InsightsView-DvXpMKmH.js"),__vite__mapDeps([26,1,19,5,6,27])),Rn(()=>import("./ResearchView-D9DNJYDq.js"),__vite__mapDeps([28,1,5,6,29])),Rn(()=>import("./NodesView-BLlfUfsy.js"),__vite__mapDeps([30,1,22,5,6,31])),Rn(()=>import("./ChatView-D7L2e_qu.js"),__vite__mapDeps([32,1,5,6])),Rn(()=>import("./RoadmapsView-Djc_X35v.js"),__vite__mapDeps([33,1,5,6,34])),Rn(()=>import("./SkillsView-Ddf0YL8z.js"),__vite__mapDeps([35,1,5,6,36])),Rn(()=>import("./MemoryView-CPwlKnUI.js"),__vite__mapDeps([37,1,17,18,5,6,38])),Rn(()=>import("./DevServerView-l8RCyL2k.js"),__vite__mapDeps([39,1,5,6,40])),Rn(()=>Promise.resolve().then(()=>Ub),void 0)})}const ld="kb-setup-warning-dismissed";function XL(e,n,s){return!n||s||e.host==="web"?!1:e.host==="mobile-shell"?!e.activeProfileId:e.desktopMode==="local"?!1:!e.activeProfileId}function ZL(){const{toasts:e,addToast:n,removeToast:s}=eL(),{shellApi:a,state:r,ready:o}=$L(),l=typeof window<"u"&&!!window.electronAPI;i.useEffect(()=>{QL()},[]);const{projects:c,loading:d,error:u,refresh:m}=JD(),{nodes:h}=Ul(),{currentNode:f,currentNodeId:p,isRemote:g,setCurrentNode:x,clearCurrentNode:v}=RL(),{currentProject:b,setCurrentProject:k,clearCurrentProject:S,loading:j}=XD(c,{nodeId:p}),{hasAiProvider:E,hasGithub:y,loading:N,hasWarnings:M}=Jb(b?.id),{updateAvailable:D,latestVersion:C,currentVersion:_,dismissed:F,dismiss:U}=hL();i.useEffect(()=>{if(p&&!f&&h.length>0){const gt=h.find(hn=>hn.id===p);if(gt){x(gt);return}}p&&h.length>0&&(h.some(hn=>hn.id===p)||v())},[p,f,h,x,v]);const[A,$]=i.useState(""),T=_L(p,{projectId:b?.id,searchQuery:A||void 0});ML(p);const J=g&&T.projects.length>0?T.projects:c,{themeMode:B,colorTheme:se,dashboardFontScalePct:P,setThemeMode:O,setColorTheme:I,setDashboardFontScalePct:w}=oL(),{sessions:Y,generating:re,needsInput:le,planningSessions:ve,dismissSession:de}=UD(b?.id),Fe=Y.filter(gt=>gt.status==="awaiting_input"||gt.status==="error"),X=qD(),L=lL({projectId:b?.id,planningSessions:ve}),ne=oi()==="mobile",{pushNav:H,replaceCurrent:z}=xL({enabled:!0}),{viewMode:W,setViewMode:we,taskView:Z,handleChangeTaskView:fe}=bL({projectsLoading:d,projectsError:u,currentProjectLoading:j,currentProject:b,projectsLength:c.length,setupWizardOpen:L.setupWizardOpen,openSetupWizard:L.openSetupWizard,themeMode:B,setThemeMode:O}),{views:Oe}=yL(b?.id),Ve=i.useCallback(gt=>{gt==="missions"&&(Jt(void 0),Kt(void 0),kn(void 0));const hn=Z;fe(gt),hn!==gt&&H({type:"view",revert:()=>fe(hn)})},[fe,Z,H]),He=Z==="board"||Z==="list",{tasks:Je,createTask:$e,moveTask:he,pauseTask:ue,deleteTask:Ee,mergeTask:je,retryTask:xe,resetTask:Pe,updateTask:ie,duplicateTask:Me,archiveTask:We,unarchiveTask:mt,archiveAllDone:st,loadArchivedTasks:Ze,ingestCreatedTasks:dt,lastFetchTimeMs:Ae}=WD({...b?{projectId:b.id}:{},searchQuery:A||void 0,sseEnabled:He}),[Ue,kt]=i.useState(!1),[De,be]=i.useState(0),pe=i.useRef(performance.now()),Re=i.useRef(!1),Be=i.useRef(!1),at=i.useMemo(()=>d?"projects":j?"project":"tasks",[d,j]);i.useEffect(()=>{if(!d&&!Re.current){Re.current=!0;const gt=`projects loaded at ${Math.round(performance.now()-pe.current)}ms from mount`;console.log(`[App] ${gt}`),Or("[App]",gt)}if(!j&&!Be.current){Be.current=!0;const gt=`current-project resolved at ${Math.round(performance.now()-pe.current)}ms from mount`;console.log(`[App] ${gt}`),Or("[App]",gt)}},[d,j]),i.useEffect(()=>{if(Ue||d||j)return;const gt=performance.now(),hn=window.setTimeout(()=>{const Vs=`dashboard ready at ${Math.round(performance.now()-pe.current)}ms from mount (settle delay=${Math.round(performance.now()-gt)}ms)`;console.log(`[App] ${Vs}`),Or("[App]",Vs),kt(!0)},zL);return()=>{window.clearTimeout(hn)}},[Ue,d,j]);const{keyboardOpen:me}=ya({enabled:ne}),ft=ne&&me&&!L.anyModalOpen;Mi(ft);const[Et,jt]=i.useState(0),$t=i.useCallback(()=>{Wf(b?.id).then(gt=>{jt(gt.unreadCount)}).catch(gt=>{console.warn("[App] Failed to fetch mailbox unread count:",gt)})},[b?.id]);i.useEffect(()=>{$t();const gt=new URLSearchParams;b?.id&&gt.set("projectId",b.id);const hn=gt.size>0?`?${gt.toString()}`:"";return gi(`/api/events${hn}`,{events:{"message:sent":$t,"message:received":$t,"message:read":$t,"message:deleted":$t}})},[b?.id,$t]);const[Ft,Rt]=i.useState(!1),[It,Vt]=i.useState(!1),[Qt,Jt]=i.useState(void 0),[on,Kt]=i.useState(void 0),[qt,kn]=i.useState(void 0),[nn,Xt]=i.useState(!1),[Gt,ln]=i.useState(!1),[ye,Le]=i.useState(()=>ss(ld,b?.id)==="true");i.useEffect(()=>{Le(ss(ld,b?.id)==="true")},[b?.id]),i.useEffect(()=>{const gt=()=>{ln(!0)};return window.addEventListener(yd,gt),()=>{window.removeEventListener(yd,gt)}},[]);const ae=i.useCallback(()=>{vs(ld,"true",b?.id),Le(!0)},[b?.id]),{maxConcurrent:Te,autoMerge:Ne,globalPaused:ee,enginePaused:Ie,taskStuckTimeoutMs:St,showQuickChatFAB:pt,prAuthAvailable:Dt,settingsLoaded:Ut,experimentalFeatures:Ce,insightsEnabled:et,roadmapEnabled:tt,memoryEnabled:Lt,devServerEnabled:Zt,todosEnabled:sn,toggleAutoMerge:At,toggleGlobalPause:cn,toggleEnginePause:Tn,refresh:En}=cL(b?.id),bn=Ce.skillsView===!0,In=Ce.nodesView===!0,ge=Ce.researchView===!0,ut=Ce.agentOnboarding===!0,xn=!0,oe=i.useCallback(()=>{L.closeSettings(),be(gt=>gt+1),En()},[L,En]);i.useEffect(()=>{Ut&&(za(Z)||(Z==="skills"&&!bn&&fe("board"),Z==="insights"&&!et&&fe("board"),Z==="roadmaps"&&!tt&&fe("board"),Z==="memory"&&!Lt&&fe("board"),(Z==="devserver"||Z==="dev-server")&&!Zt&&fe("board"),Z==="research"&&!ge&&fe("board")))},[Z,Ut,bn,et,tt,fe,xn,Lt,Zt,ge]),i.useEffect(()=>{Ft&&!In&&Rt(!1)},[Ft,In]);const{availableModels:ct,favoriteProviders:rt,favoriteModels:wt,toggleFavoriteProvider:ot,toggleFavoriteModel:vt}=uL();mL({projectId:b?.id,setupWizardOpen:L.setupWizardOpen,openModelOnboarding:L.openModelOnboarding,openSettings:L.openSettings});const{handleSelectProject:Wt,handleViewAllProjects:an,handleAddProject:pn,handleSetupComplete:Hn,handleModelOnboardingComplete:Mn,handlePauseProject:Qn,handleResumeProject:ms,handleRemoveProject:Xn,handleToggleFavorite:mn,handleToggleModelFavorite:Pt}=kL({setCurrentProject:k,clearCurrentProject:S,setViewMode:we,currentProject:b,refreshProjects:m,toggleFavoriteProvider:ot,toggleFavoriteModel:vt,addToast:n,openSettings:L.openSettings,openSetupWizard:L.openSetupWizard,closeSetupWizard:L.closeSetupWizard,closeModelOnboarding:L.closeModelOnboarding}),{handleDetailClose:is}=dL({projectId:b?.id,projects:c,projectsLoading:d,currentProject:b,setCurrentProject:k,addToast:n,openTaskDetail:L.openDetailTask,closeTaskDetail:L.closeDetailTask}),Gn=i.useCallback(async({insightId:gt,title:hn,description:Vs})=>{await $e({title:hn,description:Vs,column:"triage",source:{sourceType:"dashboard_ui",sourceMetadata:{origin:"insights",insightId:gt}}})},[$e]),{handleBoardQuickCreate:K,handleModalCreate:Ke,handlePlanningTaskCreated:Ye,handlePlanningTasksCreated:ht,handleSubtaskTasksCreated:Nt,handleGitHubImport:_t}=jL({createTask:$e,ingestCreatedTasks:dt,onPlanningTaskCreated:L.onPlanningTaskCreated,onPlanningTasksCreated:L.onPlanningTasksCreated,onSubtaskTasksCreated:L.onSubtaskTasksCreated,addToast:n}),zt=i.useCallback((gt,hn)=>{hn==="changes"?L.openDetailWithChangesTab(gt):L.openDetailTask(gt,hn),H({type:"modal",close:L.closeDetailTask})},[L,H]),Jn=i.useCallback(async gt=>{try{const hn=await Wa(gt,b?.id);L.openDetailTask(hn,"logs"),H({type:"modal",close:L.closeDetailTask})}catch(hn){n(`Failed to open task logs: ${hn.message}`,"error")}},[L,b?.id,n,H]),[as,ce]=i.useState([]);i.useEffect(()=>{let gt=!1;return lo(b?.id).then(hn=>{gt||ce(hn)}).catch(()=>{gt||ce([])}),()=>{gt=!0}},[b?.id]);const Ge=i.useMemo(()=>new Map(as.map(gt=>[gt.id,gt.name])),[as]);i.useCallback(()=>{In&&Rt(gt=>!gt)},[In]);const lt=i.useCallback(()=>{In&&(Ft?Rt(!1):(Rt(!0),H({type:"view",revert:()=>Rt(!1)})))},[In,Ft,H]),tn=i.useCallback((gt,hn,Vs)=>{L.openDetailTask(gt,hn,Vs),H({type:"modal",close:L.closeDetailTask})},[L,H]),G=i.useCallback(gt=>{L.openSettings(gt),H({type:"modal",close:oe})},[L,H,oe]),Se=i.useCallback(()=>{L.openNewTask(),H({type:"modal",close:L.closeNewTask})},[L,H]),it=i.useCallback(()=>{L.openPlanning(),H({type:"modal",close:L.closePlanning})},[L,H]),Ct=i.useCallback(gt=>{L.openPlanningWithInitialPlan(gt),H({type:"modal",close:L.closePlanning})},[L,H]),Tt=i.useCallback(()=>{L.resumePlanning(),H({type:"modal",close:L.closePlanning})},[L,H]),An=i.useCallback(gt=>{L.openSubtaskBreakdown(gt),H({type:"modal",close:L.closeSubtask})},[L,H]),vn=i.useCallback(()=>{L.openGitHubImport(),H({type:"modal",close:L.closeGitHubImport})},[L,H]),yn=i.useCallback(()=>{L.terminalOpen?L.toggleTerminal():(L.toggleTerminal(),H({type:"modal",close:L.closeTerminal}))},[L,H]),fn=i.useCallback(()=>{L.openFiles(),H({type:"modal",close:L.closeFiles})},[L,H]),Ln=i.useCallback(()=>{L.openTodos(),H({type:"modal",close:L.closeTodos})},[L,H]),Zn=i.useCallback(()=>{L.openActivityLog(),H({type:"modal",close:L.closeActivityLog})},[L,H]),hs=i.useCallback(()=>{L.openGitManager(),H({type:"modal",close:L.closeGitManager})},[L,H]),On=i.useCallback(()=>{L.openSystemStats(),H({type:"modal",close:L.closeSystemStats})},[L,H]),$n=i.useCallback(()=>{L.openSchedules(),H({type:"modal",close:L.closeSchedules})},[L,H]),Pn=i.useCallback(()=>{L.openScripts(),H({type:"modal",close:L.closeScripts})},[L,H]),ps=i.useCallback(()=>{L.openWorkflowSteps(),H({type:"modal",close:L.closeWorkflowSteps})},[L,H]),qn=i.useCallback(gt=>{L.openUsage(gt),H({type:"modal",close:L.closeUsage})},[L,H]),es=i.useCallback(async(gt,hn)=>{await L.runScript(gt,hn),z({type:"modal",close:L.closeTerminal})},[L,z]),Fn=i.useCallback(()=>{L.closeSettings(),L.openModelOnboarding(),z({type:"modal",close:L.closeModelOnboarding})},[L,z]),rs=i.useCallback(()=>{L.setFileWorkspace("project"),L.openFiles()},[L]),ks=i.useCallback(async()=>{Vt(!0);try{await m()}finally{Vt(!1)}},[m]),os=i.useCallback(gt=>{Kt(gt),Jt(void 0),fe("missions")},[fe]),xs=i.useCallback(gt=>{gt.type==="planning"?L.openPlanningWithSession(gt.id):gt.type==="subtask"?L.openSubtaskWithSession(gt.id):gt.type==="mission_interview"?(Kt(void 0),Jt(gt.id),kn(void 0),fe("missions")):(gt.type==="milestone_interview"||gt.type==="slice_interview")&&(Jt(void 0),Kt(void 0),kn(gt.id),fe("missions"))},[fe,L]),qs=i.useCallback(()=>{},[]),Fs=i.useCallback(()=>{},[]),[wa,ka]=i.useState(!1),[cr,Qi]=i.useState(!1),Xi=XL(r,o,wa);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]);const Xs=!d&&!j&&c.length===0&&!b&&!!u,li=()=>Xs?t.jsx(K$,{errorMessage:u??"Failed to fetch projects",isRetrying:It,onRetry:ks,onManageConnection:a?()=>{a.openConnectionManager()}:void 0}):Ft?t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(VL,{addToast:n,onClose:()=>Rt(!1)})})})}):W==="overview"?t.jsx(_s,{children:t.jsx(DR,{projects:c,loading:d,onSelectProject:Wt,onAddProject:pn,onPauseProject:Qn,onResumeProject:ms,onRemoveProject:Xn,nodes:h})}):za(Z)?t.jsx(_s,{children:t.jsx(wL,{taskView:Z,context:{projectId:b?.id,tasks:g&&T.tasks.length>0?T.tasks:Je,workflowSteps:as,openTaskDetail:(gt,hn)=>tn(gt,hn),renderTaskCard:gt=>t.jsx(Jr,{task:gt,projectId:b?.id,onOpenDetail:hn=>tn(hn),addToast:n,workflowStepNameLookup:Ge})}})}):Z==="skills"?!Ut||!bn?null:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(GL,{addToast:n,projectId:b?.id,onClose:()=>fe("board")})})}):Z==="chat"?t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(WL,{addToast:n,projectId:b?.id})})}):Z==="mailbox"?t.jsx(_s,{children:t.jsx(ET,{projectId:b?.id,addToast:n,onUnreadCountChange:jt})}):Z==="roadmaps"?!Ut||!tt?null:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(KL,{addToast:n,projectId:b?.id})})}):Z==="missions"?t.jsx(_s,{children:t.jsx(jT,{isInline:!0,isOpen:!0,onClose:()=>{Kt(void 0),Jt(void 0),kn(void 0),fe("board")},addToast:n,projectId:b?.id,onSelectTask:gt=>{const hn=Je.find(Vs=>Vs.id===gt);hn&&tn(hn)},availableTasks:Je.map(gt=>({id:gt.id,title:gt.title})),resumeSessionId:Qt,targetMissionId:on,milestoneSliceResumeSessionId:qt,onMilestoneSliceResumeFetchError:()=>kn(void 0)})}):Z==="agents"&&xn?t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(UL,{addToast:n,projectId:b?.id,onOpenTaskLogs:Jn,agentOnboardingEnabled:ut})})}):Z==="documents"?t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(BL,{projectId:b?.id,addToast:n,onOpenDetail:tn})})}):Z==="insights"?!Ut||!et?null:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(HL,{projectId:b?.id,addToast:n,onClose:()=>fe("board"),onCreateTask:Gn})})}):Z==="research"?!Ut||!ge?null:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(qL,{projectId:b?.id,addToast:n,onOpenSettings:gt=>L.openSettings(gt),readinessVersion:De})})}):Z==="memory"?!Ut||!Lt?null:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(JL,{addToast:n,projectId:b?.id})})}):Z==="devserver"||Z==="dev-server"?!Ut||!Zt?null:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(YL,{addToast:n,projectId:b?.id})})}):Z==="board"?t.jsx(_s,{children:t.jsx(z0,{tasks:g&&T.tasks.length>0?T.tasks:Je,projectId:b?.id,maxConcurrent:Te,onMoveTask:he,onPauseTask:ue,onOpenDetail:tn,addToast:n,onQuickCreate:K,onNewTask:Se,onPlanningMode:Ct,onSubtaskBreakdown:An,autoMerge:Ne,onToggleAutoMerge:At,globalPaused:ee,onUpdateTask:ie,onRetryTask:xe,onArchiveTask:We,onUnarchiveTask:mt,onDeleteTask:Ee,onArchiveAllDone:st,onLoadArchivedTasks:Ze,searchQuery:A,availableModels:ct,onOpenDetailWithTab:zt,favoriteProviders:rt,favoriteModels:wt,onToggleFavorite:mn,onToggleModelFavorite:Pt,taskStuckTimeoutMs:St,onOpenMission:os,lastFetchTimeMs:Ae})}):t.jsx(_s,{children:t.jsx(CR,{tasks:g&&T.tasks.length>0?T.tasks:Je,projectId:b?.id,onMoveTask:he,onRetryTask:xe,onDeleteTask:Ee,onMergeTask:je,onResetTask:Pe,onDuplicateTask:Me,onOpenDetail:(gt,hn)=>tn(gt,void 0,hn),addToast:n,globalPaused:ee,onNewTask:Se,onQuickCreate:K,onPlanningMode:Ct,onSubtaskBreakdown:An,availableModels:ct,favoriteProviders:rt,favoriteModels:wt,onToggleFavorite:mn,onToggleModelFavorite:Pt,taskStuckTimeoutMs:St,searchQuery:A,lastFetchTimeMs:Ae,prAuthAvailable:Dt})});if(!Ue)return t.jsxs(t.Fragment,{children:[t.jsx(J$,{stage:at}),t.jsx(tx,{toasts:e,onRemove:s})]});const Pi=!L.modelOnboardingOpen&&b$(),bi=!L.modelOnboardingOpen&&!Pi&&nr()&&!Qb();return t.jsxs(t.Fragment,{children:[t.jsx(xS,{isElectron:l,onOpenSettings:G,onOpenGitHubImport:vn,onOpenPlanning:it,onResumePlanning:Tt,activePlanningSessionCount:ve.length,onOpenUsage:qn,onOpenActivityLog:Zn,onOpenSystemStats:On,onOpenMailbox:()=>Ve("mailbox"),mailboxUnreadCount:Et,onOpenSchedules:$n,onOpenGitManager:hs,onOpenNodes:lt,showNodesButton:In,onOpenWorkflowSteps:ps,onOpenScripts:Pn,onRunScript:es,onToggleTerminal:yn,onOpenFiles:fn,filesOpen:L.filesOpen,onOpenTodos:Ln,todosOpen:L.todosOpen,todosEnabled:sn,globalPaused:ee,enginePaused:Ie,onToggleGlobalPause:cn,onToggleEnginePause:Tn,view:Z,onChangeView:W==="project"&&b?Ve:void 0,showSkillsTab:bn,showAgentsTab:xn,searchQuery:A,onSearchChange:$,projects:J,currentProject:b,onSelectProject:Wt,onViewAllProjects:an,projectId:b?.id,mobileNavEnabled:ne,availableNodes:h,currentNode:f,onSelectNode:gt=>{gt===null?v():x(gt)},isRemote:g,experimentalFeatures:{insights:et,roadmap:tt,memoryView:Lt,devServer:Zt,devServerView:Zt,researchView:ge},pluginDashboardViews:Oe,shellConnectionControl:a&&r.host!=="web"?t.jsx(ff,{state:r,onManage:()=>Qi(!0)}):void 0}),W==="project"&&b&&!Ft&&Z!=="missions"&&!L.isPlanningOpen&&!X&&t.jsx(dD,{sessions:Fe,onResumeSession:xs,onDismissSession:qs,onDismissAll:Fs}),W==="project"&&b&&t.jsx(hD,{onOpenSettings:()=>L.openSettings("general")}),W==="project"&&b&&Pi&&t.jsx(fD,{onResume:L.openModelOnboarding}),W==="project"&&b&&bi&&t.jsx(gD,{onOpenModelOnboarding:L.openModelOnboarding,onOpenSettings:gt=>L.openSettings(gt)}),W==="project"&&b&&D&&C&&_&&!F&&t.jsx(pD,{latestVersion:C,currentVersion:_,onDismiss:U}),W==="project"&&b&&!N&&M&&!ye&&t.jsx(Yb,{hasAiProvider:E,hasGithub:y,onDismiss:ae}),t.jsx("div",{className:`project-content${W==="project"&&b?" project-content--with-footer":""}${ne&&!ft?" project-content--with-mobile-nav":""}`,children:li()}),W==="project"&&b&&!Ft&&t.jsx(aD,{tasks:g&&T.tasks.length>0?T.tasks:Je,projectId:b.id,taskStuckTimeoutMs:St,backgroundSessions:Y,backgroundGenerating:re,backgroundNeedsInput:le,onOpenBackgroundSession:xs,onDismissBackgroundSession:de,lastFetchTimeMs:Ae,currentProjectPath:b.path,onOpenProjectDirectory:rs}),t.jsx(xD,{view:Z,onChangeView:W==="project"&&b?Ve:()=>{},footerVisible:W==="project"&&!!b,modalOpen:L.anyModalOpen,keyboardOpen:ft,onOpenSettings:G,onOpenActivityLog:Zn,onOpenSystemStats:On,onOpenMailbox:()=>Ve("mailbox"),onOpenNodes:lt,mailboxUnreadCount:Et,onOpenGitManager:hs,onOpenWorkflowSteps:ps,onOpenSchedules:$n,onOpenScripts:Pn,onToggleTerminal:yn,onOpenFiles:fn,onOpenTodos:Ln,todosOpen:L.todosOpen,onOpenGitHubImport:vn,onOpenPlanning:it,onResumePlanning:Tt,activePlanningSessionCount:ve.length,onOpenUsage:()=>qn(null),onViewAllProjects:an,onRunScript:es,projectId:b?.id,showSkillsTab:bn,experimentalFeatures:{insights:et,roadmap:tt,memoryView:Lt,devServer:Zt,devServerView:Zt,todoView:sn,researchView:ge,nodesView:In},pluginDashboardViews:Oe,shellConnectionControl:a&&r.host!=="web"?t.jsx(ff,{state:r,onManage:()=>Qi(!0)}):void 0}),W==="project"&&b&&Z!=="chat"&&Z!=="mailbox"&&Z!=="insights"&&Z!=="devserver"&&Z!=="dev-server"&&!za(Z)&&t.jsx(zD,{projectId:b.id,addToast:n,showFAB:pt,open:nn,onOpenChange:Xt,favoriteProviders:rt,favoriteModels:wt,onToggleFavorite:mn,onToggleModelFavorite:Pt}),t.jsx(W$,{projectId:b?.id,tasks:Je,projects:c,currentProject:b,addToast:n,toasts:e,removeToast:s,modalManager:L,projectActions:{handleAddProject:pn,handleSetupComplete:Hn,handleModelOnboardingComplete:Mn},taskHandlers:{handleModalCreate:Ke,handlePlanningTaskCreated:Ye,handlePlanningTasksCreated:ht,handleSubtaskTasksCreated:Nt,handleGitHubImport:_t},taskOperations:{moveTask:he,deleteTask:Ee,mergeTask:je,retryTask:xe,resetTask:Pe,duplicateTask:Me},deepLink:{handleDetailClose:is},settings:{prAuthAvailable:Dt,themeMode:B,colorTheme:se,dashboardFontScalePct:P,setThemeMode:O,setColorTheme:I,setDashboardFontScalePct:w},onSettingsClose:oe,onReopenOnboarding:Fn}),t.jsx(FL,{open:Gt}),a&&t.jsxs(t.Fragment,{children:[t.jsx(LL,{open:Xi,shellApi:a,shellState:r,onComplete:()=>ka(!0)}),t.jsx(OL,{open:cr,shellApi:a,shellState:r,onClose:()=>Qi(!1)})]})]})}function eO(){return t.jsx(ZD,{children:t.jsx(TL,{children:t.jsx(PL,{children:t.jsx(RS,{children:t.jsx(ZL,{})})})})})}function gx(e){e.postMessage({type:"SKIP_WAITING"})}function gf(e){e.addEventListener("statechange",()=>{e.state==="installed"&&navigator.serviceWorker.controller&&gx(e)})}function tO(){if(!("serviceWorker"in navigator))return;let e=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{e||(e=!0,Zd("service worker activated new version"))}),navigator.serviceWorker.register("/sw.js").then(n=>{console.log("SW registered:",n.scope),n.waiting&&navigator.serviceWorker.controller&&gx(n.waiting),n.installing&&gf(n.installing),n.addEventListener("updatefound",()=>{const s=n.installing;s&&gf(s)})}).catch(n=>{console.log("SW registration failed:",n)})}Iw();vw();bx.createRoot(document.getElementById("root")).render(t.jsx(i.StrictMode,{children:t.jsx(yw,{children:t.jsx(eO,{})})}));tO();export{ns as $,Gs as A,zn as B,Wn as C,Qs as D,vs as E,Ki as F,Al as G,Ll as H,jo as I,_e as J,MS as K,bt as L,AF as M,fd as N,jy as O,Kn as P,Cn as Q,us as R,$i as S,Dl as T,ol as U,io as V,tz as W,en as X,e$ as Y,ds as Z,td as _,un as a,Ul as a$,mi as a0,Sn as a1,Rn as a2,Y4 as a3,Xj as a4,H4 as a5,q4 as a6,Zj as a7,EF as a8,eN as a9,G3 as aA,K3 as aB,W3 as aC,V3 as aD,q3 as aE,B3 as aF,Tf as aG,Dw as aH,Kr as aI,az as aJ,sz as aK,iz as aL,rz as aM,Wr as aN,cd as aO,Ky as aP,Lr as aQ,si as aR,Oy as aS,cv as aT,Cs as aU,Af as aV,Dy as aW,UF as aX,BF as aY,HF as aZ,qF as a_,zO as aa,UO as ab,ij as ac,Qd as ad,sr as ae,fa as af,Ci as ag,Ei as ah,pi as ai,I3 as aj,F3 as ak,O3 as al,$3 as am,z3 as an,D3 as ao,L3 as ap,ys as aq,Zr as ar,Rs as as,iw as at,fi as au,jf as av,Oi as aw,Cx as ax,U3 as ay,H3 as az,Un as b,lF as b$,JD as b0,rm as b1,ic as b2,Ja as b3,O1 as b4,R3 as b5,T3 as b6,z1 as b7,yD as b8,U1 as b9,d3 as bA,l3 as bB,ts as bC,Rl as bD,Wi as bE,A3 as bF,M3 as bG,P3 as bH,yO as bI,vO as bJ,xO as bK,wO as bL,AO as bM,PO as bN,EO as bO,NO as bP,SO as bQ,CO as bR,jO as bS,kO as bT,bO as bU,_O as bV,_I as bW,oF as bX,rF as bY,hF as bZ,aF as b_,_D as ba,ya as bb,D1 as bc,_l as bd,_f as be,vD as bf,CD as bg,ra as bh,Sf as bi,$u as bj,Di as bk,GF as bl,YF as bm,JF as bn,QF as bo,XF as bp,ZF as bq,e3 as br,t3 as bs,n3 as bt,s3 as bu,i3 as bv,a3 as bw,r3 as bx,o3 as by,c3 as bz,Qe as c,zF as c$,cF as c0,dF as c1,uF as c2,_j as c3,mF as c4,tu as c5,Sj as c6,Cj as c7,Ej as c8,Nj as c9,xk as cA,eF as cB,ii as cC,_i as cD,qD as cE,pI as cF,RO as cG,WF as cH,iO as cI,aO as cJ,Kp as cK,LF as cL,rO as cM,lO as cN,gO as cO,fO as cP,Pk as cQ,yk as cR,Ni as cS,wk as cT,jk as cU,kk as cV,Nk as cW,Sk as cX,$O as cY,OF as cZ,FF as c_,iF as ca,$l as cb,Vy as cc,qa as cd,Va as ce,cN as cf,Cw as cg,Ew as ch,dk as ci,uk as cj,S3 as ck,HO as cl,BO as cm,C3 as cn,qO as co,XO as cp,JO as cq,VO as cr,YO as cs,WO as ct,QO as cu,KO as cv,GO as cw,Ix as cx,bk as cy,ZO as cz,DF as d,bF as d$,Fi as d0,Y3 as d1,Q3 as d2,KF as d3,cO as d4,dd as d5,ws as d6,CI as d7,n$ as d8,i$ as d9,kd as dA,Uu as dB,NF as dC,CF as dD,pd as dE,Bs as dF,Vv as dG,x3 as dH,MF as dI,no as dJ,SP as dK,SF as dL,RF as dM,PF as dN,Nf as dO,kF as dP,wF as dQ,fF as dR,gF as dS,B4 as dT,_F as dU,vF as dV,xF as dW,aj as dX,yF as dY,jF as dZ,v3 as d_,qi as da,nd as db,r$ as dc,uO as dd,oO as de,mO as df,dO as dg,hO as dh,pO as di,ua as dj,nz as dk,SS as dl,zl as dm,X3 as dn,Uh as dp,Z3 as dq,ez as dr,MO as ds,u3 as dt,h3 as du,g3 as dv,p3 as dw,m3 as dx,f3 as dy,b3 as dz,IF as e,y3 as e0,bd as e1,E3 as e2,j3 as e3,k3 as e4,N3 as e5,w3 as e6,VF as e7,J3 as e8,DO as e9,TO as ea,IO as eb,Py as ec,OO as ed,FO as ee,LO as ef,Wa as f,$F as g,Os as h,ba as i,Dn as j,Hd as k,_3 as l,Ns as m,Qj as n,pF as o,ri as p,sF as q,V4 as r,gi as s,tF as t,Mi as u,nF as v,TF as w,oi as x,SD as y,ss as z};