@runfusion/fusion 0.23.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.
- package/dist/bin.js +26610 -20597
- package/dist/client/assets/AgentDetailView-BwJaLqZh.css +1 -0
- package/dist/client/assets/AgentDetailView-gy_5SUj2.js +18 -0
- package/dist/client/assets/AgentsView-BkB9FiMT.js +29 -0
- package/dist/client/assets/{AgentsView-DSGQWObq.css → AgentsView-CV3vm7Qk.css} +1 -1
- package/dist/client/assets/ChatView-B_-B8fqu.js +1 -0
- package/dist/client/assets/ChatView-DwJAd5G1.css +1 -0
- package/dist/client/assets/{DevServerView-C9lzHrcT.js → DevServerView-BkvtjZBa.js} +1 -1
- package/dist/client/assets/{DirectoryPicker-aVdFaV37.js → DirectoryPicker-BK-KbnhP.js} +1 -1
- package/dist/client/assets/{DocumentsView-DIpg3NSP.js → DocumentsView-BEg1CQAk.js} +1 -1
- package/dist/client/assets/{DocumentsView-BrhyOdeE.css → DocumentsView-gv4zG3aT.css} +1 -1
- package/dist/client/assets/EvalsView-Berf9bQm.js +1 -0
- package/dist/client/assets/EvalsView-CUNJ1TLc.css +1 -0
- package/dist/client/assets/{agentSkills-DDHJnrkn.css → ExperimentalAgentOnboardingModal-B-APN_lM.css} +1 -1
- package/dist/client/assets/ExperimentalAgentOnboardingModal-jcInE50G.js +499 -0
- package/dist/client/assets/InsightsView-B0J4mhzV.css +1 -0
- package/dist/client/assets/InsightsView-BX5bSF1J.js +11 -0
- package/dist/client/assets/{MemoryView-nXlTqebk.js → MemoryView-CKElJY_3.js} +2 -2
- package/dist/client/assets/NodesView-DLUOBLf6.js +14 -0
- package/dist/client/assets/NodesView-DT4pXowv.css +1 -0
- package/dist/client/assets/{PiExtensionsManager-Buopv-jb.js → PiExtensionsManager-COlJf0Kx.js} +2 -2
- package/dist/client/assets/PluginManager-CfW55BF4.js +1 -0
- package/dist/client/assets/PluginManager-DtRQXia5.css +1 -0
- package/dist/client/assets/{ResearchView-_BHXUv2j.js → ResearchView-B256Lr8I.js} +1 -1
- package/dist/client/assets/SettingsModal-BeA_nQtW.js +31 -0
- package/dist/client/assets/SettingsModal-DzsLquBu.css +1 -0
- package/dist/client/assets/{SettingsModal-C89Ikhfm.js → SettingsModal-yRqM4DV8.js} +1 -1
- package/dist/client/assets/SetupWizardModal-uUZk3TKT.js +1 -0
- package/dist/client/assets/{SkillsView-hDpTBdFT.js → SkillsView-CP8JX0P_.js} +1 -1
- package/dist/client/assets/TodoView-Cx9cVhq7.css +1 -0
- package/dist/client/assets/TodoView-DCRIkDZ-.js +6 -0
- package/dist/client/assets/createLucideIcon-BazL2hk5.js +21 -0
- package/dist/client/assets/dashboard-view-BkTMSZYn.css +1 -0
- package/dist/client/assets/dashboard-view-CyWN-d02.js +63 -0
- package/dist/client/assets/dashboard-view-lR7YYmSC.js +21 -0
- package/dist/client/assets/{folder-open-usZkXdq2.js → folder-open-DHjELt8-.js} +1 -1
- package/dist/client/assets/index-CQyVRLOb.js +692 -0
- package/dist/client/assets/index-CxA2Nn0_.css +1 -0
- package/dist/client/assets/projectDetection-G3XuxD2X.js +1 -0
- package/dist/client/assets/{star-BAT_ObKE.js → star-DYesq1AV.js} +1 -1
- package/dist/client/assets/{upload-BC2YKNEV.js → upload-DTWF3Db5.js} +1 -1
- package/dist/client/assets/{users-Dkd4rtrN.js → users--syrel4l.js} +1 -1
- package/dist/client/index.html +12 -20
- package/dist/client/theme-data.css +106 -0
- package/dist/client/version.json +1 -1
- package/dist/droid-cli/package.json +1 -1
- package/dist/extension.js +14287 -9568
- package/dist/pi-claude-cli/package.json +1 -1
- package/dist/plugins/fusion-plugin-cursor-runtime/bundled.js +218 -0
- package/dist/plugins/fusion-plugin-cursor-runtime/manifest.json +6 -0
- package/dist/plugins/fusion-plugin-cursor-runtime/package.json +11 -0
- package/dist/plugins/fusion-plugin-dependency-graph/manifest.json +1 -1
- package/dist/plugins/fusion-plugin-dependency-graph/package.json +6 -4
- package/dist/plugins/fusion-plugin-dependency-graph/src/DependencyGraph.css +58 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/DependencyGraph.tsx +301 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/GraphHighlight.css +27 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/GraphTaskNode.css +157 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/GraphTaskNode.tsx +126 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/GraphToolbar.css +35 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/GraphToolbar.tsx +36 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/DependencyGraph.highlighting.test.tsx +112 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/DependencyGraph.persistence.test.tsx +115 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/DependencyGraph.test.tsx +128 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/GraphTaskNode.drag.test.tsx +82 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/GraphTaskNode.test.tsx +307 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/GraphToolbar.test.tsx +60 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/edges.test.tsx +75 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/filtering.test.tsx +62 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/filters.test.ts +78 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/graphPositionStorage.test.ts +95 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/host-integration.test.ts +74 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/index.test.ts +58 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/interactions.test.tsx +121 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/layout.test.ts +70 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/persistence.test.tsx +89 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/useGraphData.test.ts +86 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/useGraphInteraction.test.ts +167 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/useGraphPositions.test.ts +66 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/useNodeDrag.test.ts +81 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/dashboard-interop.d.ts +35 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/dashboard-view.tsx +19 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/edges.tsx +70 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/filters.ts +8 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/hooks/__tests__/useDependencyChain.test.ts +53 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/hooks/useDependencyChain.ts +60 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/hooks/useGraphPositions.ts +45 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/hooks/useNodeDrag.ts +114 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/index.ts +1 -2
- package/dist/plugins/fusion-plugin-dependency-graph/src/layout.ts +91 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/styles/drag.css +15 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/types.ts +21 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/useGraphData.ts +17 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/useGraphInteraction.ts +292 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/utils/graphPositionStorage.ts +65 -0
- package/dist/plugins/fusion-plugin-droid-runtime/bundled.js +136680 -0
- package/dist/plugins/fusion-plugin-droid-runtime/manifest.json +13 -0
- package/dist/plugins/fusion-plugin-droid-runtime/mcp-schema-server.cjs +49 -0
- package/dist/plugins/fusion-plugin-droid-runtime/package.json +11 -0
- package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-openclaw-runtime/bundled.js +93 -6
- package/dist/plugins/fusion-plugin-openclaw-runtime/mcp-schema-server.cjs +59 -0
- package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-reports/manifest.json +33 -0
- package/dist/plugins/fusion-plugin-reports/package.json +26 -0
- package/dist/plugins/fusion-plugin-reports/src/__tests__/manifest.test.ts +51 -0
- package/dist/plugins/fusion-plugin-reports/src/__tests__/review-panel.test.ts +166 -0
- package/dist/plugins/fusion-plugin-reports/src/__tests__/settings.test.ts +157 -0
- package/dist/plugins/fusion-plugin-reports/src/index.ts +41 -0
- package/dist/plugins/fusion-plugin-reports/src/review-panel.ts +294 -0
- package/dist/plugins/fusion-plugin-reports/src/review-types.ts +75 -0
- package/dist/plugins/fusion-plugin-reports/src/settings.ts +105 -0
- package/dist/plugins/fusion-plugin-roadmap/manifest.json +16 -0
- package/dist/plugins/fusion-plugin-roadmap/package.json +48 -0
- package/dist/plugins/fusion-plugin-roadmap/src/__tests__/api-client.test.ts +101 -0
- package/dist/plugins/fusion-plugin-roadmap/src/__tests__/index.test.ts +92 -0
- package/dist/plugins/fusion-plugin-roadmap/src/__tests__/roadmap-routes.test.ts +48 -0
- package/dist/plugins/fusion-plugin-roadmap/src/__tests__/roadmap-suggestions.test.ts +31 -0
- package/dist/plugins/fusion-plugin-roadmap/src/dashboard/RoadmapsView.css +1299 -0
- package/dist/plugins/fusion-plugin-roadmap/src/dashboard/RoadmapsView.tsx +2559 -0
- package/dist/plugins/fusion-plugin-roadmap/src/dashboard/__tests__/RoadmapsView.test.tsx +1144 -0
- package/dist/plugins/fusion-plugin-roadmap/src/dashboard/__tests__/useRoadmaps.test.ts +1756 -0
- package/dist/plugins/fusion-plugin-roadmap/src/dashboard/api.ts +70 -0
- package/dist/plugins/fusion-plugin-roadmap/src/dashboard/test-setup.ts +7 -0
- package/dist/plugins/fusion-plugin-roadmap/src/dashboard/types.ts +1 -0
- package/dist/plugins/fusion-plugin-roadmap/src/dashboard/useConfirm.ts +8 -0
- package/dist/plugins/fusion-plugin-roadmap/src/dashboard/useRoadmaps.ts +1188 -0
- package/dist/plugins/fusion-plugin-roadmap/src/dashboard/useViewportMode.ts +20 -0
- package/dist/plugins/fusion-plugin-roadmap/src/dashboard-view.tsx +6 -0
- package/dist/plugins/fusion-plugin-roadmap/src/index.ts +74 -0
- package/dist/plugins/fusion-plugin-roadmap/src/roadmap-routes.ts +1 -0
- package/dist/plugins/fusion-plugin-roadmap/src/roadmap-schema.ts +41 -0
- package/dist/plugins/fusion-plugin-roadmap/src/roadmap-suggestions.d.ts +15 -0
- package/dist/plugins/fusion-plugin-roadmap/src/roadmap-suggestions.ts +15 -0
- package/dist/plugins/fusion-plugin-roadmap/src/roadmap-types.d.ts +283 -0
- package/dist/plugins/fusion-plugin-roadmap/src/roadmap-types.d.ts.map +1 -0
- package/dist/plugins/fusion-plugin-roadmap/src/roadmap-types.js +21 -0
- package/dist/plugins/fusion-plugin-roadmap/src/roadmap-types.js.map +1 -0
- package/dist/plugins/fusion-plugin-roadmap/src/roadmap-types.ts +310 -0
- package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-routes.d.ts +5 -0
- package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-routes.d.ts.map +1 -0
- package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-routes.js +361 -0
- package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-routes.js.map +1 -0
- package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-routes.ts +408 -0
- package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-suggestions.d.ts +68 -0
- package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-suggestions.d.ts.map +1 -0
- package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-suggestions.js +300 -0
- package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-suggestions.js.map +1 -0
- package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-suggestions.ts +381 -0
- package/dist/plugins/fusion-plugin-roadmap/src/server/index.d.ts +3 -0
- package/dist/plugins/fusion-plugin-roadmap/src/server/index.ts +1 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/__tests__/roadmap-handoff.test.ts +445 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/__tests__/roadmap-ordering.test.ts +334 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/__tests__/roadmap-store.test.ts +1318 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-handoff.ts +163 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-ordering.d.ts +37 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-ordering.d.ts.map +1 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-ordering.js +188 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-ordering.js.map +1 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-ordering.ts +311 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-store.d.ts +299 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-store.d.ts.map +1 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-store.js +765 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-store.js.map +1 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-store.ts +1001 -0
- package/dist/plugins/fusion-plugin-whatsapp-chat/manifest.json +8 -0
- package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +34 -0
- package/dist/plugins/fusion-plugin-whatsapp-chat/src/__tests__/auth-state.test.ts +99 -0
- package/dist/plugins/fusion-plugin-whatsapp-chat/src/__tests__/connection.test.ts +145 -0
- package/dist/plugins/fusion-plugin-whatsapp-chat/src/__tests__/index.test.ts +216 -0
- package/dist/plugins/fusion-plugin-whatsapp-chat/src/__tests__/reply.test.ts +52 -0
- package/dist/plugins/fusion-plugin-whatsapp-chat/src/auth-state.ts +89 -0
- package/dist/plugins/fusion-plugin-whatsapp-chat/src/connection.ts +253 -0
- package/dist/plugins/fusion-plugin-whatsapp-chat/src/index.ts +262 -0
- package/dist/plugins/fusion-plugin-whatsapp-chat/src/qrcode.d.ts +1 -0
- package/dist/plugins/fusion-plugin-whatsapp-chat/src/reply.ts +37 -0
- package/package.json +2 -2
- package/skill/fusion/SKILL.md +2 -2
- package/skill/fusion/references/engine-tools.md +3 -0
- package/skill/fusion/references/extension-tools.md +39 -0
- package/skill/fusion/references/fusion-capabilities.md +3 -0
- package/dist/client/assets/AgentDetailView-C1XceMgi.js +0 -18
- package/dist/client/assets/AgentDetailView-CeO_1MK7.css +0 -1
- package/dist/client/assets/AgentsView-Deh125ss.js +0 -527
- package/dist/client/assets/ChatView-7D_RQDqT.js +0 -1
- package/dist/client/assets/InsightsView-AWo5o_81.css +0 -1
- package/dist/client/assets/InsightsView-jKjEFAx_.js +0 -11
- package/dist/client/assets/NodesView-Di2SvOhg.js +0 -14
- package/dist/client/assets/NodesView-fXqDk9ur.css +0 -1
- package/dist/client/assets/PluginManager-B9-NbQ8f.js +0 -1
- package/dist/client/assets/PluginManager-C1DbPaar.css +0 -1
- package/dist/client/assets/RoadmapsView-DHWjUoc8.js +0 -6
- package/dist/client/assets/SettingsModal-DHitIpsa.css +0 -1
- package/dist/client/assets/SettingsModal-DR_yirvK.js +0 -31
- package/dist/client/assets/SetupWizardModal-BtDMY9pa.js +0 -1
- package/dist/client/assets/agentSkills-B-w5wFHh.js +0 -1
- package/dist/client/assets/index-Bc6ZdGMz.css +0 -1
- package/dist/client/assets/index-D__RMku8.js +0 -694
- package/dist/plugins/fusion-plugin-dependency-graph/src/DependencyGraphView.css +0 -141
- package/dist/plugins/fusion-plugin-dependency-graph/src/DependencyGraphView.tsx +0 -428
- package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/DependencyGraphView.test.tsx +0 -261
- package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/storage.test.ts +0 -41
- package/dist/plugins/fusion-plugin-dependency-graph/src/storage.ts +0 -22
- /package/dist/client/assets/{RoadmapsView-DdGlfuu-.css → dashboard-view-DdGlfuu-.css} +0 -0
|
@@ -0,0 +1,692 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentDetailView-gy_5SUj2.js","assets/vendor-react-K0fH_qHe.js","assets/star-DYesq1AV.js","assets/ExperimentalAgentOnboardingModal-jcInE50G.js","assets/ExperimentalAgentOnboardingModal-B-APN_lM.css","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/AgentDetailView-BwJaLqZh.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/TodoView-DCRIkDZ-.js","assets/TodoView-Cx9cVhq7.css","assets/SetupWizardModal-uUZk3TKT.js","assets/DirectoryPicker-BK-KbnhP.js","assets/folder-open-DHjELt8-.js","assets/DirectoryPicker-DzKVmxOf.css","assets/projectDetection-G3XuxD2X.js","assets/SetupWizardModal-CGYGKurR.css","assets/SettingsModal-BeA_nQtW.js","assets/SettingsModal-yRqM4DV8.js","assets/SettingsModal-DzsLquBu.css","assets/users--syrel4l.js","assets/SettingsModal-BNSrO1M9.css","assets/dashboard-view-lR7YYmSC.js","assets/createLucideIcon-BazL2hk5.js","assets/dashboard-view-BkTMSZYn.css","assets/dashboard-view-CyWN-d02.js","assets/dashboard-view-DdGlfuu-.css","assets/AgentsView-BkB9FiMT.js","assets/upload-DTWF3Db5.js","assets/AgentsView-CV3vm7Qk.css","assets/DocumentsView-BEg1CQAk.js","assets/DocumentsView-gv4zG3aT.css","assets/InsightsView-BX5bSF1J.js","assets/InsightsView-B0J4mhzV.css","assets/ResearchView-B256Lr8I.js","assets/ResearchView-BzCcDAS4.css","assets/EvalsView-Berf9bQm.js","assets/EvalsView-CUNJ1TLc.css","assets/NodesView-DLUOBLf6.js","assets/NodesView-DT4pXowv.css","assets/ChatView-B_-B8fqu.js","assets/ChatView-DwJAd5G1.css","assets/SkillsView-CP8JX0P_.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-CKElJY_3.js","assets/MemoryView-DiajLXby.css","assets/DevServerView-BkvtjZBa.js","assets/DevServerView-DlZpuAnj.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as i,j as t,R as kl,a as va,g as ig,c as bv}from"./vendor-react-K0fH_qHe.js";import"./vendor-xterm-DzcZoU0P.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))a(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&a(l)}).observe(document,{childList:!0,subtree:!0});function s(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function a(r){if(r.ep)return;r.ep=!0;const o=s(r);fetch(r.href,o)}})();/**
|
|
3
|
+
* @license lucide-react v1.7.0 - ISC
|
|
4
|
+
*
|
|
5
|
+
* This source code is licensed under the ISC license.
|
|
6
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
7
|
+
*/const ag=(...e)=>e.filter((n,s,a)=>!!n&&n.trim()!==""&&a.indexOf(n)===s).join(" ").trim();/**
|
|
8
|
+
* @license lucide-react v1.7.0 - ISC
|
|
9
|
+
*
|
|
10
|
+
* This source code is licensed under the ISC license.
|
|
11
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
12
|
+
*/const xv=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/**
|
|
13
|
+
* @license lucide-react v1.7.0 - ISC
|
|
14
|
+
*
|
|
15
|
+
* This source code is licensed under the ISC license.
|
|
16
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
17
|
+
*/const vv=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 Vu=e=>{const n=vv(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 dc={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 yv=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},wv=i.createContext({}),kv=()=>i.useContext(wv),jv=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=""}=kv()??{},g=a??h?Number(s??m)*24/Number(n??u):s??m;return i.createElement("svg",{ref:d,...dc,width:n??u??dc.width,height:n??u??dc.height,stroke:e??f,strokeWidth:g,className:ag("lucide",p,r),...!o&&!yv(c)&&{"aria-hidden":"true"},...c},[...l.map(([x,w])=>i.createElement(x,w)),...Array.isArray(o)?o:[o]])});/**
|
|
33
|
+
* @license lucide-react v1.7.0 - ISC
|
|
34
|
+
*
|
|
35
|
+
* This source code is licensed under the ISC license.
|
|
36
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
37
|
+
*/const tt=(e,n)=>{const s=i.forwardRef(({className:a,...r},o)=>i.createElement(jv,{ref:o,iconNode:n,className:ag(`lucide-${xv(Vu(e))}`,`lucide-${e}`,a),...r}));return s.displayName=Vu(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 Nv=[["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"}]],Ks=tt("activity",Nv);/**
|
|
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 Sv=[["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"}]],Cv=tt("archive-restore",Sv);/**
|
|
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 Ev=[["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"}]],xo=tt("archive",Ev);/**
|
|
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 _v=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],vo=tt("arrow-down",_v);/**
|
|
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 Mv=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],Aa=tt("arrow-left",Mv);/**
|
|
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 Av=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],yo=tt("arrow-right",Av);/**
|
|
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 Pv=[["path",{d:"m21 16-4 4-4-4",key:"f6ql7i"}],["path",{d:"M17 20V4",key:"1ejh1v"}],["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}]],rg=tt("arrow-up-down",Pv);/**
|
|
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 Rv=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],ka=tt("arrow-up",Rv);/**
|
|
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 Iv=[["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"}]],Tv=tt("book-open",Iv);/**
|
|
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 $v=[["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"}]],Tn=tt("bot",$v);/**
|
|
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 Dv=[["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"}]],kd=tt("box",Dv);/**
|
|
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 Lv=[["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"}]],oo=tt("brain",Lv);/**
|
|
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 Ov=[["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"}]],og=tt("calendar",Ov);/**
|
|
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 zv=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],Wu=tt("check-check",zv);/**
|
|
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 Fv=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],hs=tt("check",Fv);/**
|
|
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 Uv=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],rn=tt("chevron-down",Uv);/**
|
|
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 Bv=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],ql=tt("chevron-left",Bv);/**
|
|
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 Hv=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Mn=tt("chevron-right",Hv);/**
|
|
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 qv=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],Ei=tt("chevron-up",qv);/**
|
|
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 Vv=[["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"}]],Ps=tt("circle-alert",Vv);/**
|
|
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 Wv=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],$n=tt("circle-check-big",Wv);/**
|
|
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 Kv=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],Vl=tt("circle-dot",Kv);/**
|
|
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 Gv=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]],jd=tt("circle-question-mark",Gv);/**
|
|
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 Jv=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],Yv=tt("circle-stop",Jv);/**
|
|
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 Qv=[["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"}]],wo=tt("circle-x",Qv);/**
|
|
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 Xv=[["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"}]],Zv=tt("clipboard-list",Xv);/**
|
|
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 ey=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],Hi=tt("clock",ey);/**
|
|
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 ty=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],lg=tt("code",ty);/**
|
|
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 ny=[["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"}]],Ku=tt("columns-3",ny);/**
|
|
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 sy=[["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"}]],sa=tt("copy",sy);/**
|
|
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 iy=[["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"}]],cg=tt("cpu",iy);/**
|
|
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 ay=[["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"}]],ry=tt("download",ay);/**
|
|
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 oy=[["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"}]],ly=tt("ellipsis-vertical",oy);/**
|
|
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 cy=[["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"}]],Nd=tt("ellipsis",cy);/**
|
|
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 dy=[["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"}]],dg=tt("external-link",dy);/**
|
|
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 uy=[["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"}]],ou=tt("eye-off",uy);/**
|
|
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 my=[["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"}]],kr=tt("eye",my);/**
|
|
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 hy=[["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"}]],hi=tt("file-code",hy);/**
|
|
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 py=[["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"}]],Sd=tt("file-diff",py);/**
|
|
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 fy=[["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"}]],gy=tt("file-minus",fy);/**
|
|
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 by=[["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"}]],ug=tt("file-pen",by);/**
|
|
243
|
+
* @license lucide-react v1.7.0 - ISC
|
|
244
|
+
*
|
|
245
|
+
* This source code is licensed under the ISC license.
|
|
246
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
247
|
+
*/const xy=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],vy=tt("file-plus",xy);/**
|
|
248
|
+
* @license lucide-react v1.7.0 - ISC
|
|
249
|
+
*
|
|
250
|
+
* This source code is licensed under the ISC license.
|
|
251
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
252
|
+
*/const yy=[["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"}]],wy=tt("file-question-mark",yy);/**
|
|
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 ky=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],ia=tt("file-text",ky);/**
|
|
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 jy=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"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"}]],Ny=tt("file-type",jy);/**
|
|
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 Sy=[["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"}]],mg=tt("file",Sy);/**
|
|
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 Cy=[["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"}]],Ey=tt("flag",Cy);/**
|
|
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 _y=[["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"}]],Cd=tt("folder-git-2",_y);/**
|
|
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 My=[["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"}]],Gu=tt("folder-root",My);/**
|
|
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 Ay=[["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"}]],bs=tt("folder",Ay);/**
|
|
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 Py=[["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"}]],jl=tt("funnel",Py);/**
|
|
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 Ry=[["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"}]],Us=tt("git-branch",Ry);/**
|
|
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 Iy=[["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"}]],ko=tt("git-commit-horizontal",Iy);/**
|
|
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 Ty=[["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"}]],hg=tt("git-merge",Ty);/**
|
|
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 $y=[["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"}]],Ws=tt("git-pull-request",$y);/**
|
|
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 Dy=[["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"}]],Wl=tt("globe",Dy);/**
|
|
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 Ly=[["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"}]],Kl=tt("grid-3x3",Ly);/**
|
|
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 Oy=[["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"}]],Gl=tt("grip-vertical",Oy);/**
|
|
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 zy=[["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"}]],Fy=tt("hard-drive",zy);/**
|
|
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 Uy=[["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"}]],By=tt("heart",Uy);/**
|
|
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 Hy=[["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"}]],lo=tt("history",Hy);/**
|
|
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 qy=[["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"}]],ya=tt("inbox",qy);/**
|
|
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 Vy=[["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"}]],pg=tt("key",Vy);/**
|
|
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 Wy=[["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"}]],Ky=tt("keyboard",Wy);/**
|
|
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 Gy=[["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"}]],ja=tt("layers",Gy);/**
|
|
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 Jy=[["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"}]],aa=tt("layout-grid",Jy);/**
|
|
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 Yy=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]],_i=tt("lightbulb",Yy);/**
|
|
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 Qy=[["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"}]],cr=tt("link",Qy);/**
|
|
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 Xy=[["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"}]],Zy=tt("list-checks",Xy);/**
|
|
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 ew=[["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"}]],tw=tt("list-ordered",ew);/**
|
|
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 nw=[["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"}]],sw=tt("list-plus",nw);/**
|
|
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 iw=[["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"}]],Jl=tt("list-tree",iw);/**
|
|
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 aw=[["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"}]],Ed=tt("list",aw);/**
|
|
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 rw=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],xt=tt("loader-circle",rw);/**
|
|
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 ow=[["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"}]],Yl=tt("lock",ow);/**
|
|
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 lw=[["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"}]],Na=tt("mail",lw);/**
|
|
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 cw=[["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"}]],dw=tt("map",cw);/**
|
|
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 uw=[["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"}]],Ql=tt("maximize-2",uw);/**
|
|
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 mw=[["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"}]],hw=tt("message-square-plus",mw);/**
|
|
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 pw=[["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"}]],Ui=tt("message-square",pw);/**
|
|
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 fw=[["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"}]],jo=tt("minimize-2",fw);/**
|
|
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 gw=[["path",{d:"M5 12h14",key:"1ays0h"}]],bw=tt("minus",gw);/**
|
|
448
|
+
* @license lucide-react v1.7.0 - ISC
|
|
449
|
+
*
|
|
450
|
+
* This source code is licensed under the ISC license.
|
|
451
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
452
|
+
*/const xw=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],dr=tt("monitor",xw);/**
|
|
453
|
+
* @license lucide-react v1.7.0 - ISC
|
|
454
|
+
*
|
|
455
|
+
* This source code is licensed under the ISC license.
|
|
456
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
457
|
+
*/const vw=[["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"}]],yw=tt("move",vw);/**
|
|
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 ww=[["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"}]],kw=tt("network",ww);/**
|
|
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 jw=[["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"}]],_d=tt("package",jw);/**
|
|
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 Nw=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]],fg=tt("paperclip",Nw);/**
|
|
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 Sw=[["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"}]],pi=tt("pause",Sw);/**
|
|
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 Cw=[["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"}]],Ds=tt("pencil",Cw);/**
|
|
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 Ew=[["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"}]],Yn=tt("play",Ew);/**
|
|
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 _w=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],bn=tt("plus",_w);/**
|
|
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 Mw=[["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"}]],Aw=tt("puzzle",Mw);/**
|
|
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 Pw=[["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"}]],gg=tt("radio",Pw);/**
|
|
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 Rw=[["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"}]],rs=tt("refresh-cw",Rw);/**
|
|
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 Iw=[["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"}]],Ju=tt("rocket",Iw);/**
|
|
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 Tw=[["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"}]],$w=tt("rotate-ccw",Tw);/**
|
|
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 Dw=[["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"}]],Lw=tt("rotate-cw",Dw);/**
|
|
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 Ow=[["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"}]],bg=tt("save",Ow);/**
|
|
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 zw=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Fi=tt("search",zw);/**
|
|
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 Fw=[["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"}]],wa=tt("send",Fw);/**
|
|
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 Uw=[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]],co=tt("server",Uw);/**
|
|
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 Bw=[["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"}]],to=tt("settings",Bw);/**
|
|
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 Hw=[["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"}]],qw=tt("shield-alert",Hw);/**
|
|
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 Vw=[["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"}]],Ww=tt("shield",Vw);/**
|
|
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 Kw=[["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"}]],Gw=tt("skull",Kw);/**
|
|
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 Jw=[["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"}]],ps=tt("sparkles",Jw);/**
|
|
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 Yw=[["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"}]],lu=tt("square-check-big",Yw);/**
|
|
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 Qw=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Si=tt("square",Qw);/**
|
|
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 Xw=[["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"}]],vs=tt("target",Xw);/**
|
|
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 Zw=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],Bi=tt("terminal",Zw);/**
|
|
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 ek=[["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"}]],Nl=tt("text-wrap",ek);/**
|
|
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 tk=[["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"}]],vn=tt("trash-2",tk);/**
|
|
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 nk=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],sk=tt("trending-up",nk);/**
|
|
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 ik=[["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"}]],No=tt("triangle-alert",ik);/**
|
|
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 ak=[["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"}]],Yu=tt("unlink",ak);/**
|
|
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 rk=[["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"}]],Ka=tt("user",rk);/**
|
|
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 ok=[["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"}]],xg=tt("webhook",ok);/**
|
|
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 lk=[["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"}]],Sl=tt("workflow",lk);/**
|
|
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 ck=[["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"}]],Qu=tt("wrench",ck);/**
|
|
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 dk=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],nn=tt("x",dk);/**
|
|
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 uk=[["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"}]],Qn=tt("zap",uk),Md="fusion:version-reload",Ad="fusion:version-update";let cu=!0;function uc(e){cu=e}function mk(){try{if(sessionStorage.getItem(Ad))return sessionStorage.removeItem(Ad),!0}catch{}return!1}function du(e){if(sessionStorage.getItem(Md)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}if(sessionStorage.setItem(Md,"1"),!cu){console.info("[versionCheck] auto-reload disabled by setting, skipping reload:",e);return}console.info("[versionCheck] reloading:",e),window.location.reload()}function hk(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return/Failed to fetch dynamically imported module|error loading dynamically imported module|Importing a module script failed|is not a valid JavaScript MIME type|ChunkLoadError|Unable to preload (?:CSS|module) for/i.test(n)}function pk(e){return hk(e)?(du(`chunk load error: ${e?.message??e}`),!0):!1}async function fk(){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 gk(){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&&(cu=!1)}catch{}}const bk=6e4;let Xu=0,mc=!1;async function hc(){if(!(mc||document.visibilityState!=="visible")&&!(Date.now()-Xu<bk)){Xu=Date.now(),mc=!0;try{const e=await fk();if(e&&e!=="07e197adb-75a6a9df"){try{sessionStorage.setItem(Ad,"1")}catch{}du(`build version changed: 07e197adb-75a6a9df -> ${e}`)}}finally{mc=!1}}}function xk(){gk(),window.setTimeout(()=>sessionStorage.removeItem(Md),5e3),document.addEventListener("visibilitychange",()=>{hc()}),window.addEventListener("focus",()=>{hc()}),window.setTimeout(()=>void hc(),2e3)}class So 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),!pk(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(No,{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(So,{level:"page",onError:n,children:e})}function ga({children:e,onError:n}){return t.jsx(So,{level:"modal",onError:n,children:e})}function vk({children:e,onError:n}){return t.jsx(So,{level:"root",onError:n,children:e})}const yk="modulepreload",wk=function(e){return"/"+e},Zu={},gn=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=wk(u),u in Zu)return;Zu[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":yk,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)})},uu="fn.authToken",em="token",kk="fn_token";let ir,tm=!1,Cl=!1;const Pd="fn:auth-token-recovery-required";function jk(){try{const e=window.localStorage.getItem(uu);return e&&e.length>0?e:void 0}catch{return}}function vg(e){try{window.localStorage.setItem(uu,e)}catch{}}function Nk(){if(!(tm||typeof window>"u")){tm=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(em);if(!n)return;vg(n),e.searchParams.delete(em);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function ur(){if(ir!==void 0)return ir;const e=Nk();if(e)return ir=e,e;const n=jk();if(n)return ir=n,n}function Sk(e){ir=e,Cl=!1,vg(e)}function Ck(){ir=void 0,Cl=!1;try{window.localStorage.removeItem(uu)}catch{}}function nm(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function Ek(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function _k(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!Ek(e.protocol))return!1;const s=e.hostname===n.hostname,a=e.port===n.port,r=nm(e.protocol)===nm(n.protocol);return s&&a&&r}function Mk(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 Mi(e){const n=ur();if(!n||typeof window>"u")return e;const s=Mk(e);return!s||!_k(s.parsed)?e:(s.parsed.searchParams.set(kk,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function gi(e){const n=ur();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function Ak(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function Pk(){typeof window>"u"||Cl||(Cl=!0,window.dispatchEvent(new CustomEvent(Pd)))}async function Rk(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();Ak(a)&&Pk()}catch{}}function Ik(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,ur();const e=window.fetch.bind(window);window.fetch=function(s,a){const r=ur(),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=>(Rk(d),d))}}class yg extends Error{status;details;constructor(n,s,a){super(n),this.name="ApiRequestError",this.status=s,this.details=a}}function Tk(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function ws(e){return`/api${e}`}async function T(e,n={}){const s=ws(e),a=ur(),r=(()=>{if(a){const f=new Headers(n.headers??{});return f.has("Content-Type")||f.set("Content-Type","application/json"),gi(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")||Tk(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 yg(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function Bz(){return T("/health")}function Hz(){return T("/updates/check")}function $k(e,n,s,a,r){const o=new URLSearchParams;e!==void 0&&o.set("limit",String(e)),n!==void 0&&o.set("offset",String(n)),s&&o.set("projectId",s),a&&o.set("q",a),r&&o.set("includeArchived","1");const l=o.size>0?`?${o.toString()}`:"";return T(`/tasks${l}`)}async function Sa(e,n){const a=ws(W(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(a,{headers:gi({"Content-Type":"application/json"})}),l=await o.json();if(o.ok)return l;if(r===2)throw new Error(l.error||"Request failed")}throw new Error("Request failed")}function wg(e,n,s){const{title:a,description:r,column:o,dependencies:l,breakIntoSubtasks:c,enabledWorkflowSteps:d,assignedAgentId:u,modelPresetId:m,modelProvider:h,modelId:f,validatorModelProvider:p,validatorModelId:g,planningModelProvider:x,planningModelId:w,thinkingLevel:b,summarize:y,reviewLevel:S,executionMode:k,priority:C,source:v,nodeId:j,branch:P,baseBranch:U}=e;return Mo(W("/tasks",n),{method:"POST",nodeId:s?.transportNodeId,localNodeId:s?.localNodeId,body:JSON.stringify({title:a,description:r,column:o,dependencies:l,breakIntoSubtasks:c,enabledWorkflowSteps:d,assignedAgentId:u,modelPresetId:m,modelProvider:h,modelId:f,validatorModelProvider:p,validatorModelId:g,planningModelProvider:x,planningModelId:w,thinkingLevel:b,summarize:y,reviewLevel:S,executionMode:k,priority:C,source:v,nodeId:j,branch:P,baseBranch:U})})}function mi(e,n,s){return T(W(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Dk(e,n,s,a,r,o,l,c,d){return T(W("/tasks/batch-update-models",d),{method:"POST",body:JSON.stringify({taskIds:e,modelProvider:n,modelId:s,validatorModelProvider:a,validatorModelId:r,planningModelProvider:o,planningModelId:l,nodeId:c})})}function Lk(e,n,s,a){return T(W(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n,...typeof a=="object"&&a?.preserveProgress?{preserveProgress:!0}:{}})})}function Ok(e,n,s){const a=new URLSearchParams;s?.removeDependencyReferences&&a.set("removeDependencyReferences","true");const r=a.size>0?`?${a.toString()}`:"";return T(W(`/tasks/${e}${r}`,n),{method:"DELETE"})}function zk(e,n){return T(W(`/tasks/${e}/merge`,n),{method:"POST"})}function Fk(e,n){return T(W(`/tasks/${e}/retry`,n),{method:"POST"})}function Uk(e,n){return T(W(`/tasks/${e}/reset`,n),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirm:!0})})}function Bk(e,n){return T(W(`/tasks/${e}/duplicate`,n),{method:"POST"})}function kg(e,n){return T(W(`/tasks/${e}/pause`,n),{method:"POST"})}function Hk(e,n){return T(W(`/tasks/${e}/unpause`,n),{method:"POST"})}function qk(e,n){return T(W(`/tasks/${e}/archive`,n),{method:"POST"})}function Vk(e,n){return T(W(`/tasks/${e}/unarchive`,n),{method:"POST"})}function Wk(e){return T(W("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function Kk(e,n){return T(W(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function Gk(e,n){return T(W(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function Jk(e){return T(W("/config",e))}function Xl(e){return T(W("/settings",e))}function Do(e,n){return T(W("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function Yk(e){return T(W("/update-check",e))}function qz(e){return T(W("/remote/settings",e))}function Vz(e,n){return T(W("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function Wz(e){return T(W("/remote/status",e))}function Kz(e){return T(W("/remote/install-cloudflared",e),{method:"POST"})}function Gz(e){return T(W("/remote/tunnel/start",e),{method:"POST"})}function Jz(e){return T(W("/remote/tunnel/stop",e),{method:"POST"})}function Yz(e){return T(W("/remote/tunnel/kill-external",e),{method:"POST"})}function Qz(e){return T(W("/remote/token/persistent/regenerate",e),{method:"POST"})}function Xz(e,n){return T(W("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function jg(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 Zz(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:a}=e,r=jg(null,s,a);return T(W(`/remote/url${r}`,n))}function eF(e="text",n={}){const{projectId:s,tokenType:a="persistent",ttlMs:r}=n,o=jg(e,a,r);return T(W(`/remote/qr${o}`,s))}function tF(e){return T(W("/memory",e))}function nF(e,n){return T(W("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function sF(e){return T(W("/memory/files",e))}function iF(e,n){const s=`path=${encodeURIComponent(e)}`;return T(W(`/memory/file?${s}`,n))}function aF(e,n,s){return T(W("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function rF(e,n){let s,a=n;if(n!==void 0)s=e;else if(typeof e=="string"&&e.trim().length>0){const r=e.trim();r.includes("/")||r.endsWith(".md")||r.startsWith(".")?s=r:a=r}return T(W("/memory/compact",a),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function oF(e){return T(W("/memory/dream",e),{method:"POST"})}function lF(e){return T(W("/memory/insights",e))}function cF(e,n){return T(W("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function dF(e){return T(W("/memory/extract",e),{method:"POST"})}function uF(e){return T(W("/memory/audit",e))}function mF(e){return T(W("/memory/stats",e))}function hF(e){return T(W("/memory/backend",e))}function pF(e){return T(W("/memory/install-qmd",e),{method:"POST"})}function fF(e,n){return T(W("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function Pa(){return T("/settings/global")}function kn(e){return T("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function gF(e){return T(W("/settings/scopes",e))}function bF(e){return T(W("/settings/pi-extensions",e))}function xF(e,n){return T(W("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function vF(e,n,s){return T(W("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function yF(){return T("/pi-settings")}async function wF(e){return T("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function kF(e){return T("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function jF(e){return T(W("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function Zl(e,n,s){const a=new FormData;a.append("file",n);const r=await fetch(ws(W(`/tasks/${e}/attachments`,s)),{method:"POST",headers:gi(),body:a}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function Qk(e,n,s){return T(W(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function sm(e,n,s){const a=new URLSearchParams;s?.limit!==void 0&&a.set("limit",String(s.limit)),s?.offset!==void 0&&a.set("offset",String(s.offset));const r=a.toString()?`?${a.toString()}`:"",o=W(`/tasks/${e}/logs${r}`,n),l=await fetch(ws(o),{headers:gi()});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 Xk(e,n,s,a){return T(W(`/tasks/${e}/comments/${n}`,a),{method:"PATCH",body:JSON.stringify({text:s})})}function Zk(e,n,s){return T(W(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function ej(e,n){return T(W(`/tasks/${e}/documents`,n))}function tj(e,n,s){return T(W(`/tasks/${e}/documents/${n}/revisions`,s))}async function NF(e,n){const s=new URLSearchParams;e?.q&&s.set("q",e.q),e?.limit!==void 0&&s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset));const a=s.toString(),r=`/documents${a?`?${a}`:""}`;return T(W(r,n))}function SF(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const a=s.toString(),r=`/files/markdown-list${a?`?${a}`:""}`;return T(W(r,e))}function im(e,n,s,a,r){return T(W(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:a?.author,metadata:a?.metadata})})}function nj(e,n,s){return T(W(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function sj(e,n,s){return T(W(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function ij(e,n,s){return T(W(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function aj(e,n){return T(W(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function rj(e,n,s){return T(W(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Os(){return T("/models")}function oj(){return T("/usage")}function lj(){return T("/providers/claude-cli/status")}function cj(){return T("/system/fn-binary/status")}function dj(){return T("/system/fn-binary/install",{method:"POST"})}function uj(){return T("/providers/droid-cli/status")}function mj(){return T("/providers/cursor-cli/status")}function hj(){return T("/providers/llama-cpp/status")}async function CF(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return T(`/providers/hermes/status${n}`)}async function EF(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await T(`/providers/hermes/profiles${n}`)).profiles??[]}async function _F(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return T(`/providers/openclaw/status${n}`)}async function MF(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),T(`/providers/paperclip/status?${n.toString()}`)}async function AF(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),(await T(`/providers/paperclip/companies?${n.toString()}`)).companies??[]}async function PF(e){const n=new URLSearchParams({apiUrl:e.apiUrl,companyId:e.companyId});return e.apiKey&&n.set("apiKey",e.apiKey),(await T(`/providers/paperclip/agents?${n.toString()}`)).agents??[]}async function RF(e){return T("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function IF(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return T(`/providers/paperclip/cli-status${s?`?${s}`:""}`)}async function TF(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return(await T(`/providers/paperclip/cli-companies${s?`?${s}`:""}`)).companies??[]}async function $F(e){const n=new URLSearchParams({companyId:e.companyId});return e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath),(await T(`/providers/paperclip/cli-agents?${n.toString()}`)).agents??[]}async function DF(e={}){const n=new URLSearchParams;e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return T(`/providers/paperclip/cli-discovery${s?`?${s}`:""}`)}function pj(e){return T("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function fj(e){return T("/auth/droid-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function gj(e){return T("/auth/cursor-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function bj(e){return T("/auth/llama-cpp",{method:"POST",body:JSON.stringify({enabled:e})})}async function xj(){const n=(await T("/custom-providers")).map(s=>({id:s.id,name:s.name,baseUrl:s.baseUrl,api:s.apiType==="anthropic-compatible"?"anthropic-messages":"openai-completions",apiKey:s.apiKey,models:(s.models??[]).map(a=>({id:a.id,name:a.name}))}));return Object.assign(n,{providers:n})}function vj(e){return T("/custom-providers",{method:"POST",body:JSON.stringify(e)})}function LF(e,n){const s=n,a={...typeof s.name=="string"?{name:s.name}:{},...typeof s.baseUrl=="string"?{baseUrl:s.baseUrl}:{},...typeof s.apiKey=="string"?{apiKey:s.apiKey}:{},...Array.isArray(s.models)?{models:s.models.map(r=>({id:r.id,name:r.name??r.id}))}:{},...s.api?{apiType:s.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible"}:{},..."apiType"in n?{apiType:n.apiType}:{}};return T(`/custom-providers/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(a)})}function OF(e){return T(`/custom-providers/${encodeURIComponent(e)}`,{method:"DELETE"})}function yj(e){const n=e.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible";return vj({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 uo(){return T("/auth/status")}function wj(e){return T("/auth/login",{method:"POST",body:JSON.stringify({provider:e,origin:window.location.origin})})}function kj(e,n){return T("/auth/manual-code",{method:"POST",body:JSON.stringify({provider:e,code:n})})}function jj(e){return T("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function Nj(e){return T("/auth/cancel",{method:"POST",body:JSON.stringify({provider:e})})}function Sj(e,n){return T("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function Cj(e){return T("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function Ej(e,n,s,a){return T("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:a})})}function _j(e,n,s,a){return T(W("/github/issues/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function Mj(e,n,s){return T("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function Aj(e,n,s,a){return T(W("/github/pulls/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function Pj(e){return T(W("/git/remotes",e))}function Rj(e){return T(W("/git/remotes/detailed",e))}function Ij(e,n,s){return T(W("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function Tj(e,n){return T(W(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function $j(e,n,s){return T(W(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function Dj(e,n,s){return T(W(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function Lj(e,n,s){return T(W(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function Oj(e,n){return T(W(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function zj(e,n){return(await T(W("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function Lo(e,n,s,a){return T(W("/terminal/sessions",a),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function am(e,n){return T(W(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Fj(e){return T(W("/terminal/sessions",e))}function di(e){return T(W("/git/status",e))}function Uj(e,n){const s=e?`?limit=${e}`:"";return T(W(`/git/commits${s}`,n))}function El(e,n){return T(W(`/git/commits/${e}/diff`,n))}function Bj(e){return T(W("/git/commits/ahead",e))}function Hj(e,n,s,a){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return T(W(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,a))}function Ar(e){return T(W("/git/branches",e))}function qj(e,n,s){const a=`?limit=${n}`;return T(W(`/git/branches/${encodeURIComponent(e)}/commits${a}`,s))}function Vj(e){return T(W("/git/worktrees",e))}function Wj(e,n,s){return T(W("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function Kj(e,n){return T(W(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function rm(e,n,s){const a=n?"?force=true":"";return T(W(`/git/branches/${encodeURIComponent(e)}${a}`,s),{method:"DELETE"})}function Gj(e,n){return T(W("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function Jj(e,n){const s=typeof e=="string"?void 0:e;return T(W("/git/pull",typeof e=="string"?e:n),{method:"POST",body:JSON.stringify({rebase:s?.rebase??!1})})}function Yj(e){return T(W("/git/push",e),{method:"POST"})}function Oo(e){return T(W("/git/stashes",e))}function Qj(e,n){return T(W("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function Xj(e,n,s){return T(W(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function Zj(e,n){return T(W(`/git/stashes/${e}`,n),{method:"DELETE"})}function eN(e,n){return T(W(`/git/stashes/${e}/diff`,n))}function tN(e,n,s){const a=new URLSearchParams;return a.set("path",e),a.set("staged",String(n)),T(W(`/git/diff/file?${a.toString()}`,s))}function Ga(e){return T(W("/git/changes",e))}function om(e,n){return T(W("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function nN(e,n){return T(W("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function lm(e,n){return T(W("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function sN(e,n){return T(W("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function iN(e){return T(W("/workspaces",e))}function aN(e,n,s){const a=new URLSearchParams({workspace:e});return n&&a.set("path",n),s&&a.set("projectId",s),T(`/files?${a.toString()}`)}function rN(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),T(`/files/${encodeURIComponent(n)}?${a.toString()}`)}function oN(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),T(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function lN(e,n,s){const a=new URLSearchParams({q:e});return n&&a.set("workspace",n),s&&a.set("projectId",s),T(`/files/search?${a.toString()}`)}function cN(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),T(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function dN(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),T(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function uN(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),T(`/files/${encodeURIComponent(n)}/delete?${a.toString()}`,{method:"POST"})}function mN(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),T(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function Ng(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${a.toString()}`}function hN(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${a.toString()}`}function pN(e,n,s){return T(W("/planning/create-draft",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function fN(e,n,s,a,r){return T(W("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId,planningDepth:a?.planningDepth,customQuestionCount:a?.customQuestionCount,...r?{existingSessionId:r}:{}})})}function cm(e,n,s,a){return T(W("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function gN(e,n,s){return T(W(`/planning/${encodeURIComponent(e)}/back`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function bN(e,n,s){return T(W(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function xN(e,n,s){return T(W(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Sg(e,n,s){return T(W("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function zF(e,n,s,a){return T(W("/agents/onboarding/start-streaming",s),{method:"POST",body:JSON.stringify({intent:e,context:n,mode:n.mode,existingAgentConfig:n.existingAgentConfig,planningModelProvider:a?.planningModelProvider,planningModelId:a?.planningModelId})})}function FF(e,n,s){return T(W("/agents/onboarding/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n})})}function UF(e,n){return T(W("/agents/onboarding/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function vN(e,n,s){return T(W("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function yN(e,n,s){return T(W("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function wN(e,n,s){return T(W("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const Rd=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(Rd))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function kN(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function jr(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=kN(e,d),g=new EventSource(Mi(p));r=g,g.onopen=()=>{l=0,u=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},g.onmessage=x=>{const w=x;m(w)&&n.onMessage?.(w)};for(const[x,w]of Object.entries(n.events??{}))g.addEventListener(x,b=>{const y=b;m(y)&&w(y)});g.onerror=()=>{if(o||r!==g)return;if(g.readyState===EventSource.CONNECTING){u||(u=!0,s.onConnectionStateChange?.("reconnecting"));return}if(g.close(),l>=a){s.onFatalError?.("Connection lost");return}u=!0,s.onConnectionStateChange?.("reconnecting"),l+=1;const w=Math.min(1e3*2**(l-1),3e4);c=setTimeout(()=>{c=null,h()},w)}};h();const f={close:()=>{o=!0,c&&(clearTimeout(c),c=null),r?.close(),Rd.delete(f)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return Rd.add(f),f}function dm(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 mr(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 jN(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 NN(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((a,r)=>jN(a,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function SN(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 um(e){return Array.isArray(e)?e.map(dm):(e.candidates??[]).map(dm)}async function CN(e){try{const n=await T(W("/dev-server/candidates",e));return um(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await T(W("/dev-server/detect",e));return um(s)}throw n}}function mu(e){return T(W("/dev-server/status",e)).then(mr)}async function BF(e={},n){const s=new URLSearchParams;typeof e.maxLines=="number"&&Number.isFinite(e.maxLines)&&s.set("maxLines",String(Math.max(1,Math.floor(e.maxLines)))),typeof e.offset=="number"&&Number.isFinite(e.offset)&&s.set("offset",String(Math.max(0,Math.floor(e.offset)))),typeof e.lastEventId=="number"&&Number.isFinite(e.lastEventId)&&s.set("lastEventId",String(Math.max(0,Math.floor(e.lastEventId))));const a=s.size>0?`?${s.toString()}`:"";try{const r=await T(W(`/dev-server/logs/history${a}`,n));return NN(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await mu(n);return SN(o.logs,e)}throw r}}function EN(e,n){const s=e.cwd??e.packagePath??".",a=e.scriptName;return T(W("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:a,scriptId:a,cwd:s,packagePath:e.packagePath})}).then(mr)}function _N(e){return T(W("/dev-server/stop",e),{method:"POST"}).then(mr)}function MN(e){return T(W("/dev-server/restart",e),{method:"POST"}).then(mr)}async function AN(e,n){const s=typeof e=="string"?{url:e}:e;try{const a=await T(W("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return mr(a)}catch(a){if(a instanceof Error&&/\/dev-server\/preview-url/.test(a.message)){const r=await T(W("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return mr(r)}throw a}}function HF(e){return ws(W("/dev-server/logs/stream",e))}async function qF(e){try{return(await T(W("/devserver",e))).sessions??[]}catch{try{const n=await mu(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 VF(e,n){try{return await T(W(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await mu(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 WF(e,n){try{return await T(W(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await EN({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 KF(e,n){try{return await T(W(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await _N(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 GF(e,n){try{return await T(W(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await MN(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 JF(e,n,s){try{const a=await T(W(`/devserver/${encodeURIComponent(e)}/preview`,s),{method:"POST",body:JSON.stringify({url:n})});return{url:a.url??null,source:a.source??null}}catch{const a=await AN({url:n},s);return{url:a.previewUrl??a.manualUrl??null,source:"manual"}}}async function YF(e){try{return(await T(W("/devserver/detect",e))).candidates??[]}catch{try{return(await CN(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function QF(e,n){return ws(W(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function Co(e,n,s=25e3){const a=setInterval(()=>{k1(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(a)}}}function PN(e,n){return ws(W(`/planning/${encodeURIComponent(e)}/stream`,n))}function RN(e,n){return ws(W(`/agents/onboarding/${encodeURIComponent(e)}/stream`,n))}function XF(e,n,s,a){const r=RN(e,n),o=jr(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 IN(e,n,s,a){const r=PN(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},d=jr(r,{onOpen:()=>{c(),o=Co(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 Eo(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 TN(e){return T(Eo("/routines",e))}function $N(e,n){return T(Eo("/routines",n),{method:"POST",body:JSON.stringify(e)})}function mm(e,n,s){return T(Eo(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function DN(e,n){await T(Eo(`/routines/${e}`,n),{method:"DELETE"})}function LN(e,n){return T(Eo(`/routines/${e}/trigger`,n),{method:"POST"})}function hm(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since!==void 0&&n.set("since",e.since),e?.type!==void 0&&n.set("type",e.type),e?.projectId&&n.set("projectId",e.projectId);const s=n.size>0?`?${n.toString()}`:"";return T(`/activity${s}`)}function ON(e){const n=W("/activity",e);return T(n,{method:"DELETE"})}function _o(e){return T(W("/workflow-steps",e))}function pm(e,n){return T(W("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function zN(e,n,s){return T(W(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function FN(e,n){return T(W(`/workflow-steps/${e}`,n),{method:"DELETE"})}function fm(e,n){return T(W(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function UN(e,n){return T(W(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function BN(){return T("/workflow-step-templates")}function HN(){return T("/plugin-workflow-step-templates")}function qN(e,n){return T(W(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function mo(e){return T(W("/scripts",e))}function VN(e,n,s){return T(W("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function WN(e,n){return T(W(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function Cg(e,n,s){return(await T(W("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const zo={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 Eg(e){if(!(e instanceof Error))return zo.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?zo.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?zo.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:zo.NETWORK}function KN(e,n){return T(W("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function GN(e,n,s){return T(W(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function JN(e,n){return ws(W(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function YN(e,n,s,a){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=jr(JN(e,n),{onOpen:()=>{l(),r=Co(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 QN(e,n,s,a){return T(W("/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 _g(e,n,s){return T(W("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function W(e,n){if(!n)return e;const s=e.includes("?")?"&":"?";return`${e}${s}projectId=${encodeURIComponent(n)}`}function XN(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 Mo(e,n){const{nodeId:s,localNodeId:a,...r}=n??{},o=XN(e,s,a);return T(o,r)}function Nr(e,n){const s=new URLSearchParams;e?.state&&s.set("state",e.state),e?.role&&s.set("role",e.role),e?.includeEphemeral===!0&&s.set("includeEphemeral","true"),n&&s.set("projectId",n);const a=s.size>0?`?${s.toString()}`:"";return T(`/agents${a}`)}function Id(e,n){return T(W(`/agents/${encodeURIComponent(e)}`,n))}function ZN(e,n){return T(W("/agents",n),{method:"POST",body:JSON.stringify(e)})}function eS(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function ZF(e,n,s){const a=new FormData;a.append("file",n);const r=await fetch(ws(W(`/agents/${encodeURIComponent(e)}/avatar`,s)),{method:"POST",headers:gi(),body:a}),o=await r.json();if(!r.ok)throw new Error(o.error||"Avatar upload failed");return o}function e3(e,n){return T(W(`/agents/${encodeURIComponent(e)}/avatar`,n),{method:"DELETE"})}function t3(e,n){return T(W(`/agents/${encodeURIComponent(e)}/upgrade-heartbeat-procedure`,n),{method:"POST"})}function n3(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function s3(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function i3(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function a3(e,n){return T(W(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function r3(e,n,s){const a=`path=${encodeURIComponent(n)}`;return T(W(`/agents/${encodeURIComponent(e)}/memory/file?${a}`,s))}function o3(e,n,s,a){return T(W(`/agents/${encodeURIComponent(e)}/memory/file`,a),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function tS(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function nS(e,n){return T(W(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function l3(e,n,s){const a=new URLSearchParams;n!==void 0&&a.set("limit",String(n)),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return T(`/agents/${encodeURIComponent(e)}/runs${r}`)}function c3(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function d3(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function u3(e,n,s){const a=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return T(W(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:a,triggerDetail:r})})}function m3(e,n){return T(W(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function sS(e){return T(W("/agents/stats",e))}function h3(e,n){return T(W(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function p3(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const a=s.toString();return T(`/agents/org-tree${a?`?${a}`:""}`)}function f3(e,n){return T(W(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function gm(e,n,s){return T(W(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function Mg(e){return{reviewState:{source:e.mode,summary:e.summary??void 0,items:e.items.map(n=>({id:n.itemId,body:n.body,author:{login:n.author},createdAt:n.createdAt??new Date(0).toISOString(),updatedAt:n.updatedAt??void 0,path:n.filePath,threadId:n.threadId,htmlUrl:n.url,state:n.reviewState??void 0,isResolved:n.isResolved})),addressing:[],lastRefreshedAt:e.fetchedAt??void 0,refreshStatus:"ready",refreshSource:"initial-load"},automationStatus:null}}async function iS(e,n){const s=await T(W(`/tasks/${encodeURIComponent(e)}/review`,n));return Mg(s)}async function aS(e,n){const s=await T(W(`/tasks/${encodeURIComponent(e)}/review/refresh`,n),{method:"POST"});return Mg(s)}function rS(e,n,s){return T(W(`/tasks/${encodeURIComponent(e)}/review/address`,s),{method:"POST",body:JSON.stringify({selectedItems:n,tab:"review"})})}function g3(e,n){return T(W(`/agents/${encodeURIComponent(e)}/tasks`,n))}function b3(){return T("/agents/companies")}function x3(e,n){return T(W("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function v3(e,n){return T(W("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function y3(e,n){return T(W(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function w3(e){return T(W("/backups",e))}function k3(e){return T(W("/backups",e),{method:"POST"})}function j3(e,n){const s=W("/settings/export",n),a=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return T(a)}function N3(e,n,s){return T(W("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function oS(e){return Array.isArray(e.nodeMappings)||Array.isArray(e.projectNodeMappings)||Array.isArray(e.pathMappings)}function bm(){return T("/projects/across-nodes")}function _l(){return T("/nodes")}function S3(){return T("/docker/nodes")}function C3(e){return T(`/docker/nodes/${encodeURIComponent(e)}/container-status`)}function E3(e,n){const s=new URLSearchParams;typeof n?.tail=="number"&&s.set("tail",String(n.tail));const a=s.size>0?`?${s.toString()}`:"";return T(`/docker/nodes/${encodeURIComponent(e)}/logs${a}`)}function _3(e){return T("/docker-nodes",{method:"POST",body:JSON.stringify(e)})}function lS(e){return T("/nodes",{method:"POST",body:JSON.stringify(e)})}function cS(e){return T("/nodes/discover-projects",{method:"POST",body:JSON.stringify(e)})}function dS(e,n){return T(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function uS(e){return T(`/nodes/${encodeURIComponent(e)}/docker-config`)}function mS(e,n){return T(`/nodes/${encodeURIComponent(e)}/docker-config`,{method:"PATCH",body:JSON.stringify(n)})}function hS(e){return T(`/nodes/${encodeURIComponent(e)}/docker-config/diff`)}function xm(e){return T(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function pS(e){const n=await T(`/nodes/${encodeURIComponent(e)}/health-check`,{method:"POST"});return{nodeId:n.nodeId??e,status:n.status,responseTimeMs:n.responseTimeMs,error:n.error,checkedAt:n.checkedAt??new Date().toISOString()}}function M3(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=ur();l&&o.set("fn_token",l);const c=o.toString(),d=`/browse-directory${c?`?${c}`:""}`;return T(d)}function fS(e){return T("/projects",{method:"POST",body:JSON.stringify(e)})}function Ag(e){return T(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function gS(e,n,s){return T(`/projects/${encodeURIComponent(e)}/path-mappings/${encodeURIComponent(n)}`,{method:"PUT",body:JSON.stringify({path:s})})}function vm(e){return T(`/projects/${encodeURIComponent(e)}/health`)}function bS(e){return T(W("/executor/stats",e))}function xS(e){return T(W("/system-stats",e))}function vS(e){return T(W("/kill-vitest",e),{method:"POST"})}function ym(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since&&n.set("since",e.since),e?.projectId&&n.set("projectId",e.projectId),e?.type&&n.set("type",e.type);const s=n.size>0?`?${n.toString()}`:"";return T(`/activity-feed${s}`)}function yS(e){return T(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function wS(e){return T(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function A3(){return T("/global-concurrency")}function P3(e){return T("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function kS(e,n){return T(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function Pg(e,n,s){const a=new URLSearchParams;n&&a.set("worktree",n),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return T(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function jS(e){return T(W("/missions",e))}function NS(e,n){return T(W("/missions",n),{method:"POST",body:JSON.stringify(e)})}function Rg(e,n){return T(W(`/missions/${encodeURIComponent(e)}`,n))}function SS(e,n,s){return T(W(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function CS(e,n){return T(W(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ES(e,n,s){const a=new URLSearchParams;a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset));const r=a.size>0?`?${a.toString()}`:"";return T(W(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function _S(e){return T(W("/missions/health",e))}function MS(e,n,s){return T(W(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function AS(e,n,s){return T(W(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function PS(e,n){return T(W(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function RS(e,n,s){return T(W(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function IS(e,n,s){return T(W(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function TS(e,n){return T(W(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function $S(e,n){return T(W(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function DS(e,n,s){return T(W(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function LS(e,n,s){return T(W(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function OS(e,n){return T(W(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function zS(e,n,s){return T(W(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function FS(e,n){return T(W(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function US(e,n,s,a){return T(W(`/missions/features/${encodeURIComponent(e)}/triage`,a),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function BS(e,n){return T(W(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST"})}function pc(e,n){return T(W(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function HS(e,n,s){return T(W(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function qS(e,n,s){return T(W(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function VS(e,n,s){return T(W(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function WS(e,n,s){return T(W(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function KS(e,n){return T(W(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function fc(e,n){return T(W(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function wm(e,n){return T(W(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function GS(e,n){return T(W(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function km(e,n){return T(W(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function JS(e,n,s){const a=new URLSearchParams;a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset));const r=a.size>0?`?${a.toString()}`:"";return T(W(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function YS(e,n){return T(W(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function QS(e,n){return T(W(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function XS(e,n){return T(W(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function ZS(e,n){return T(W(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function e1(e,n,s){return T(W(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function t1(e,n,s){return T(W("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function n1(e,n,s,a){return T(W("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function s1(e,n,s){return T(W(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Ig(e,n,s){return T(W("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function i1(e,n,s){return T(W("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function a1(e,n,s,a){const r=ws(W(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=jr(r,{onOpen:()=>{c(),o=Co(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 Ao(e,n,s){return W(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function Po(e,n,s){return W(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function r1(e,n){return T(Ao(e,"/start",n),{method:"POST"})}function o1(e,n,s,a){return T(Ao(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function l1(e,n,s,a){const r=ws(Ao(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=jr(r,{onOpen:()=>{c(),o=Co(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 c1(e,n,s){return T(Ao(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function d1(e,n){return T(Ao(e,"/skip",n),{method:"POST"})}function u1(e,n){return T(Po(e,"/start",n),{method:"POST"})}function m1(e,n,s,a){return T(Po(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function h1(e,n,s,a){const r=ws(Po(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=jr(r,{onOpen:()=>{c(),o=Co(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 p1(e,n,s){return T(Po(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function f1(e,n){return T(Po(e,"/skip",n),{method:"POST"})}async function g1(e,n){try{return await T(W(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function R3(e){return T(W("/todos",e))}function I3(e,n){const s={title:e};return T(W("/todos",n),{method:"POST",body:JSON.stringify(s)})}function T3(e,n,s){const a={title:n};return T(W(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function $3(e,n){return T(W(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function D3(e,n,s){const a={text:n};return T(W(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(a)})}function L3(e,n,s){const a=n;return T(W(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function O3(e,n){return T(W(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function z3(e,n,s){return T(W(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function hr(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function hu(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(ws(`/ai-sessions${a?`?${a}`:""}`),{headers:gi()});return r.ok?(await r.json()).sessions??[]:[]}async function b1(e){return T(`/ai-sessions/${encodeURIComponent(e)}/archive`,{method:"POST"})}async function x1(e){return T(`/ai-sessions/${encodeURIComponent(e)}/unarchive`,{method:"POST"})}async function Ci(e){const n=await fetch(ws(`/ai-sessions/${encodeURIComponent(e)}`),{headers:gi()});return n.ok?n.json():null}async function v1(e,n){const s=await T(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function y1(e,n){return T(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function w1(e,n){return T(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function Tg(e){await fetch(ws(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:gi()})}function k1(e,n){return T(W(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function j1(e,n,s){return T(W(`/ai-sessions/${encodeURIComponent(e)}/draft`,s),{method:"PATCH",body:JSON.stringify(n)})}function N1(e,n){return T(W(`/planning/${encodeURIComponent(e)}/summarize-draft-title`,n),{method:"POST"})}function S1(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.unreadOnly&&s.set("unreadOnly","true"),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const a=s.size>0?`?${s.toString()}`:"";return T(`/messages/inbox${a}`)}function C1(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const a=s.size>0?`?${s.toString()}`:"";return T(`/messages/outbox${a}`)}function $g(e){return T(W("/messages/unread-count",e))}function E1(e,n){return T(W("/messages",n),{method:"POST",body:JSON.stringify(e)})}function _1(e,n){return T(W(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function M1(e){return T(W("/messages/read-all",e),{method:"POST"})}function A1(e,n){return T(W(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function P1(e,n,s){const a=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return T(W(a,s))}function R1(e,n){return T(W(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function Fo(e,n){const s=new URLSearchParams;e?.status&&s.set("status",e.status),e?.limit!==void 0&&s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),n&&s.set("projectId",n);const a=s.size>0?`?${s.toString()}`:"";return T(`/approvals${a}`)}function jm(e,n){return T(W(`/approvals/${encodeURIComponent(e)}`,n))}function I1(e,n,s){return T(W(`/approvals/${encodeURIComponent(e)}/decision`,s),{method:"POST",body:JSON.stringify(n)})}function F3(e,n,s){const a=new URLSearchParams;a.set("limit",String(n)),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return T(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function U3(e,n){return T(W(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function B3(e,n,s){const a=new URLSearchParams;s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return T(`/agents/${encodeURIComponent(e)}/performance${r}`)}function H3(e,n,s){const a=new URLSearchParams;a.set("limit",String(n.limit)),n?.category&&a.set("category",n.category),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return T(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function q3(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function V3(e,n){return T(W(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function W3(e,n,s){return T(W(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function K3(e,n){return T(W(`/agents/${encodeURIComponent(e)}/budget`,n))}function G3(e,n){return T(W(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function J3(e){return T(W("/plugins",e))}async function Y3(e,n){return T(W("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function Q3(e,n){return T(W(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function X3(e,n){return T(W(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function Z3(e,n){return T(W(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function e6(e,n){return T(W(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function t6(e,n,s){return T(W(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function n6(e,n){return T(W(`/plugins/${encodeURIComponent(e)}/setup-status`,n))}async function s6(e,n){return T(W(`/plugins/${encodeURIComponent(e)}/setup/install`,n),{method:"POST"})}async function i6(e,n){return T(W(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function a6(e,n,s){return T(W(`/plugins/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function r6(e,n){return T(W(`/plugins/${encodeURIComponent(e)}/rescan`,n),{method:"POST"})}async function T1(e){return T(W("/plugins/ui-slots",e))}async function $1(e){return T(W("/plugins/dashboard-views",e))}async function o6(e){return T(W("/plugins/runtimes",e))}async function D1(e){return(await T(W("/skills/discovered",e))).skills}async function l6(e,n,s){return T(W("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function c6(e,n,s){const a=new URLSearchParams;e&&a.set("q",e),a.set("limit",String(n));const r=a.size>0?`?${a.toString()}`:"";return T(W(`/skills/catalog${r}`,s))}async function d6(e,n){return(await T(W(`/skills/${encodeURIComponent(e)}/content`,n))).content}function Nm(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const a=s.toString();return T(`/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 T(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function O1(e,n){return T(W("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function z1(e,n){return T(W(`/chat/sessions/${encodeURIComponent(e)}`,n))}function u6(e,n,s){return T(W(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function m6(e,n){return T(W(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Pr(e,n,s){const a=new URLSearchParams;n?.limit!==void 0&&a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset)),n?.before&&a.set("before",n.before);const r=a.toString();return T(W(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function h6(e={},n){const s=new URLSearchParams;n&&s.set("projectId",n),e.status&&s.set("status",e.status),e.agentId&&s.set("agentId",e.agentId);const a=s.toString();return T(`/chat/rooms${a?`?${a}`:""}`)}function p6(e,n){const s={...e,...n?{projectId:n}:{}};return T(W("/chat/rooms",n),{method:"POST",body:JSON.stringify(s)})}function f6(e,n){return T(W(`/chat/rooms/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function g6(e,n){return T(W(`/chat/rooms/${encodeURIComponent(e)}/members`,n))}function b6(e,n,s){const a=new URLSearchParams;a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset)),n?.before&&a.set("before",n.before);const r=a.toString();return T(W(`/chat/rooms/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function x6(e,n,s){return T(W(`/chat/rooms/${encodeURIComponent(e)}/messages`,s),{method:"POST",body:JSON.stringify(n)})}function F1(e,n){return T(W(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function U1(e,n,s,a,r,o){const l=ws(W(`/chat/sessions/${encodeURIComponent(e)}/messages`,r)),c=new AbortController;let d=!1,u=!1,m=!1;const h=Math.max(1e3,6e4);let f=null;const p=()=>{f&&(clearTimeout(f),f=null)},g=()=>{m||(m=!0,p())},x=(w,b)=>{if(w)switch(g(),w){case"thinking":try{s.onThinking?.(JSON.parse(b))}catch{s.onThinking?.(b)}break;case"text":try{s.onText?.(JSON.parse(b))}catch{s.onText?.(b)}break;case"tool_start":try{s.onToolStart?.(JSON.parse(b))}catch{}break;case"tool_end":try{s.onToolEnd?.(JSON.parse(b))}catch{}break;case"fallback":try{s.onFallback?.(JSON.parse(b))}catch{}break;case"done":u=!0;try{const y=JSON.parse(b);s.onDone?.({messageId:typeof y.messageId=="string"?y.messageId:"",...y.message&&typeof y.message=="object"?{message:y.message}:{}})}catch{s.onDone?.({messageId:""})}break;case"error":u=!0;try{const y=JSON.parse(b);s.onError?.(y.message||y)}catch{s.onError?.(b||"Stream error")}break}};return(async()=>{try{const w=Array.isArray(a)&&a.length>0,b=w?(()=>{const E=new FormData;return E.append("content",n),a.forEach(R=>E.append("attachments",R)),E})():JSON.stringify({content:n}),y=await fetch(l,{method:"POST",headers:w?gi():gi({"Content-Type":"application/json"}),body:b,signal:c.signal});if(!y.ok){const E=await y.text();let R=`Request failed: ${y.status}`;try{R=JSON.parse(E).error||R}catch{}s.onError?.(R);return}if(!y.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected"),f=setTimeout(()=>{u||d||m||(u=!0,s.onError?.("Timed out waiting for first response event"),c.abort())},h);const S=y.body.getReader(),k=new TextDecoder;let C="",v="",j=[];const P=(E,R=!1)=>{C+=E;const L=C.split(`
|
|
643
|
+
`);C=L.pop()||"",R&&C.length>0&&(L.push(C),C="");for(const F of L){const M=F.endsWith("\r")?F.slice(0,-1):F;if(M.startsWith("event:"))v=M.slice(6).trim();else if(M.startsWith("data:")){const O=M.slice(5);j.push(O.startsWith(" ")?O.slice(1):O)}else if(M===""){const O=j.join(`
|
|
644
|
+
`);x(v,O),v="",j=[]}}if(R&&v&&j.length>0){const F=j.join(`
|
|
645
|
+
`);x(v,F),v="",j=[]}};for(;;){const{done:E,value:R}=await S.read();if(E){P(k.decode(),!0);break}P(k.decode(R,{stream:!0}))}const U=C.length>0||v.length>0||j.length>0;!u&&!d&&!U&&s.onError?.("Connection closed unexpectedly"),p()}catch(w){if(w instanceof DOMException&&w.name==="AbortError"){!d&&!u&&s.onError?.("Connection aborted"),p();return}if(d){p();return}p(),s.onError?.(w instanceof Error?w.message:"Connection error")}})(),{close:()=>{d=!0,p(),c.abort()},isConnected:()=>!d}}function B1(e,n,s,a){const r=ws(W(`/chat/sessions/${encodeURIComponent(e)}/stream`,s)),o=new AbortController;let l=!1,c=!1;const d=(u,m)=>{if(u)switch(u){case"thinking":try{n.onThinking?.(JSON.parse(m))}catch{n.onThinking?.(m)}break;case"text":try{n.onText?.(JSON.parse(m))}catch{n.onText?.(m)}break;case"tool_start":try{n.onToolStart?.(JSON.parse(m))}catch{}break;case"tool_end":try{n.onToolEnd?.(JSON.parse(m))}catch{}break;case"fallback":try{n.onFallback?.(JSON.parse(m))}catch{}break;case"done":c=!0;try{const h=JSON.parse(m);n.onDone?.({messageId:typeof h.messageId=="string"?h.messageId:"",...h.message&&typeof h.message=="object"?{message:h.message}:{}})}catch{n.onDone?.({messageId:""})}break;case"error":c=!0;try{const h=JSON.parse(m);n.onError?.(h.message||h)}catch{n.onError?.(m||"Stream error")}break}};return(async()=>{try{const u=new Headers(gi());a?.lastEventId;const m=await fetch(r,{method:"GET",headers:u,signal:o.signal});if(!m.ok){const y=await m.text();let S=`Request failed: ${m.status}`;try{S=JSON.parse(y).error||S}catch{}n.onError?.(S);return}if(!m.body){n.onError?.("No response body");return}n.onConnectionStateChange?.("connected");const h=m.body.getReader(),f=new TextDecoder;let p="",g="",x=[];const w=(y,S=!1)=>{p+=y;const k=p.split(`
|
|
646
|
+
`);p=k.pop()||"",S&&p.length>0&&(k.push(p),p="");for(const C of k){const v=C.endsWith("\r")?C.slice(0,-1):C;if(v.startsWith("event:"))g=v.slice(6).trim();else if(v.startsWith("data:")){const j=v.slice(5);x.push(j.startsWith(" ")?j.slice(1):j)}else if(v===""){const j=x.join(`
|
|
647
|
+
`);d(g,j),g="",x=[]}}if(S&&g&&x.length>0){const C=x.join(`
|
|
648
|
+
`);d(g,C),g="",x=[]}};for(;;){const{done:y,value:S}=await h.read();if(y){w(f.decode(),!0);break}w(f.decode(S,{stream:!0}))}const b=p.length>0||g.length>0||x.length>0;if(!c&&!l&&!b)return}catch(u){if(u instanceof DOMException&&u.name==="AbortError"){!l&&!c&&n.onError?.("Connection aborted");return}if(l)return;n.onError?.(u instanceof Error?u.message:"Connection error")}})(),{close:()=>{l=!0,o.abort()},isConnected:()=>!l}}function v6(e={},n){const s=new URLSearchParams;e.category&&s.set("category",e.category),e.status&&s.set("status",e.status),e.runId&&s.set("runId",e.runId),e.limit!==void 0&&s.set("limit",String(e.limit)),e.offset!==void 0&&s.set("offset",String(e.offset));const a=s.size>0?`?${s.toString()}`:"";return T(W(`/insights${a}`,n))}function y6(e,n){return T(W(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function w6(e,n){return T(W(`/insights/${encodeURIComponent(e)}/archive`,n),{method:"POST"})}function k6(e,n){return T(W(`/insights/${encodeURIComponent(e)}/unarchive`,n),{method:"POST"})}function j6(e="manual",n,s,a,r){const o={trigger:e,inputMetadata:n};return a&&(o.modelProvider=a),r&&(o.modelId=r),T(W("/insights/run",s),{method:"POST",body:JSON.stringify(o)})}function N6(e){return T(W("/insights/runs",e))}function S6(e,n){return T(W(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function C6(e={},n){const s=new URLSearchParams;e.q&&s.set("q",e.q),e.runId&&s.set("runId",e.runId),e.scoreMin!==void 0&&s.set("scoreMin",String(e.scoreMin)),e.scoreMax!==void 0&&s.set("scoreMax",String(e.scoreMax)),e.limit!==void 0&&s.set("limit",String(e.limit)),e.offset!==void 0&&s.set("offset",String(e.offset));const a=s.size>0?`?${s.toString()}`:"";return T(W(`/evals${a}`,n))}function E6(e,n){return T(W(`/evals/${encodeURIComponent(e)}`,n))}function _6(e){return T(W("/evals/runs",e))}function M6(e={},n){const s=new URLSearchParams;e.q&&s.set("q",e.q),e.status&&s.set("status",e.status),e.limit!==void 0&&s.set("limit",String(e.limit));const a=s.size>0?`?${s.toString()}`:"";return T(W(`/research/runs${a}`,n))}function A6(e,n){return T(W("/research/runs",n),{method:"POST",body:JSON.stringify(e)})}function P6(e,n){return T(W(`/research/runs/${encodeURIComponent(e)}`,n))}function Dg(e){if(e instanceof yg){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 R6(e,n){try{return await T(W(`/research/runs/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}catch(s){Dg(s)}}async function I6(e,n){try{return await T(W(`/research/runs/${encodeURIComponent(e)}/retry`,n),{method:"POST"})}catch(s){Dg(s)}}function T6(e,n,s){return T(W(`/research/runs/${encodeURIComponent(e)}/export?format=${encodeURIComponent(n)}`,s))}function $6(e,n,s){const a=n.findingId??"finding-1";return T(W(`/research/runs/${encodeURIComponent(e)}/findings/${encodeURIComponent(a)}/task`,s),{method:"POST",body:JSON.stringify({title:n.title,description:n.description,priority:n.priority,attachExport:n.attachExport})})}function D6(e,n,s){const a=n.findingId??"finding-1";return T(W(`/research/runs/${encodeURIComponent(e)}/findings/${encodeURIComponent(a)}/tasks/${encodeURIComponent(n.taskId)}/enrich`,s),{method:"POST",body:JSON.stringify({attachExport:n.attachExport})})}async function H1(e){return Mo("/health",{nodeId:e})}async function q1(e){return Mo("/projects",{nodeId:e})}async function V1(e,n,s){const a=new URLSearchParams({projectId:n});return s&&s.trim()&&a.set("q",s.trim()),Mo(`/tasks?${a.toString()}`,{nodeId:e})}async function W1(e,n){return Mo(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function L6(e){return T(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function O6(e){return T(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function z6(e){return T(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function F6(e){return T(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}async function K1(e,n){return Promise.all(n.map(({projectId:s,path:a})=>gS(s,e,a)))}function G1(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 J1({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}=G1(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 Y1(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Ca({status:e,showLabel:n=!1,className:s,compact:a=!1}){const r=Y1(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 Sm=new Map,Q1=6e4;function Lg(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=Sm.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 T1(e);if(h||d.current)return;Sm.set(m,{slots:x,expiresAt:Date.now()+Q1}),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 Cm({size:e,color:n,label:s="llama.cpp"}){return t.jsx(cg,{size:e,color:n,"aria-label":s,"data-testid":"llama-cpp-icon"})}const X1={sm:16,md:20,lg:24};function Z1({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 Em({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 wi({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 e0({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 _m({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 t0({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 gc({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 Mm({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 Am({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 Pm({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 bc({size:e,color:n,label:s="DeepSeek"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"deepseek-icon","aria-label":s,children:t.jsx("path",{d:"M4 12a8 8 0 1 1 12.7 6.4L12 16h4a4 4 0 1 0-1.6 3.2L12 22l7-1-1.2-3.6A10 10 0 1 0 2 12z",fill:n})})}function Rm({size:e,color:n,label:s="Cloudflare"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"cloudflare-icon","aria-label":s,children:t.jsx("path",{d:"M7 16.5h10.8a2.9 2.9 0 0 0 .3-5.8 4.9 4.9 0 0 0-9.3-1.6A3.6 3.6 0 0 0 7 16.5m-1.9 0h3.2a2.5 2.5 0 0 0 .2-5 3.4 3.4 0 0 0-3.4 3.4c0 .6 0 1 .2 1.6",fill:n})})}function Rr({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 Im({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 xc({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 Tm({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 vc({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 n0({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 s0({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 $m({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 yc({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 i0({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 Dm({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 wc({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 Lm({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 kc({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 Om({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 a0({size:e,color:n,label:s="Factory AI — via Droid CLI"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"droid-cli-icon","aria-label":s,children:[t.jsx("rect",{x:"2",y:"3",width:"14",height:"14",rx:"3",fill:n}),t.jsx("path",{d:"M6.5 7.5h2.6a2.9 2.9 0 1 1 0 5.8H6.5zM9 7.5v5.8",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"}),t.jsx("rect",{x:"13",y:"13",width:"10",height:"9",rx:"1.5",fill:n}),t.jsx("path",{d:"M15.2 16.2l1.6 1.4-1.6 1.4M18.6 19.6h2.4",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})]})}function r0({size:e,color:n,label:s="Cursor — via Cursor CLI"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"cursor-cli-icon","aria-label":s,children:[t.jsx("rect",{x:"2",y:"3",width:"14",height:"14",rx:"3",fill:n}),t.jsx("path",{d:"M10.8 7.2a3.6 3.6 0 1 0 0 5.6",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"}),t.jsx("rect",{x:"13",y:"13",width:"10",height:"9",rx:"1.5",fill:n}),t.jsx("path",{d:"M15.2 16.2l1.6 1.4-1.6 1.4M18.6 19.6h2.4",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})]})}const o0={anthropic:{component:Z1,color:"var(--provider-anthropic)"},"claude-cli":{component:Om,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:Om,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"droid-cli":{component:a0,color:"var(--provider-openai)",label:"Factory AI — via Droid CLI"},"cursor-cli":{component:r0,color:"var(--provider-cursor-cli)",label:"Cursor — via Cursor CLI"},"llama-cpp":{component:Cm,color:"var(--provider-ollama)",label:"llama.cpp"},"llama-server":{component:Cm,color:"var(--provider-ollama)",label:"llama.cpp"},openai:{component:Em,color:"var(--provider-openai)"},"openai-codex":{component:Em,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:wi,color:"var(--provider-gemini)"},gemini:{component:wi,color:"var(--provider-gemini)"},"google-antigravity":{component:wi,color:"var(--provider-gemini)",label:"Google Gemini"},antigravity:{component:wi,color:"var(--provider-gemini)",label:"Google Gemini"},"google-vertex":{component:wi,color:"var(--provider-gemini)",label:"Google Vertex AI"},vertex:{component:wi,color:"var(--provider-gemini)",label:"Google Vertex AI"},"google-cloud-code":{component:wi,color:"var(--provider-gemini)",label:"Google Cloud Code"},"cloud-code":{component:wi,color:"var(--provider-gemini)",label:"Google Cloud Code"},"google-gemini-cli":{component:wi,color:"var(--provider-gemini)",label:"Google Gemini CLI"},"google-generative-ai":{component:wi,color:"var(--provider-gemini)",label:"Google Generative AI"},ollama:{component:e0,color:"var(--text)"},github:{component:Dm,color:"var(--text)"},"github-copilot":{component:Dm,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:i0,color:"var(--provider-openrouter)"},minimax:{component:_m,color:"var(--provider-minimax)"},"minimax-cn":{component:_m,color:"var(--provider-minimax)",label:"MiniMax (CN)"},zai:{component:t0,color:"var(--provider-zai)"},kimi:{component:gc,color:"var(--provider-kimi)"},moonshot:{component:gc,color:"var(--provider-kimi)"},"kimi-coding":{component:gc,color:"var(--provider-kimi)",label:"Kimi"},bedrock:{component:Mm,color:"var(--provider-bedrock)"},"amazon-bedrock":{component:Mm,color:"var(--provider-bedrock)",label:"Amazon Bedrock"},xai:{component:Am,color:"var(--text)"},grok:{component:Am,color:"var(--text)",label:"xAI"},opencode:{component:Pm,color:"var(--provider-opencode)"},"opencode-go":{component:Pm,color:"var(--provider-opencode)",label:"Opencode (Go)"},deepseek:{component:bc,color:"var(--provider-deepseek)",label:"DeepSeek"},"deepseek-ai":{component:bc,color:"var(--provider-deepseek)",label:"DeepSeek"},"deep-seek":{component:bc,color:"var(--provider-deepseek)",label:"DeepSeek"},cloudflare:{component:Rm,color:"var(--provider-cloudflare)",label:"Cloudflare"},cloudflared:{component:Rm,color:"var(--provider-cloudflare)",label:"Cloudflare"},qwen:{component:Rr,color:"var(--provider-qwen)"},"qwen-ai":{component:Rr,color:"var(--provider-qwen)",label:"Qwen"},"qwen-coder":{component:Rr,color:"var(--provider-qwen)",label:"Qwen Coder"},alibaba:{component:Rr,color:"var(--provider-qwen)",label:"Qwen"},tongyi:{component:Rr,color:"var(--provider-qwen)",label:"Qwen"},lmstudio:{component:Im,color:"var(--provider-lmstudio)",label:"LM Studio"},"lm-studio":{component:Im,color:"var(--provider-lmstudio)",label:"LM Studio"},huggingface:{component:xc,color:"var(--provider-huggingface)",label:"Hugging Face"},"hugging-face":{component:xc,color:"var(--provider-huggingface)",label:"Hugging Face"},hf:{component:xc,color:"var(--provider-huggingface)",label:"Hugging Face"},mistral:{component:Tm,color:"var(--provider-mistral)",label:"Mistral AI"},"mistral-ai":{component:Tm,color:"var(--provider-mistral)",label:"Mistral AI"},azure:{component:vc,color:"var(--provider-azure)"},"azure-openai":{component:vc,color:"var(--provider-azure)",label:"Azure OpenAI"},"azure-openai-responses":{component:vc,color:"var(--provider-azure)",label:"Azure OpenAI"},fireworks:{component:yc,color:"var(--provider-fireworks)",label:"Fireworks AI"},"fireworks-ai":{component:yc,color:"var(--provider-fireworks)",label:"Fireworks AI"},fireworksai:{component:yc,color:"var(--provider-fireworks)",label:"Fireworks AI"},cerebras:{component:n0,color:"var(--provider-cerebras)"},groq:{component:s0,color:"var(--provider-groq)"},vercel:{component:$m,color:"var(--provider-vercel)"},"vercel-ai-gateway":{component:$m,color:"var(--provider-vercel)",label:"Vercel AI Gateway"},hermes:{component:wc,color:"var(--provider-hermes)",label:"Hermes"},"hermes-agent":{component:wc,color:"var(--provider-hermes)",label:"Hermes"},hermesagent:{component:wc,color:"var(--provider-hermes)",label:"Hermes"},openclaw:{component:Lm,color:"var(--provider-openclaw)",label:"OpenClaw"},"open-claw":{component:Lm,color:"var(--provider-openclaw)",label:"OpenClaw"},paperclip:{component:kc,color:"var(--provider-paperclip)",label:"Paperclip"},paperclipai:{component:kc,color:"var(--provider-paperclip)",label:"Paperclip"},"paperclip-ai":{component:kc,color:"var(--provider-paperclip)",label:"Paperclip"}};function Sn({provider:e,size:n="sm"}){const s=e.toLowerCase(),a=o0[s],r=a?.component,o=a?.color??"var(--text-muted)",l=a?.label,c=X1[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(cg,{size:c})})}function Og({authenticated:e,onToggled:n,compact:s=!1}){const[a,r]=i.useState(null),[o,l]=i.useState(null),[c,d]=i.useState(null),u=i.useRef(!0);i.useEffect(()=>(u.current=!0,()=>{u.current=!1}),[]);const m=i.useCallback(async()=>{try{const b=await uj();return u.current&&r(b),b}catch(b){return u.current&&d({kind:"error",message:b instanceof Error?b.message:String(b)}),null}},[]);i.useEffect(()=>{m()},[m]);const h=i.useCallback(async()=>{l("testing"),d(null),await m(),u.current&&l(null)},[m]),f=i.useCallback(async b=>{l(b?"enabling":"disabling"),d(null);try{const y=await fj(b);u.current&&d({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await m()}catch(y){u.current&&d({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{u.current&&l(null)}},[n,m]),p=a?.binary.available??!1,g=a?.enabled??e,x=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"droid"})," CLI. Uses your existing Factory AI subscription / quota instead of an API key."]}),w=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(xt,{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(Sn,{provider:"droid-cli",size:"sm"}),t.jsx("strong",{children:"Factory AI — via Droid CLI"}),t.jsx(l0,{status:a,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:w})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:"Details"}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[x,t.jsx(zm,{status:a,authenticated:e}),c&&t.jsx(Fm,{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(Sn,{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(zm,{status:a,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:w}),c&&t.jsx(Fm,{action:c})]})}function l0({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 zm({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(xt,{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 Fm({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 Um({actions:e}){return t.jsx(Og,{compact:!0,authenticated:!1,onToggled:()=>{e?.refreshAuthProviders?.()}})}function c0({actions:e}){return t.jsx(Og,{authenticated:!1,onToggled:()=>{e?.refreshAuthProviders?.()}})}function d0(){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 u0({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 m0=[{pluginId:"fusion-plugin-droid-runtime",slotId:"settings-provider-card",componentPath:"./components/settings-provider-card.js",component:Um},{pluginId:"fusion-plugin-droid-runtime",slotId:"settings-integration-card",componentPath:"./components/settings-integration-card.js",component:Um},{pluginId:"fusion-plugin-droid-runtime",slotId:"onboarding-provider-card",componentPath:"./components/onboarding-provider-card.js",component:c0},{pluginId:"fusion-plugin-droid-runtime",slotId:"onboarding-setup-help",componentPath:"./components/onboarding-setup-help.js",component:d0},{pluginId:"fusion-plugin-droid-runtime",slotId:"post-onboarding-recommendation",componentPath:"./components/post-onboarding-recommendation.js",component:u0}];function h0(e){return m0.find(s=>s.pluginId===e.pluginId&&s.slotId===e.slot.slotId&&s.componentPath===e.slot.componentPath)?.component??null}function p0({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 ta({slotId:e,projectId:n,pluginIds:s,renderPlaceholder:a=!0,actions:r}){const{getSlotsForId:o,loading:l,error:c}=Lg(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(So,{level:"page",children:t.jsx(t.Fragment,{children:d.map((u,m)=>{const h=`${u.pluginId}-${u.slot.slotId}-${m}`,f=h0(u);return f?t.jsx(f,{entry:u,actions:r},h):a?t.jsx(p0,{slotId:u.slot.slotId,pluginId:u.pluginId},h):null})})})}function f0(){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 Ys(){const[e,n]=i.useState(f0);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 Sr(e){return e.replace(/\\/g,"/")}function pu(e){return e.replace(/[\\/]+$/g,"")}function fu(e){const n=Sr(pu(e));return n?n.split("/").filter(Boolean):[]}function gu(e){const n=Sr(pu(e));if(!n)return e;const s=n.split("/").filter(Boolean);return s[s.length-1]||n}function zg(e,n){const s=fu(e);return s.length===0?Sr(e):s.slice(-2).join("/")}function g0(e){const n=Sr(pu(e)),s=n.lastIndexOf("/");return s<0?"":n.slice(0,s+1)}function b0(e,n){return!e||e==="."?n:[...fu(e),n].join("/")}function x0(e){const n=fu(e);return n.length===0?".":(n.pop(),n.length===0?".":n.join("/"))}function U6(e){const n=Sr(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 bu=new Map;function Ro(e,n){return`plugin:${e}:${n}`}function Fg(e){const n=/^plugin:([^:]+):(.+)$/u.exec(e);return n?{pluginId:n[1],viewId:n[2]}:null}function rr(e){return Fg(e)!==null}function Bm(e,n,s){bu.set(Ro(e,n),s)}function v0(e,n){return bu.get(Ro(e,n))??null}function y0(e,n){return bu.has(Ro(e,n))}function jc({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(No,{}),"Plugin view unavailable"]}),t.jsxs("p",{className:"plugin-dashboard-view-missing-description",children:["No host registration found for ",t.jsx("code",{children:e}),"."]})]})}function w0({viewId:e,context:n}){const s=Fg(e);if(!s)return t.jsx(jc,{viewId:e});const a=v0(s.pluginId,s.viewId);return a?t.jsx(So,{fallback:t.jsx(jc,{viewId:e}),children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(a,{context:n})})}):t.jsx(jc,{viewId:e})}const no=Ro,k0={activity:Ks,bot:Tn,brain:oo,checksquare:lu,clock:Hi,filetext:ia,folder:bs,gitbranch:Us,grid3x3:Kl,layoutgrid:aa,mail:Na,map:dw,messagesquare:Ui,monitor:dr,search:Fi,sparkles:ps,target:vs,workflow:Sl,zap:Qn};function j0(e){return(e??"").trim().toLowerCase().replace(/[-_\s]/g,"")}function Ml(e){return k0[j0(e)]??Kl}const Uo="__fusion:no-branch__",Ug={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function N0({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(rn,{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=Ug[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:zg(d.path)})]}),u&&t.jsx(hs,{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 Hm({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 S0({onOpenSettings:e,onOpenGitHubImport:n,onOpenPlanning:s,onResumePlanning:a,activePlanningSessionCount:r=0,onOpenUsage:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:d,mailboxUnreadCount:u=0,mailboxPendingApprovalCount:m=0,chatHasUnreadResponse:h=!1,onOpenSchedules:f,onOpenGitManager:p,onOpenNodes:g,showNodesButton:x,onOpenWorkflowSteps:w,onOpenScripts:b,onRunScript:y,onToggleTerminal:S,onOpenFiles:k,filesOpen:C,onOpenTodos:v,todosOpen:j,todosEnabled:P,globalPaused:U,enginePaused:E,onToggleGlobalPause:R,onToggleEnginePause:L,view:F="board",onChangeView:M,showSkillsTab:O,showAgentsTab:q,searchQuery:te="",onSearchChange:Z,branchFilter:K="",baseBranchFilter:A="",branchOptions:I=[],baseBranchOptions:$=[],onBranchFilterChange:N,onBaseBranchFilterChange:G,projects:ge=[],currentProject:je,onSelectProject:ke,onViewAllProjects:ne,projectId:qe,shellHost:ee={kind:"browser"},mobileNavEnabled:le,availableNodes:se=[],currentNode:re,onSelectNode:J,isRemote:B=!1,experimentalFeatures:ve,pluginDashboardViews:Ne=[],shellConnectionControl:H}){const be=Ys(),ce=be==="mobile",Le=ce||be==="tablet",He=ce&&le,[gt,Ue]=i.useState(!1),[pe,Oe]=i.useState(!1),[ze,lt]=i.useState(!1),[Be,ye]=i.useState(!1),[Y,_e]=i.useState(!1),[ct,pt]=i.useState(!1),[de,Ve]=i.useState(!1),[Ee,$e]=i.useState(!1),[ut,ht]=i.useState(!1),[Se,we]=i.useState(!1),[Ae,he]=i.useState(!1),[We,me]=i.useState({}),[nt,Ct]=i.useState(!1),[wt,$t]=i.useState(-1),[Vt,Mt]=i.useState(null),[Dt,Qt]=i.useState({}),[Kt,Bt]=i.useState(!1),on=i.useRef(null),fn=i.useRef(null),Jt=i.useRef(null),an=i.useRef(null),zt=i.useRef(null),en=i.useRef(null),Zt=i.useRef(!1),dn=i.useRef(null),xe=i.useRef(null),Fe=i.useRef(null),Ke=i.useRef(null),et=i.useRef(null),Qe=i.useRef(null),It=i.useRef(null),St=i.useRef(null),Ht=i.useRef(!1),jt=i.useMemo(()=>se.filter(ie=>ie.type==="remote"),[se]),ae=jt.length>0,De=i.useMemo(()=>Object.entries(We).sort(([ie],[it])=>ie.localeCompare(it)),[We]),At=De.length>0,Lt=De.length+(At?1:0),Ft=i.useMemo(()=>Object.entries(Dt).sort(([ie],[it])=>ie.localeCompare(it)),[Dt]),Pe=i.useMemo(()=>!!(M||ve?.researchView||P||ve?.insights||O||ve?.memoryView||ve?.devServerView||!He||Ne.some(ie=>ie.view.placement!=="primary")),[M,ve,P,O,He,Ne]),dt=i.useCallback(()=>{const ie=window.visualViewport;return ie&&ie.width>0&&ie.height>0?{width:ie.width,height:ie.height,offsetTop:ie.offsetTop,offsetLeft:ie.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),bt=i.useCallback(()=>{const ie=It.current;if(!ie)return;const it=ie.getBoundingClientRect(),Gt=St.current,{width:Cn,height:fs,offsetTop:On,offsetLeft:jn}=dt(),zn=16,hn=16,Et=6,En=Gt?.offsetWidth||Math.max(it.width,260),yn=Math.min(En,Math.max(Cn-zn*2,160)),ls=Gt?.offsetHeight||280,cs=Math.min(ls,Math.max(fs-hn*2,160)),Hn=it.top-On,qn=it.bottom-On,wn=it.right-jn,Zn=fs-qn,_n=Hn,ss=Zn<cs&&_n>Zn,Ns=Math.min(Math.max(wn-yn,zn),Cn-zn-yn)+jn,es=ss?Math.max(hn+On,Hn-cs-Et+On):Math.min(qn+Et+On,fs+On-hn-cs);Mt({top:es,left:Ns,width:yn})},[dt]),_t=i.useCallback((ie,it)=>{y?.(ie,it),he(!1),$t(-1)},[y]),Yt=i.useCallback(()=>{b?.(),he(!1),$t(-1)},[b]),Xt=i.useCallback(ie=>{switch(ie.key){case"ArrowDown":ie.preventDefault(),Lt>0&&$t(it=>it<Lt-1?it+1:0);break;case"ArrowUp":ie.preventDefault(),Lt>0&&$t(it=>it>0?it-1:Lt-1);break;case"Enter":if(ie.preventDefault(),wt>=0)if(wt<De.length){const[it,Gt]=De[wt];_t(it,Gt)}else At&&wt===De.length&&Yt();break;case"Home":ie.preventDefault(),Lt>0&&$t(0);break;case"End":ie.preventDefault(),Lt>0&&$t(Lt-1);break}},[Yt,_t,wt,De,At,Lt]);i.useEffect(()=>{Zt.current=Y},[Y]),i.useEffect(()=>{Ht.current=Ae},[Ae]),i.useEffect(()=>{if(!Y||!Le)return;let ie=!1;return Bt(!0),mo(qe).then(it=>{ie||Qt(it)}).catch(()=>{ie||Qt({})}).finally(()=>{ie||Bt(!1)}),()=>{ie=!0}},[Y,Le,qe]),i.useEffect(()=>{if(!Ae||Le)return;let ie=!1;return Ct(!0),mo(qe).then(it=>{ie||me(it)}).catch(()=>{ie||me({})}).finally(()=>{ie||Ct(!1)}),()=>{ie=!0}},[Ae,Le,qe]),i.useEffect(()=>{if(!Ae)return;const ie=it=>{Qe.current&&!Qe.current.contains(it.target)&&he(!1)};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[Ae]),i.useEffect(()=>{if(!Ae)return;const ie=it=>{it.key==="Escape"&&(he(!1),It.current?.focus())};return document.addEventListener("keydown",ie),()=>document.removeEventListener("keydown",ie)},[Ae]),i.useEffect(()=>{if(Ae){$t(-1);const ie=window.setTimeout(()=>St.current?.focus(),0);return()=>window.clearTimeout(ie)}Mt(null)},[Ae]),i.useEffect(()=>{if(!Ae)return;const ie=requestAnimationFrame(()=>{bt()});return()=>cancelAnimationFrame(ie)},[Ae,nt,De.length,At,bt]),i.useEffect(()=>{if(!Ae)return;const ie=()=>bt();window.addEventListener("resize",ie),window.addEventListener("scroll",ie,!0);const it=window.visualViewport;return it&&(it.addEventListener("resize",ie),it.addEventListener("scroll",ie)),()=>{window.removeEventListener("resize",ie),window.removeEventListener("scroll",ie,!0),it&&(it.removeEventListener("resize",ie),it.removeEventListener("scroll",ie))}},[Ae,bt]),i.useEffect(()=>{Le&&(he(!1),$t(-1))},[Le]);const Te=gt||te.length>0,Ye=(pe||te.length>0)&&!ze,Nt=(F==="board"||F==="list")&&!ce&&Z&&!ze&&te.length===0,Ut=(F==="board"||F==="list")&&!ce&&Z,tn=F==="board";i.useEffect(()=>{te===""&<(!1)},[te]),i.useEffect(()=>{if(!Be)return;const ie=it=>{fn.current&&!fn.current.contains(it.target)&&on.current&&!on.current.contains(it.target)&&ye(!1)};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[Be]),i.useEffect(()=>{if(!ut)return;const ie=it=>{an.current&&!an.current.contains(it.target)&&Jt.current&&!Jt.current.contains(it.target)&&ht(!1)};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[ut]),i.useEffect(()=>{if(!ct)return;const ie=it=>{dn.current&&!dn.current.contains(it.target)&&pt(!1)};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[ct]),i.useEffect(()=>{const ie=it=>{if(it.key==="Escape"){if($e(!1),ht(!1),Zt.current){_e(!1);return}if(Ht.current){he(!1),It.current?.focus();return}ye(!1),Ue(!1),pt(!1),Ve(!1)}};return document.addEventListener("keydown",ie),()=>document.removeEventListener("keydown",ie)},[]),i.useEffect(()=>{if(!de)return;const ie=it=>{xe.current&&!xe.current.contains(it.target)&&Ve(!1)};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[de]),i.useEffect(()=>{if(!Se)return;const ie=it=>{et.current&&!et.current.contains(it.target)&&we(!1)};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[Se]),i.useEffect(()=>{if(!Se)return;const ie=it=>{it.key==="Escape"&&we(!1)};return document.addEventListener("keydown",ie),()=>document.removeEventListener("keydown",ie)},[Se]),i.useEffect(()=>{if(!Ee)return;const ie=it=>{Fe.current&&!Fe.current.contains(it.target)&&Ke.current&&!Ke.current.contains(it.target)&&$e(!1)};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[Ee]);const Xn=i.useCallback(()=>{Ue(ie=>!ie)},[]),fe=i.useCallback(()=>{Oe(!0),lt(!1)},[]),at=i.useCallback(()=>{Oe(!1),lt(!0),Z&&Z("")},[Z]),ot=i.useCallback(()=>{ye(ie=>!ie)},[]),rt=i.useCallback(ie=>{ie&&ie(),ye(!1),_e(!1)},[]),mt=i.useCallback(()=>{Ue(!1),Z&&Z("")},[Z]),vt=ee.kind==="desktop-shell";return t.jsxs("div",{className:"header-wrapper",children:[t.jsxs("header",{className:"header","data-shell-kind":ee.kind,children:[t.jsxs("div",{className:"header-left",children:[t.jsxs("div",{className:"header-brand",children:[t.jsxs("svg",{className:"header-logo",width:24,height:24,viewBox:"0 0 128 128",fill:"none","aria-label":"Fusion logo",role:"img",children:[t.jsx("circle",{cx:"64",cy:"64",r:"52",stroke:"currentColor",strokeWidth:"8"}),t.jsx("path",{d:"M26 101C44 82 62 64 82 45C90 37 98 30 104 24C96 35 89 47 81 60C70 79 57 95 43 108C38 112 32 108 26 101Z",fill:"currentColor"})]}),t.jsx("h1",{className:"logo",children:"Fusion"})]}),ce&&ge.length>=1&&ke&&t.jsxs("div",{className:"mobile-project-switch",ref:xe,children:[t.jsx("button",{className:`mobile-project-switch-trigger${de?" mobile-project-switch-trigger--open":""}`,onClick:()=>Ve(ie=>!ie),title:"Switch project","aria-label":"Switch project","aria-expanded":de,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(rn,{size:14,className:`mobile-project-switch-chevron${de?" mobile-project-switch-chevron--open":""}`})}),de&&t.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:ge.map(ie=>{const it=je?.id===ie.id,Gt=Ug[ie.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${it?" mobile-project-switch-item--current":""}`,onClick:()=>{ke(ie),Ve(!1)},role:"option","aria-selected":it,"data-testid":`mobile-project-switch-item-${ie.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:Gt||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:ie.name}),t.jsx("span",{className:"mobile-project-switch-path",children:zg(ie.path)})]}),it&&t.jsx(hs,{size:14,className:"mobile-project-switch-check"})]},ie.id)})})]}),!Le&&ge.length>=1&&ne&&t.jsx(N0,{projects:ge,currentProject:je??null,onViewAll:ne,onSelectProject:ke}),ae&&t.jsxs("div",{className:`header-node-selector${ce?" header-node-selector--mobile":""}`,ref:ce?void 0:dn,children:[t.jsx(J1,{node:re??null,showDetails:!ce}),!ce&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${ct?" node-selector-trigger--open":""}`,onClick:()=>pt(ie=>!ie),title:"Switch node","aria-label":"Switch node","aria-expanded":ct,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(Mn,{size:12,className:`node-selector-chevron${ct?" node-selector-chevron--open":""}`})}),ct&&t.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[t.jsxs("button",{className:`node-selector-option${B?"":" node-selector-option--active"}`,onClick:()=>{J?.(null),pt(!1)},role:"option","aria-selected":!B,"data-testid":"node-option-local",children:[t.jsx(Ca,{status:"online",compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),jt.map(ie=>t.jsxs("button",{className:`node-selector-option${re?.id===ie.id?" node-selector-option--active":""}`,onClick:()=>{J?.(ie),pt(!1)},role:"option","aria-selected":re?.id===ie.id,"data-testid":`node-option-${ie.id}`,children:[t.jsx(Ca,{status:ie.status,compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:ie.name}),t.jsx("span",{className:"node-selector-option-status",children:ie.status})]},ie.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[H,He&&M&&(F==="board"||F==="list")&&t.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${F==="board"?" active":""}`,onClick:()=>M("board"),title:"Board view","aria-label":"Board view","aria-pressed":F==="board","data-testid":"mobile-view-toggle-board",children:t.jsx(aa,{size:16})}),t.jsx("button",{className:`view-toggle-btn${F==="list"?" active":""}`,onClick:()=>M("list"),title:"List view","aria-label":"List view","aria-pressed":F==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(Ed,{size:16})})]}),Z&&ce&&(He||F==="board"||F==="list")&&!Te&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:Xn,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx(Fi,{size:16})}),Nt&&t.jsx("button",{className:"btn-icon",onClick:fe,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(Fi,{size:16})}),ce&&He&&o&&t.jsx("button",{className:"btn-icon",onClick:ie=>o(ie.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(Ks,{size:16})}),!He&&M&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${F==="board"?" active":""}`,onClick:()=>M("board"),title:"Board view","aria-label":"Board view","aria-pressed":F==="board",children:t.jsx(aa,{size:16})}),t.jsx("button",{className:`view-toggle-btn${F==="list"?" active":""}`,onClick:()=>M("list"),title:"List view","aria-label":"List view","aria-pressed":F==="list",children:t.jsx(Ed,{size:16})}),q&&t.jsx("button",{className:`view-toggle-btn${F==="agents"?" active":""}`,onClick:()=>M("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":F==="agents",children:t.jsx(Tn,{size:16})}),t.jsx("button",{className:`view-toggle-btn${F==="missions"?" active":""}`,onClick:()=>M("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":F==="missions",children:t.jsx(vs,{size:16})}),t.jsxs("button",{className:`view-toggle-btn${F==="chat"?" active":""}`,onClick:()=>M("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":F==="chat","data-testid":"header-chat-view-btn",children:[t.jsx(Ui,{size:16}),h&&F!=="chat"&&t.jsx("span",{className:"status-dot status-dot--pending header-chat-unread-dot","aria-label":"Unread chat response"})]}),t.jsx("button",{className:`view-toggle-btn${F==="documents"?" active":""}`,onClick:()=>M("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":F==="documents",children:t.jsx(ia,{size:16})}),t.jsxs("button",{className:`view-toggle-btn${F==="mailbox"?" active":""}`,onClick:()=>M("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":F==="mailbox",children:[t.jsx(Na,{size:16}),m>0&&F!=="mailbox"&&t.jsx("span",{className:"status-dot status-dot--pending header-chat-unread-dot","aria-label":"Pending approvals"})]}),Ne.filter(ie=>ie.view.placement==="primary").sort((ie,it)=>(ie.view.order??Number.MAX_SAFE_INTEGER)-(it.view.order??Number.MAX_SAFE_INTEGER)).map(ie=>{const it=no(ie.pluginId,ie.view.viewId),Gt=Ml(ie.view.icon);return t.jsx("button",{className:`view-toggle-btn${F===it||F==="graph"&&ie.pluginId==="fusion-plugin-dependency-graph"&&ie.view.viewId==="graph"?" active":""}`,onClick:()=>M(ie.pluginId==="fusion-plugin-dependency-graph"&&ie.view.viewId==="graph"?"graph":it),title:`${ie.view.label} view`,"aria-label":`${ie.view.label} view`,"aria-pressed":F===it,"data-testid":`view-toggle-plugin-${ie.pluginId}-${ie.view.viewId}`,children:t.jsx(Gt,{size:16})},`${ie.pluginId}:${ie.view.viewId}`)}),Pe&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:Ke,className:`view-toggle-btn${["research","skills","insights","memory","dev-server","devserver","graph"].includes(F)||ve?.evalsView&&F==="evals"||P&&j||rr(F)?" active":""}`,onClick:()=>$e(ie=>!ie),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":Ee,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(rn,{size:12})}),Ee&&t.jsxs("div",{ref:Fe,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[ve?.evalsView&&t.jsxs("button",{className:`view-toggle-overflow-item${F==="evals"?" active":""}`,onClick:()=>{M("evals"),$e(!1)},role:"menuitem","data-testid":"view-overflow-evals",children:[t.jsx(vs,{size:14}),t.jsx("span",{children:"Evals"})]}),ve?.researchView&&t.jsxs("button",{className:`view-toggle-overflow-item${F==="research"?" active":""}`,onClick:()=>{M("research"),$e(!1)},role:"menuitem","data-testid":"view-overflow-research",children:[t.jsx(Fi,{size:14}),t.jsx("span",{children:"Research"})]}),ve?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${F==="insights"?" active":""}`,onClick:()=>{M("insights"),$e(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(ps,{size:14}),t.jsx("span",{children:"Insights"})]}),O&&t.jsxs("button",{className:`view-toggle-overflow-item${F==="skills"?" active":""}`,onClick:()=>{M("skills"),$e(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(Qn,{size:14}),t.jsx("span",{children:"Skills"})]}),ve?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${F==="memory"?" active":""}`,onClick:()=>{M("memory"),$e(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(oo,{size:14}),t.jsx("span",{children:"Memory"})]}),ve?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${F==="dev-server"||F==="devserver"?" active":""}`,onClick:()=>{M("devserver"),$e(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(dr,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]}),P&&v&&t.jsxs("button",{className:`view-toggle-overflow-item${j?" active":""}`,onClick:()=>{v(),$e(!1)},role:"menuitem","data-testid":"view-overflow-todos",children:[t.jsx(lu,{size:14}),t.jsx("span",{children:"Todos"})]}),Ne.filter(ie=>ie.view.placement!=="primary").sort((ie,it)=>(ie.view.order??Number.MAX_SAFE_INTEGER)-(it.view.order??Number.MAX_SAFE_INTEGER)).map(ie=>{const it=no(ie.pluginId,ie.view.viewId),Gt=Ml(ie.view.icon);return t.jsxs("button",{className:`view-toggle-overflow-item${F===it||F==="graph"&&ie.pluginId==="fusion-plugin-dependency-graph"&&ie.view.viewId==="graph"?" active":""}`,onClick:()=>{M(ie.pluginId==="fusion-plugin-dependency-graph"&&ie.view.viewId==="graph"?"graph":it),$e(!1)},role:"menuitem","data-testid":`view-overflow-plugin-${ie.pluginId}-${ie.view.viewId}`,children:[t.jsx(Gt,{size:14}),t.jsx("span",{children:ie.view.label})]},`${ie.pluginId}:${ie.view.viewId}`)})]})]})]}),!Le&&o&&t.jsx("button",{className:"btn-icon",onClick:ie=>o(ie.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"desktop-header-usage-btn",children:t.jsx(Ks,{size:16})}),!Le&&c&&t.jsx("button",{className:"btn-icon",onClick:c,title:"System Stats","data-testid":"desktop-header-system-stats-btn",children:t.jsx(dr,{size:16})}),!Le&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(lo,{size:16})}),!Le&&!vt&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(Hm,{size:16})}),!Le&&t.jsxs("button",{className:`btn-icon${r>0?" btn-icon--has-indicator":""}`,onClick:r>0&&a?a:s,title:r>0?"Resume planning session":"Create a task with AI planning","data-testid":"planning-btn",style:{position:"relative"},children:[t.jsx(_i,{size:16}),r>0&&t.jsx("span",{className:"header-badge header-badge--pulse","data-testid":"planning-badge","aria-label":`${r} active planning session${r!==1?"s":""}`,children:r})]}),!Le&&t.jsxs("div",{className:"terminal-split-btn",ref:Qe,children:[t.jsx("button",{className:"btn-icon btn-icon--terminal terminal-split-btn__main",onClick:S,title:"Open Terminal","data-testid":"terminal-toggle-btn",children:t.jsx(Bi,{size:16})}),b&&y&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"terminal-split-btn__divider"}),t.jsx("button",{ref:It,className:`btn-icon terminal-split-btn__chevron${Ae?" btn-icon--active":""}`,onClick:()=>he(ie=>!ie),title:"Scripts","aria-haspopup":"listbox","aria-expanded":Ae,"aria-label":"Quick scripts","data-testid":"scripts-btn",children:t.jsx(rn,{size:12,className:`quick-scripts-dropdown__trigger-chevron${Ae?" rotate":""}`})}),Ae&&t.jsx("div",{ref:St,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:Xt,"data-testid":"quick-scripts-dropdown",style:Vt?{position:"fixed",top:`${Vt.top}px`,left:`${Vt.left}px`,width:`${Vt.width}px`,right:"auto"}:void 0,children:nt?t.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[t.jsx(xt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):De.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(Bi,{size:16})}),t.jsx("p",{children:"No scripts configured"}),t.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:Yt,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:De.map(([ie,it],Gt)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${wt===Gt?"highlighted":""}`,onClick:()=>_t(ie,it),role:"option","aria-selected":wt===Gt,"data-testid":`quick-script-item-${ie}`,children:[t.jsx(Yn,{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:ie}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:it,children:it.length>50?`${it.slice(0,50)}...`:it})]})]},ie))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${At&&wt===De.length?"highlighted":""}`,onClick:Yt,"data-testid":"quick-scripts-manage",children:[t.jsx(to,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})]}),!Le&&k&&t.jsx("button",{className:`btn-icon${C?" btn-icon--active":""}`,onClick:k,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(bs,{size:16})}),!Le&&p&&t.jsx("button",{className:"btn-icon",onClick:p,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Us,{size:16})}),!Le&&w&&t.jsx("button",{className:"btn-icon",onClick:w,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(Sl,{size:16})}),!Le&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:Jt,className:"btn-icon",onClick:()=>ht(ie=>!ie),title:"More actions","aria-label":"More actions","aria-expanded":ut,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(Nd,{size:16})}),ut&&t.jsxs("div",{ref:an,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[g&&x!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{g(),ht(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx(co,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{rt(f),ht(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(Hi,{size:14}),t.jsx("span",{children:"Automation"})]})]})]}),t.jsxs("div",{className:"engine-control-split-btn",ref:et,children:[t.jsx("button",{className:`btn-icon engine-control-split-btn__main${U?" btn-icon--stopped":""}`,onClick:R,title:U?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:U?t.jsx(Yn,{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${Se?" btn-icon--active":""}`,onClick:()=>we(ie=>!ie),title:"Engine options","aria-haspopup":"menu","aria-expanded":Se,"data-testid":"engine-control-chevron-btn",children:t.jsx(rn,{size:12})}),Se&&t.jsx("div",{className:"engine-control-split-btn__menu",role:"menu",children:t.jsxs("button",{className:`engine-control-split-btn__menu-item${E?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{L?.(),we(!1)},role:"menuitem",title:E?"Resume scheduling":"Pause triage",disabled:!!U,"data-testid":"engine-control-pause-triage-btn",children:[E?t.jsx(Yn,{size:14}):t.jsx(pi,{size:14}),t.jsx("span",{children:E?"Resume scheduling":"Pause triage"})]})})]}),!Le&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(to,{size:16})}),t.jsx(ta,{slotId:"header-action",projectId:qe}),Le&&!He&&t.jsx("button",{ref:on,className:"btn-icon compact-overflow-trigger",onClick:ot,title:"More header actions","aria-label":"More header actions","aria-expanded":Be,"aria-haspopup":"menu",children:t.jsx(Nd,{size:16})}),Le&&!He&&Be&&t.jsxs("div",{ref:fn,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[ge.length>=1&&ne&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>rt(ne),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(Kl,{size:16}),t.jsx("span",{children:"Projects"})]}),k&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>rt(k),role:"menuitem","data-testid":"overflow-files-btn",children:[t.jsx(bs,{size:16}),t.jsx("span",{children:"Browse Files"})]}),t.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>rt(r>0&&a?a:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx(_i,{size:16}),r>0&&t.jsx("span",{className:"header-badge header-badge--pulse","data-testid":"overflow-planning-badge",children:r})]}),t.jsx("span",{children:r>0?`Resume planning session (${r})`:"Create a task with AI planning"})]}),p&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>rt(p),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(Us,{size:16}),t.jsx("span",{children:"Git Manager"})]}),g&&x!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>rt(g),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(co,{size:16}),t.jsx("span",{children:"Nodes"})]}),!vt&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>rt(n),role:"menuitem",children:[t.jsx(Hm,{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:()=>rt(S),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[t.jsx(Bi,{size:16}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>_e(ie=>!ie),role:"menuitem","aria-expanded":Y,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(Mn,{size:14,className:`mobile-overflow-chevron${Y?" mobile-overflow-chevron--open":""}`})})]}),Y&&t.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:Kt?t.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[t.jsx(xt,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):Ft.length>0?t.jsxs(t.Fragment,{children:[Ft.map(([ie,it])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{y&&y(ie,it),ye(!1),_e(!1)},role:"menuitem","data-testid":`overflow-script-item-${ie}`,children:[t.jsx(Yn,{size:14}),t.jsx("span",{children:ie})]},ie)),b&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>rt(b),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(hi,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):b&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>rt(b),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(hi,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>rt(f),role:"menuitem","data-testid":"overflow-schedules-btn",children:[t.jsx(Hi,{size:16}),t.jsx("span",{children:"Automation"})]}),l&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>rt(l),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[t.jsx(lo,{size:16}),t.jsx("span",{children:"View Activity Log"})]}),d&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>rt(d),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(Na,{size:16}),t.jsxs("span",{children:["Mailbox",u>0?` (${u})`:""]}),m>0&&t.jsx("span",{className:"header-badge","data-testid":"overflow-mailbox-approval-badge",children:m})]}),o&&t.jsxs("button",{className:"mobile-overflow-item",onClick:ie=>rt(()=>o(ie.currentTarget.getBoundingClientRect())),role:"menuitem","data-testid":"overflow-usage-btn",children:[t.jsx(Ks,{size:16}),t.jsx("span",{children:"View Usage"})]}),w&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>rt(w),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(Sl,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>rt(e),role:"menuitem",children:[t.jsx(to,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),Ut&&Ye&&t.jsxs("div",{className:"header-floating-search",children:[t.jsxs("div",{className:"header-search",children:[t.jsx(Fi,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:te,onChange:ie=>Z(ie.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:at,"aria-label":"Close search",children:t.jsx(nn,{size:14})})]}),tn&&t.jsxs("div",{className:"header-branch-filters","data-testid":"header-branch-filters-desktop",children:[t.jsxs("label",{className:"header-branch-filter-label",children:[t.jsx("span",{children:"Working branch"}),t.jsxs("select",{className:"header-branch-filter-select",value:K,onChange:ie=>N?.(ie.target.value),"data-testid":"working-branch-filter",children:[t.jsx("option",{value:"",children:"All working branches"}),t.jsx("option",{value:Uo,children:"No working branch"}),I.map(ie=>t.jsx("option",{value:ie,children:ie},ie))]})]}),t.jsxs("label",{className:"header-branch-filter-label",children:[t.jsx("span",{children:"Base branch"}),t.jsxs("select",{className:"header-branch-filter-select",value:A,onChange:ie=>G?.(ie.target.value),"data-testid":"target-branch-filter",children:[t.jsx("option",{value:"",children:"All base branches"}),t.jsx("option",{value:Uo,children:"No base branch"}),$.map(ie=>t.jsx("option",{value:ie,children:ie},ie))]})]})]})]}),Z&&ce&&Te&&t.jsxs("div",{className:"header-floating-search",children:[t.jsxs("div",{ref:zt,className:"header-search mobile-search-expanded",children:[t.jsx(Fi,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:en,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:te,onChange:ie=>Z(ie.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:mt,"aria-label":"Close search",children:t.jsx(nn,{size:14})})]}),tn&&t.jsxs("div",{className:"header-branch-filters","data-testid":"header-branch-filters-mobile",children:[t.jsxs("label",{className:"header-branch-filter-label",children:[t.jsx("span",{children:"Working branch"}),t.jsxs("select",{className:"header-branch-filter-select",value:K,onChange:ie=>N?.(ie.target.value),"data-testid":"working-branch-filter-mobile",children:[t.jsx("option",{value:"",children:"All working branches"}),t.jsx("option",{value:Uo,children:"No working branch"}),I.map(ie=>t.jsx("option",{value:ie,children:ie},ie))]})]}),t.jsxs("label",{className:"header-branch-filter-label",children:[t.jsx("span",{children:"Base branch"}),t.jsxs("select",{className:"header-branch-filter-select",value:A,onChange:ie=>G?.(ie.target.value),"data-testid":"target-branch-filter-mobile",children:[t.jsx("option",{value:"",children:"All base branches"}),t.jsx("option",{value:Uo,children:"No base branch"}),$.map(ie=>t.jsx("option",{value:ie,children:ie},ie))]})]})]})]})]})}const C0={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","memory-dreams-processed"],ntfyDashboardHost:void 0,webhookEnabled:!1,webhookUrl:void 0,webhookFormat:"generic",webhookEvents:[],notificationProviders:[],customProviders:[],defaultProjectId:void 0,setupComplete:void 0,favoriteProviders:void 0,favoriteModels:void 0,openrouterModelSync:!0,opencodeGoModelSync:!0,updateCheckEnabled:!0,fnBinaryCheckEnabled:!0,updateCheckFrequency:"daily",autoReloadOnVersionChange:!0,showGitHubStarButton:!0,githubTrackingDefaultRepo:void 0,modelOnboardingComplete:void 0,useClaudeCli:void 0,useDroidCli:void 0,useLlamaCpp:void 0,executionGlobalProvider:void 0,executionGlobalModelId:void 0,planningGlobalProvider:void 0,planningGlobalModelId:void 0,validatorGlobalProvider:void 0,validatorGlobalModelId:void 0,titleSummarizerGlobalProvider:void 0,titleSummarizerGlobalModelId:void 0,daemonToken:void 0,daemonPort:4040,daemonHost:"127.0.0.1",settingsSyncEnabled:!1,settingsSyncAuth:!1,settingsSyncInterval:9e5,settingsSyncConflictResolution:"last-write-wins",dashboardCurrentNodeId:void 0,dashboardCurrentProjectIdByNode:void 0,vitestAutoKillEnabled:!0,vitestKillThresholdPct:90,persistAgentToolOutput:!0,researchGlobalDefaults:{searchProvider:void 0,synthesisProvider:void 0,synthesisModelId:void 0,enabledSources:{webSearch:!0,pageFetch:!0,github:!1,localDocs:!0,llmSynthesis:!0},maxSourcesPerRun:20,defaultExportFormat:"markdown"},researchGlobalEnabled:!0,researchGlobalMaxConcurrentRuns:3,researchGlobalDefaultTimeout:3e5,researchGlobalMaxSourcesPerRun:20,researchGlobalMaxSynthesisRounds:2,researchGlobalWebSearchProvider:"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:{}},E0={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,preserveProgressOnStuckRequeue:!0,maxPostReviewFixes:1,maxSpawnedAgentsPerParent:5,maxSpawnedAgentsGlobal:20,maintenanceIntervalMs:3e5,autoArchiveDoneTasksEnabled:!0,autoArchiveDoneAfterMs:2880*60*1e3,archiveAgentLogMode:"compact",autoUpdatePrStatus:!1,githubCommentOnDone:!1,githubCommentTemplate:void 0,githubTrackingEnabledByDefault:!1,githubTrackingDefaultRepo:void 0,githubAuthMode:"gh-cli",githubAuthToken:void 0,autoBackupEnabled:!1,autoBackupSchedule:"0 2 * * *",autoBackupRetention:7,autoBackupDir:".fusion/backups",autoSummarizeTitles:!1,useAiMergeCommitSummary:!0,titleSummarizerProvider:void 0,titleSummarizerModelId:void 0,titleSummarizerFallbackProvider:void 0,titleSummarizerFallbackModelId:void 0,scripts:void 0,setupScript:void 0,insightExtractionEnabled:!1,insightExtractionSchedule:"0 2 * * *",insightExtractionMinIntervalMs:864e5,taskEvaluationEnabled:!1,taskEvaluationSchedule:"0 5 * * *",taskEvaluationProvider:void 0,taskEvaluationModelId:void 0,taskEvaluationFollowUpPolicy:"off",taskEvaluationRetention:void 0,memoryEnabled:!0,memoryBackendType:"qmd",memoryAutoSummarizeEnabled:!1,memoryAutoSummarizeThresholdChars:5e4,memoryAutoSummarizeSchedule:"0 3 * * *",memoryDreamsEnabled:!1,memoryDreamsSchedule:"0 4 * * *",tokenCap:void 0,runStepsInNewSessions:!1,maxParallelSteps:2,missionStaleThresholdMs:6e5,missionMaxTaskRetries:3,missionHealthCheckIntervalMs:3e5,agentPrompts:void 0,promptOverrides:void 0,reflectionEnabled:!1,reflectionIntervalMs:36e5,reflectionAfterTask:!0,reviewHandoffPolicy:"disabled",showQuickChatFAB:!1,researchSettings:{enabled:!0,searchProvider:void 0,synthesisProvider:void 0,synthesisModelId:void 0,enabledSources:{webSearch:!0,pageFetch:!0,github:!1,localDocs:!0,llmSynthesis:!0},limits:{maxConcurrentRuns:3,maxSourcesPerRun:20,maxDurationMs:3e5,requestTimeoutMs:3e4}},evalSettings:{enabled:!1,intervalMs:864e5,evaluatorProvider:void 0,evaluatorModelId:void 0,followUpPolicy:"suggest-only",retentionDays:30},researchEnabled:!0,researchMaxConcurrentRuns:3,researchDefaultTimeout:3e5,researchMaxSourcesPerRun:20,researchMaxSynthesisRounds:2},_0=Object.freeze(Object.keys(C0)),M0=Object.freeze(Object.keys(E0));function B6(e){return _0.includes(e)}function H6(e){return M0.includes(e)}function Re(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function A0(e){return!!(e?.provider&&e?.modelId)}function ra(...e){for(const n of e)if(A0(n))return{provider:n.provider,modelId:n.modelId};return{}}function ec(e){return ra({provider:e?.defaultProviderOverride,modelId:e?.defaultModelIdOverride},{provider:e?.defaultProvider,modelId:e?.defaultModelId})}function P0(e){return ra({provider:e?.executionProvider,modelId:e?.executionModelId},{provider:e?.executionGlobalProvider,modelId:e?.executionGlobalModelId},ec(e))}function R0(e){return ra({provider:e?.planningProvider,modelId:e?.planningModelId},{provider:e?.planningGlobalProvider,modelId:e?.planningGlobalModelId},ec(e))}function I0(e){return ra({provider:e?.validatorProvider,modelId:e?.validatorModelId},{provider:e?.validatorGlobalProvider,modelId:e?.validatorGlobalModelId},ec(e))}function q6(e){return ra({provider:e?.titleSummarizerProvider,modelId:e?.titleSummarizerModelId},{provider:e?.titleSummarizerGlobalProvider,modelId:e?.titleSummarizerGlobalModelId},{provider:e?.planningProvider,modelId:e?.planningModelId},ec(e))}function Bg(e,n){return ra({provider:e.modelProvider,modelId:e.modelId},P0(n))}function Hg(e,n){return ra({provider:e.validatorModelProvider,modelId:e.validatorModelId},I0(n))}function qg(e,n){return ra({provider:e.planningModelProvider,modelId:e.planningModelId},R0(n))}const V6=["off","minimal","low","medium","high"],ea=["triage","todo","in-progress","in-review","done","archived"],Al="triage";function xu(e){return typeof e=="string"&&ea.includes(e)}function Vg(e,n=Al){return xu(e)?e:n}const oa=["low","normal","high","urgent"],js="normal",T0=["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"],ns={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},$0={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"},Td={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 D0(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 qm(e){return e==="urgent"?3:e==="high"?2:e==="low"?0:1}function Vm(e,n){return qm(n)-qm(e)}function Nc(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 Wm(e){const n=e.columnMovedAt??e.updatedAt??e.createdAt,s=Date.parse(n);return Number.isFinite(s)?s:0}function Km(e){return e==="merging"||e==="merging-pr"||e==="merging-fix"}function Wg(e,n){return n==="todo"?[...e].sort((s,a)=>{const r=Vm(s.priority,a.priority);return r!==0?r:s.createdAt!==a.createdAt?s.createdAt.localeCompare(a.createdAt):Nc(s.id,a.id)}):[...e].sort((s,a)=>{if(n==="done"){const o=Wm(a)-Wm(s);return o!==0?o:Nc(s.id,a.id)}if(n==="in-review"){const o=Km(s.status),l=Km(a.status);if(o!==l)return o?-1:1}const r=Vm(s.priority,a.priority);return r!==0?r:Nc(s.id,a.id)})}function L0(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 O0({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 Kg=i.createContext(null);function z0({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 kl.createElement(Kg.Provider,{value:d},e,kl.createElement(O0,{isOpen:c!==null,options:c?.options??null,onConfirm:()=>l(!0),onCancel:()=>l(!1)}))}function ai(){const e=i.useContext(Kg);return e||{confirm:async n=>!1}}function F0(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 Gg({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(Ws,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("a",{className:`card-github-badge ${F0(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,href:n.url,target:"_blank",rel:"noopener noreferrer",children:[t.jsx(Vl,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function Bo(e,n){return`${e??"default"}:${n}`}class U0{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=Bo(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const a=Bo(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=Bo(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(Mi(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=Bo(this.projectId,l.taskId),d=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:Gm(l,"prInfo")?l.prInfo??null:d?.prInfo,issueInfo:Gm(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 ba=new U0;let B0=0;function Gm(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function Jg(e){const n=i.useRef(null);n.current===null&&(n.current=`badge-hook-${B0++}`);const s=i.useSyncExternalStore(o=>ba.subscribe(o),()=>ba.getSnapshot(),()=>ba.getSnapshot()),a=i.useCallback(o=>{ba.subscribeTask(n.current,o)},[]),r=i.useCallback(o=>{ba.unsubscribeTask(n.current,o)},[]);return i.useEffect(()=>{ba.setProjectId(e??null)},[e]),i.useEffect(()=>()=>{ba.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:a,unsubscribeFromBadge:r}}function Pl(e,n,s,a){return e===void 0||!n?s:!a||n>=a?e??void 0:s}function H0({taskId:e,prInfo:n,issueInfo:s,updatedAt:a,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:d}=Jg(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=Pl(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??a),f=Pl(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??a);return!h&&!f?null:t.jsx(Gg,{prInfo:h,issueInfo:f})}const q0=i.memo(H0);q0.displayName="TaskCardBadge";const Zs={data:new Map,pendingPromise:null,lastFetchTime:null},V0=5e3;function xl(e,n){return n?`${n}::${e}`:e}function W0(e,n){const s=Zs.data.get(xl(e,n));if(!(!s||Date.now()-s.timestamp>V0))return s}function K0(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 zj(c,e)}catch(h){u=h instanceof Error?h:new Error(String(h));const f=Re(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=Zs.data.get(xl(f,e));return p&&p.timestamp>u})&&Zs.lastFetchTime&&Zs.lastFetchTime>u)return;if(a.current&&(clearTimeout(a.current),a.current=null),Zs.pendingPromise){s(!0);try{await Zs.pendingPromise}finally{s(!1)}return}s(!0);const h=r(c);Zs.pendingPromise=h;try{const f=await h,p=Date.now();for(const[g,x]of Object.entries(f))Zs.data.set(xl(g,e),{result:x,timestamp:p});Zs.lastFetchTime=p}catch{}finally{Zs.pendingPromise=null,s(!1)}},[r,e]),l=i.useCallback(c=>Zs.data.get(xl(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:Zs.lastFetchTime,getBatchData:l}}const $d=new Map,G0=3e4;function Yg(e,n,s,a){return`${e}:${n??""}:${s??""}:${a??""}`}function J0(e,n,s,a){const r=Yg(e,n,s,a),o=$d.get(r);return o?Date.now()>o.expiresAt?($d.delete(r),null):o.stats:null}function Y0(e,n,s,a,r){const o=Yg(e,n,s,a);$d.set(o,{stats:r,expiresAt:Date.now()+G0})}function Q0(e,n,s,a,r={}){const o=r.enabled??!0,l=r.worktree,c=r.stepVersion,d=r.pollIntervalMs,[u,m]=i.useState(null),[h,f]=i.useState(!1);return i.useEffect(()=>{if(!o){m(null),f(!1);return}const p=n==="done"&&!!s,g=(n==="in-progress"||n==="in-review")&&!!l;if(!e||!p&&!g){m(null),f(!1);return}const x=g?l:void 0,w=c!==void 0?String(c):void 0;let b=!1;async function y(k=!1){if(!k){const C=J0(e,a,x,w);if(C){b||(m(C),f(!1));return}}f(!0);try{const C=await Pg(e,x,a);b||(m(C.stats),Y0(e,a,x,w,C.stats))}catch{b||m(null)}finally{b||f(!1)}}y();let S;return d&&g&&(S=setInterval(()=>{y(!0)},d)),()=>{b=!0,S&&clearInterval(S)}},[e,n,s,a,o,l,c,d]),{stats:u,loading:h}}const X0=new Set(["failed","stuck-killed"]);function Rl(e,n,s){if(e.column!=="in-progress"||e.status&&X0.has(e.status)||!n||n<=0)return!1;const a=new Date(e.updatedAt).getTime();return(s??Date.now())-a>n}function Z0(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function eC(e){return e==="done"||e==="skipped"}function tC(e,n,s){const a=s?.get(e)?.trim();if(a)return a;const r=n?.workflowStepName?.trim();return r||e}function Qg(e,n){const s=(e.steps??[]).map((d,u)=>({id:`step-${u}`,name:d.name,status:d.status,source:"step",phase:"pre-merge"})),a=new Map((e.workflowStepResults??[]).map(d=>[d.workflowStepId,d])),r=(e.enabledWorkflowSteps??[]).map(d=>{const u=a.get(d);return{id:`workflow-${d}`,name:tC(d,u,n),status:u?Z0(u.status):"pending",source:"workflow",phase:u?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(d=>eC(d.status)).length;return{total:l,completed:c,items:o}}function nC(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 Xg(e){return e.filter(n=>{const s=typeof n.action=="string"?n.action:"",a=typeof n.outcome=="string"?n.outcome:"";return s.includes("[timing]")||a.includes("[timing]")}).map(n=>{const a=`${n.action??""}
|
|
649
|
+
${n.outcome??""}`.match(/(\d+(?:\.\d+)?)ms\b/i),r=a?Number(a[1]):void 0;return{timestamp:n.timestamp,durationMs:Number.isFinite(r)?r:void 0,summary:nC(n)}})}function Zg(e){if(!e||e.length===0)return null;let n=0,s=0;for(const a of Xg(e))typeof a.durationMs=="number"&&(n+=a.durationMs,s+=1);return s>0?n:null}function Ea(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function eb(e,n){if(!e||e.length===0)return null;let s=0,a=0;for(const r of e){if(!r.startedAt)continue;const o=Ea(r.startedAt);if(o==null)continue;let l;if(r.completedAt){const c=Ea(r.completedAt);if(c==null||c<o)continue;l=c}else l=Math.max(o,n);s+=l-o,a+=1}return a>0?s:null}function tb(e,n,s){const a=Ea(e);if(a==null)return null;const r=Ea(n),o=r!=null&&r>=a?r:s;return Math.max(0,o-a)}const Dd=new Map;async function sC(e,n){const s=Dd.get(e);if(s)return s;try{const a=await Rg(e,n);return Dd.set(e,a.title),a.title}catch{return e}}const Jm=12;function iC(e){return e.length<=Jm?e:e.slice(0,Jm-3)+"..."}const Ld=new Map;async function aC(e,n){const s=Ld.get(e);if(s)return s;try{const a=await Id(e,n);return Ld.set(e,a.name),a.name}catch{return e}}function rC(e){return typeof e=="string"&&oa.includes(e)?e:js}function oC(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}function nb(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 lC(e){return e.sourceType==="agent_heartbeat"||e.sourceType==="automation"||!!nb(e)}const cC=new Set(["triage","todo"]),Ym=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]),Qm=new Set(["merging","merging-pr","merging-fix"]),dC={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},uC=new Set(["in-progress","in-review","done"]),mC=3e4;function hC(e){return e==="merging-fix"?"Merging fixes…":e}function pC(e){const n=Ea(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function Xm(e,n){const s=Ea(e.columnMovedAt??e.updatedAt);return s==null?null:Math.max(0,n-s)}function Gr(e,n){return tb(e.executionStartedAt,e.executionCompletedAt,n)}function fC(e){return e.column==="done"?pC(e):null}function sb(e,n){const s=Ea(e.updatedAt);return s==null?null:Math.max(0,n-s)}function gC(e,n){const s=Gr(e,n);if(s!=null)return s;const a=sb(e,n),r=Jr(e,n);return r!=null?r+(a??0):a}function Jr(e,n){if(typeof e.timedExecutionMs=="number")return e.timedExecutionMs;const s=Zg(e.log),a=eb(e.workflowStepResults,n);return s==null&&a==null?null:(s??0)+(a??0)}function Zm(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 eh(e){if(!e)return null;const n=e.trim();return n.length>0?n:null}function bC(e){const n=eh(e.branch),s=eh(e.baseBranch),a=`fusion/${e.id.toLowerCase()}`,r=n&&(n===a||n.startsWith(`${a}-`))?null:n,o=s?.toLowerCase()==="main"?null:s;return{branch:r,baseBranch:o??null}}function th(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 nh(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 xC(e,n){return e.length!==n.length?!1:e.every((s,a)=>s.name===n[a]?.name&&s.status===n[a]?.status)}function vC(e,n){return e.length!==n.length?!1:e.every((s,a)=>s===n[a])}function yC(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>s===n[a])}function wC(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function kC(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 jC(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 NC(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 SC(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 CC(e,n){const s=e.task,a=n.task;return e.queued===n.queued&&e.projectId===n.projectId&&e.globalPaused===n.globalPaused&&e.taskStuckTimeoutMs===n.taskStuckTimeoutMs&&e.onOpenDetail===n.onOpenDetail&&e.addToast===n.addToast&&e.onUpdateTask===n.onUpdateTask&&e.onArchiveTask===n.onArchiveTask&&e.onUnarchiveTask===n.onUnarchiveTask&&e.onDeleteTask===n.onDeleteTask&&e.onRetryTask===n.onRetryTask&&e.onOpenDetailWithTab===n.onOpenDetailWithTab&&e.onOpenMission===n.onOpenMission&&e.onMoveTask===n.onMoveTask&&e.workflowStepNameLookup===n.workflowStepNameLookup&&e.disableDrag===n.disableDrag&&s.id===a.id&&s.title===a.title&&s.description===a.description&&s.column===a.column&&s.columnMovedAt===a.columnMovedAt&&s.timedExecutionMs===a.timedExecutionMs&&s.updatedAt===a.updatedAt&&s.createdAt===a.createdAt&&s.status===a.status&&s.priority===a.priority&&s.executionMode===a.executionMode&&s.paused===a.paused&&s.error===a.error&&s.size===a.size&&s.blockedBy===a.blockedBy&&s.worktree===a.worktree&&s.branch===a.branch&&s.baseBranch===a.baseBranch&&s.breakIntoSubtasks===a.breakIntoSubtasks&&s.currentStep===a.currentStep&&s.modelProvider===a.modelProvider&&s.modelId===a.modelId&&s.validatorModelProvider===a.validatorModelProvider&&s.validatorModelId===a.validatorModelId&&s.planningModelProvider===a.planningModelProvider&&s.planningModelId===a.planningModelId&&s.reviewLevel===a.reviewLevel&&s.missionId===a.missionId&&s.assignedAgentId===a.assignedAgentId&&s.mergeRetries===a.mergeRetries&&s.sourceType===a.sourceType&&s.sourceAgentId===a.sourceAgentId&&s.sourceMetadata?.issueUrl===a.sourceMetadata?.issueUrl&&s.sourceMetadata?.agentName===a.sourceMetadata?.agentName&&NC(s.attachments,a.attachments)&&SC(s.comments,a.comments)&&vC(s.dependencies,a.dependencies)&&xC(s.steps,a.steps)&&yC(s.enabledWorkflowSteps,a.enabledWorkflowSteps)&&jC(s.workflowStepResults,a.workflowStepResults)&&nh(s.prInfo,a.prInfo)&&nh(s.issueInfo,a.issueInfo)}function EC({task:e,projectId:n,queued:s,onOpenDetail:a,addToast:r,globalPaused:o,onUpdateTask:l,onArchiveTask:c,onUnarchiveTask:d,onDeleteTask:u,onRetryTask:m,onOpenDetailWithTab:h,taskStuckTimeoutMs:f,onOpenMission:p,onMoveTask:g,lastFetchTimeMs:x,workflowStepNameLookup:w,disableDrag:b}){const[y,S]=i.useState(!1),[k,C]=i.useState(!1),[v,j]=i.useState(!1),[P,U]=i.useState(e.description||""),[E,R]=i.useState(!1),[L,F]=i.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(Pe=>Pe.status==="done"||Pe.status==="skipped")),[M,O]=i.useState(null),[q,te]=i.useState(null),[Z,K]=i.useState(!1),[A,I]=i.useState(!1),[$,N]=i.useState(()=>Date.now()),G=i.useRef(null),ge=i.useRef(!1),je=i.useRef(null),ke=i.useRef(null),[ne,qe]=i.useState(!1),{badgeUpdates:ee,subscribeToBadge:le,unsubscribeFromBadge:se}=Jg(n),{confirm:re}=ai(),J=i.useRef(null),B=i.useRef(!1),ve=i.useCallback(Pe=>Pe instanceof Element?!!Pe.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);i.useEffect(()=>{U(e.description||"")},[e.id,e.description]),i.useEffect(()=>{if(!Z)return;const Pe=dt=>{ke.current&&!ke.current.contains(dt.target)&&K(!1)};return document.addEventListener("click",Pe),()=>document.removeEventListener("click",Pe)},[Z]),i.useEffect(()=>{if(!e.missionId){O(null);return}const Pe=Dd.get(e.missionId);if(Pe){O(Pe);return}let dt=!1;return sC(e.missionId,n).then(bt=>{dt||O(bt)}),()=>{dt=!0}},[e.missionId,n]),i.useEffect(()=>{if(!e.assignedAgentId){te(null);return}const Pe=Ld.get(e.assignedAgentId);if(Pe){te(Pe);return}te(null);let dt=!1;return aC(e.assignedAgentId,n).then(bt=>{dt||te(bt)}),()=>{dt=!0}},[e.assignedAgentId,n]),i.useEffect(()=>{if(v&&G.current){const Pe=G.current;Pe.focus(),Pe.style.height="auto",Pe.style.height=Pe.scrollHeight+"px"}},[v]),i.useEffect(()=>{if(typeof IntersectionObserver>"u"){qe(!0);return}const Pe=je.current;if(!Pe)return;const dt=new IntersectionObserver(([bt])=>{qe(bt?.isIntersecting??!0)},{rootMargin:"200px"});return dt.observe(Pe),()=>dt.disconnect()},[v,e.id]);const Ne=i.useCallback(Pe=>{Pe.dataTransfer.setData("text/plain",e.id),Pe.dataTransfer.effectAllowed="move",S(!0)},[e.id]),H=i.useCallback(()=>{S(!1)},[]),be=i.useCallback(Pe=>Pe.dataTransfer.types.includes("Files"),[]),ce=i.useCallback(Pe=>{be(Pe)&&(Pe.preventDefault(),Pe.stopPropagation(),Pe.dataTransfer.dropEffect="copy",C(!0))},[be]),Me=i.useCallback(Pe=>{be(Pe)&&(Pe.preventDefault(),Pe.stopPropagation(),C(!1))},[be]),Le=i.useCallback(async Pe=>{if(!be(Pe))return;Pe.preventDefault(),Pe.stopPropagation(),C(!1);const dt=Array.from(Pe.dataTransfer.files);for(const bt of dt)try{await Zl(e.id,bt,n),r(`Attached ${bt.name} to ${e.id}`,"success")}catch(_t){r(`Failed to attach ${bt.name}: ${Re(_t)}`,"error")}},[e.id,be,r]),He=i.useCallback(()=>{v||a(e)},[e,a,v]),gt=i.useCallback(Pe=>{if(ge.current){ge.current=!1;return}ve(Pe.target)||He()},[He,ve]),Ue=i.useCallback(Pe=>{const dt=Pe.touches[0];dt&&(J.current={x:dt.clientX,y:dt.clientY,time:Date.now()},B.current=!1)},[]),pe=i.useCallback(Pe=>{if(!J.current)return;const dt=Pe.touches[0];if(!dt)return;const bt=Math.abs(dt.clientX-J.current.x),_t=Math.abs(dt.clientY-J.current.y);(bt>sh||_t>sh)&&(B.current=!0)},[]),Oe=i.useCallback(Pe=>{if(ve(Pe.target)||!J.current)return;const bt=Date.now()-J.current.time<_C,_t=!B.current;bt&&_t&&(ge.current=!0,He()),J.current=null,B.current=!1},[He,ve]),ze=i.useCallback(async(Pe,dt)=>{Pe.stopPropagation();try{const bt=await Sa(dt,n);a(bt)}catch{r(`Failed to load dependency ${dt}`,"error")}},[a,r]),lt=e.status==="failed",Be=e.paused===!0,ye=!!(e.paused&&e.pausedByAgentId),Y=rC(e.priority),_e=Y!==js,ct=Rl(e,f,x),pt=e.column==="triage"&&e.status==="awaiting-approval",de=e.column==="archived",Ve=!o&&!s&&!lt&&!Be&&!ct&&!pt&&(e.column==="in-progress"||Ym.has(e.status)),Ee=!b&&!s&&!Be&&!v&&!de,$e=cC.has(e.column)&&!Ve&&!Be&&!s&&l,ut=!!(e.prInfo||e.issueInfo),ht=e.sourceType==="github_import",Se=i.useMemo(()=>bC(e),[e.id,e.branch,e.baseBranch]),we=!!(Se.branch||Se.baseBranch),Ae=wC(e.sourceMetadata),he=lC(e),We=nb(e),me=We?`Created by agent: ${We}`:"Created by agent",nt=!!(e.assignedAgentId&&q===null),Ct=i.useMemo(()=>{const Pe=[];return e.modelProvider&&Pe.push(e.modelProvider),e.validatorModelProvider&&!Pe.includes(e.validatorModelProvider)&&Pe.push(e.validatorModelProvider),e.planningModelProvider&&!Pe.includes(e.planningModelProvider)&&Pe.push(e.planningModelProvider),Pe},[e.modelProvider,e.validatorModelProvider,e.planningModelProvider]),wt=i.useMemo(()=>Qg(e,w),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,w]),$t=wt.total>0&&(e.status==="executing"||e.column==="in-progress");i.useEffect(()=>{if(e.column!=="in-progress"&&e.column!=="in-review")return;const Pe=e.status!=null&&Qm.has(e.status);if(e.column==="in-progress"){const bt=Gr(e,Date.now()),_t=Xm(e,Date.now()),Yt=Jr(e,Date.now());if(bt==null&&_t==null&&Yt==null)return}if(!Pe&&e.column==="in-review"){const bt=Gr(e,Date.now()),_t=Jr(e,Date.now());if(bt==null&&_t==null)return}N(Date.now());const dt=window.setInterval(()=>{N(Date.now())},mC);return()=>window.clearInterval(dt)},[e.column,e.status,e.columnMovedAt,e.updatedAt,e.workflowStepResults,e.timedExecutionMs,e.executionStartedAt,e.executionCompletedAt]);const Vt=i.useMemo(()=>{if(!uC.has(e.column))return null;if(e.status!=null&&Qm.has(e.status)){const Xt=gC(e,$);if(Xt!=null){const Te=th(Xt);if(Te){const Ye=sb(e,$),Nt=Ye==null?null:Zm(Ye),Ut=Nt?`Execution time ${Te}. Merge phase ${Nt}`:`Execution time ${Te}. Merging`;return{label:Te,title:Ut,ariaLabel:Ut}}}}if(e.column==="in-progress"){const Xt=Gr(e,$)??Xm(e,$)??Jr(e,$);if(Xt==null)return null;const Te=Zm(Xt);return Te?{label:Te,title:`In progress ${Te}`,ariaLabel:`In progress ${Te}`}:null}const dt=Gr(e,$)??Jr(e,$);if(dt==null)return null;const bt=th(dt);if(!bt)return null;const _t=fC(e);if(_t==null)return{label:bt,title:`Execution time ${bt}`,ariaLabel:`Execution time ${bt}`};const Yt=new Date(_t).toLocaleString();return{label:bt,title:`Execution time ${bt}. Completed ${Yt}`,ariaLabel:`Execution time ${bt}. Completed ${Yt}`}},[e.column,e.status,e.columnMovedAt,e.timedExecutionMs,e.updatedAt,e.workflowStepResults,e.log,e.executionStartedAt,e.executionCompletedAt,$]);i.useEffect(()=>{if(!ut||!ne){se(e.id);return}return le(e.id),()=>{se(e.id)}},[ut,ne,le,e.id,se]);const Mt=ee.get(`${n??"default"}:${e.id}`),Dt=e.column==="in-progress"||e.column==="in-review",Qt=i.useMemo(()=>e.steps.map(Pe=>`${Pe.name}:${Pe.status}`).join("|"),[e.steps]),{stats:Kt}=Q0(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:ne,worktree:e.worktree,stepVersion:Dt?Qt:void 0,pollIntervalMs:Dt?3e4:void 0}),Bt=i.useMemo(()=>W0(e.id,n),[e.id,n]),on=i.useMemo(()=>{const Pe=Mt?.prInfo,dt=Mt?.timestamp,bt=Bt?.result?.prInfo,_t=Bt?.timestamp?new Date(Bt.timestamp).toISOString():void 0,Yt=e.prInfo,Xt=e.prInfo?.lastCheckedAt??e.updatedAt;let Te=Pl(Pe,dt,Yt,Xt);const Ye=dt&&dt>=Xt?dt:Xt;return bt&&_t&&(!Ye||_t>Ye)&&(Te=bt),Te},[Mt,Bt,e.prInfo,e.updatedAt]),fn=i.useMemo(()=>{const Pe=Mt?.issueInfo,dt=Mt?.timestamp,bt=Bt?.result?.issueInfo,_t=Bt?.timestamp?new Date(Bt.timestamp).toISOString():void 0,Yt=e.issueInfo,Xt=e.issueInfo?.lastCheckedAt??e.updatedAt;let Te=Pl(Pe,dt,Yt,Xt);const Ye=dt&&dt>=Xt?dt:Xt;return bt&&_t&&(!Ye||_t>Ye)&&(Te=bt),Te},[Mt,Bt,e.issueInfo,e.updatedAt]),Jt=i.useCallback(Pe=>{Pe?.stopPropagation(),!(!$e||E)&&(j(!0),U(e.description||""))},[$e,E,e.description]),an=i.useCallback(()=>{j(!1),U(e.description||"")},[e.description]),zt=i.useCallback(()=>P!==(e.description||""),[P,e.description]),en=i.useCallback(async()=>{if(!(!l||E)){if(!zt()){an();return}R(!0);try{await l(e.id,{description:P.trim()||void 0}),r(`Updated ${e.id}`,"success"),j(!1)}catch(Pe){r(`Failed to update ${e.id}: ${Re(Pe)}`,"error")}finally{R(!1)}}},[l,e.id,P,E,zt,an,r]),Zt=i.useCallback(Pe=>{Pe.key==="Enter"&&!Pe.shiftKey?(Pe.preventDefault(),en()):Pe.key==="Escape"&&(Pe.preventDefault(),an())},[en,an]),dn=i.useCallback(()=>{setTimeout(()=>{const Pe=document.activeElement;Pe===G.current||Pe?.closest(".card-editing-content")||(zt()?en():an())},0)},[zt,en,an]),xe=i.useCallback(Pe=>{$e&&(Pe.stopPropagation(),Jt(Pe))},[$e,Jt]),Fe=i.useCallback(Pe=>{Pe.stopPropagation(),Jt(Pe)},[Jt]),Ke=i.useCallback(Pe=>{U(Pe.target.value);const dt=Pe.target;dt.style.height="auto",dt.style.height=dt.scrollHeight+"px"},[]),et=i.useCallback(Pe=>{Pe.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch(dt=>{r(`Failed to archive ${e.id}: ${Re(dt)}`,"error")})},[r,c,e.id]),Qe=i.useCallback(Pe=>{Pe.stopPropagation(),d&&d(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch(dt=>{r(`Failed to unarchive ${e.id}: ${Re(dt)}`,"error")})},[r,d,e.id]),It=i.useCallback(async Pe=>{if(Pe.stopPropagation(),!(!u||!await re({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0})))try{await u(e.id),r(`Deleted ${e.id}`,"success")}catch(bt){const _t=kC(bt);if(!_t||_t.dependentIds.length===0){r(`Failed to delete ${e.id}: ${Re(bt)}`,"error");return}const Yt=_t.dependentIds.join(", ");if(!await re({title:"Force Delete Task",message:`${e.id} is a dependency of ${Yt}.
|
|
650
|
+
|
|
651
|
+
Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await u(e.id,{removeDependencyReferences:!0}),r(`Deleted ${e.id} after removing dependency references`,"success")}catch(Te){r(`Failed to delete ${e.id}: ${Re(Te)}`,"error")}}},[r,re,u,e.id]),St=i.useCallback(Pe=>{Pe.stopPropagation(),h?.(e,"changes")},[e,h]),Ht=i.useCallback(Pe=>{Pe.stopPropagation(),F(dt=>!dt)},[]),jt=i.useCallback(Pe=>{Pe.stopPropagation(),e.missionId&&p&&p(e.missionId)},[e.missionId,p]),ae=i.useCallback(Pe=>{Pe.stopPropagation(),K(dt=>!dt)},[]),De=i.useCallback(async(Pe,dt)=>{if(Pe.stopPropagation(),K(!1),!!g)try{const bt=e.steps.some(Xt=>Xt.status!=="pending"),_t=(dt==="todo"||dt==="triage")&&bt;let Yt;if(_t){if(await re({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Yt={preserveProgress:!0};else if(!await re({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,dt,Yt),r(`Moved ${e.id} to ${ns[dt]}`,"success")}catch(bt){r(`Failed to move ${e.id}: ${Re(bt)}`,"error")}},[r,re,g,e.id,e.steps]),At=i.useCallback(async Pe=>{if(Pe.stopPropagation(),!(!m||A)){I(!0);try{await m(e.id)}catch(dt){r(`Failed to retry ${e.id}: ${Re(dt)}`,"error")}finally{I(!1)}}},[r,A,m,e.id]),Lt=`card${y?" dragging":""}${s?" queued":""}${Ve?" agent-active":""}${lt?" failed":""}${Be?" paused":""}${ct?" stuck":""}${pt?" awaiting-approval":""}${k?" file-drop-target":""}${v?" card-editing":""}${E?" card-saving":""}`,Ft=(()=>{if(e.column==="in-progress"){const Pe=Kt?.filesChanged,dt=Pe==null||Pe===0?e.modifiedFiles?.length:void 0,bt=Pe!=null&&Pe>0?Pe:dt;return bt==null||bt===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:St,disabled:!h,children:[t.jsx(bs,{size:12}),t.jsxs("span",{children:[bt," ",bt===1?"file":"files"," changed"]})]})}if(e.column==="in-review"){const Pe=Kt?.filesChanged,dt=Pe==null||Pe===0?e.modifiedFiles?.length:void 0,bt=Pe!=null&&Pe>0?Pe:dt;return bt==null||bt===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:St,disabled:!h,children:[t.jsx(bs,{size:12}),t.jsxs("span",{children:[bt," ",bt===1?"file":"files"," changed"]})]})}if(e.column==="done"){const Pe=Kt?.filesChanged,dt=e.mergeDetails?.filesChanged,bt=Pe??dt;if(bt!=null&&bt>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:St,disabled:!h,children:[t.jsx(bs,{size:12}),t.jsxs("span",{children:[bt," ",bt===1?"file":"files"," changed"]})]});const _t=e.modifiedFiles?.length;if(_t!=null&&_t>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:St,disabled:!h,children:[t.jsx(bs,{size:12}),t.jsxs("span",{children:[_t," ",_t===1?"file":"files"," changed"]})]})}return null})();return v?t.jsx("div",{ref:je,className:Lt,"data-id":e.id,"data-column":e.column,onDoubleClick:xe,children:t.jsxs("div",{className:"card-editing-content",children:[t.jsx("textarea",{ref:G,className:"card-edit-desc-textarea",placeholder:"Task description",value:P,onChange:Ke,onKeyDown:Zt,onBlur:dn,disabled:E,rows:4}),E&&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:je,className:Lt,"data-id":e.id,"data-column":e.column,draggable:Ee,onDragStart:Ee?Ne:void 0,onDragEnd:Ee?H:void 0,onDragOver:ce,onDragLeave:Me,onDrop:Le,onClick:gt,onTouchStart:Ue,onTouchMove:pe,onTouchEnd:Oe,onDoubleClick:xe,children:[t.jsxs("div",{className:"card-header",children:[t.jsx("span",{className:"card-id",children:e.id}),Be&&t.jsx("span",{className:"card-status-badge paused",children:ye?"paused by agent":"paused"}),!Be&&e.status&&e.status!=="queued"&&t.jsx("span",{className:`card-status-badge card-status-badge--${e.column}${pt?" awaiting-approval":""}${Ym.has(e.status)?" pulsing":""}${lt?" failed":""}${ct?" stuck":""}`,children:ct?"Stuck":pt?"Awaiting Approval":hC(e.status)}),ct&&(Be||!e.status||e.status==="queued")&&t.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),ut&&t.jsx(Gg,{prInfo:on,issueInfo:fn}),he&&t.jsxs("span",{className:"card-agent-created-badge",title:me,"aria-label":me,children:[t.jsx(Tn,{size:11,"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:me}),t.jsx("span",{"aria-hidden":"true",children:"Agent"})]}),_e&&t.jsx("span",{className:`card-priority-badge card-priority-badge--${Y}`,children:Y}),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(Qn,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),e.missionId&&t.jsxs("span",{className:"card-mission-badge",onClick:jt,title:`Mission: ${M??e.missionId}`,role:p?"button":void 0,tabIndex:p?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.jsx(vs,{size:11}),iC(M??e.missionId)]}),t.jsxs("div",{className:"card-header-actions",children:[$e&&t.jsx("button",{className:"card-edit-btn",onClick:Fe,title:"Edit task","aria-label":"Edit task",children:t.jsx(Ds,{size:12})}),e.column==="triage"&&u&&t.jsx("button",{className:"card-delete-btn",onClick:It,title:"Delete task","aria-label":"Delete task",children:t.jsx(vn,{size:12})}),e.column==="done"&&c&&t.jsx("button",{className:"card-archive-btn",onClick:et,title:"Archive task","aria-label":"Archive task",children:"Archive"}),e.column==="archived"&&d&&t.jsx("button",{className:"card-unarchive-btn",onClick:Qe,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),e.column==="in-progress"&&g&&t.jsxs("div",{className:"card-send-back",ref:ke,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:ae,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":Z,children:["Send back",t.jsx(rn,{size:10})]}),Z&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:Td["in-progress"].filter(Pe=>Pe!=="in-review").map(Pe=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:dt=>De(dt,Pe),children:ns[Pe]},Pe))})]}),e.column==="in-review"&&g&&t.jsxs("div",{className:"card-send-back",ref:ke,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:ae,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":Z,children:["Move",t.jsx(rn,{size:10})]}),Z&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:Td["in-review"].map(Pe=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:dt=>De(dt,Pe),children:Pe==="done"?"Done (no merge)":ns[Pe]},Pe))})]}),e.size&&t.jsx("span",{className:`card-size-badge size-${e.size.toLowerCase()}`,children:e.size})]})]}),lt&&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:At,disabled:A,children:[t.jsx(Lw,{size:12}),A?"Retrying…":"Retry"]})]}),t.jsx("div",{className:"card-title",title:e.title||e.description||void 0,children:ah(e.title,ih)||ah(e.description,ih)||e.id}),we&&t.jsxs("div",{className:"card-branch-row","aria-label":"Branch metadata",children:[Se.branch&&t.jsxs("span",{className:"card-branch-chip",title:Se.branch,children:[t.jsx("span",{className:"card-branch-label",children:"Branch"}),t.jsx("span",{className:"card-branch-value",children:Se.branch})]}),Se.baseBranch&&t.jsxs("span",{className:"card-branch-chip",title:Se.baseBranch,children:[t.jsx("span",{className:"card-branch-label",children:"Base"}),t.jsx("span",{className:"card-branch-value",children:Se.baseBranch})]})]}),$t&&(()=>{const Pe=wt.completed/wt.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:`${Pe}%`,backgroundColor:dC[e.column]}})}),t.jsxs("span",{className:"card-progress-label",children:[wt.completed,"/",wt.total]})]}),t.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:Ht,"aria-expanded":L,"aria-label":L?"Hide steps":"Show steps",children:[t.jsxs("span",{children:[wt.total," step",wt.total===1?"":"s"]}),t.jsx(rn,{size:14,className:`card-steps-toggle-icon${L?" expanded":""}`})]}),L&&t.jsx("div",{className:"card-steps-list",children:wt.items.map(dt=>{const bt=dt.source==="workflow"&&dt.status==="failed";return t.jsxs("div",{className:"card-step-item",children:[t.jsx("span",{className:`card-step-dot card-step-dot--${dt.status}${bt?" card-step-dot--workflow-failed":""}`,"aria-hidden":"true"}),t.jsx("span",{className:`card-step-name${dt.status==="done"?" completed":""}`,children:dt.name}),dt.source==="workflow"&&t.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${dt.phase}`,title:"Workflow check",children:"workflow"})]},dt.id)})})]})})(),(Ft||Vt||ht)&&t.jsxs("div",{className:"card-footer-row",children:[Ft,ht&&t.jsx("span",{className:"card-source-provenance",title:Ae?`Imported from GitHub: ${Ae}`:"Imported from GitHub","aria-label":"Imported from GitHub",children:t.jsx(Sn,{provider:"github",size:"sm"})}),Vt&&t.jsxs("span",{className:"card-time-indicator",title:Vt.title,"aria-label":Vt.ariaLabel,children:[t.jsx(Hi,{size:12}),t.jsx("span",{children:Vt.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(Pe=>t.jsxs("span",{className:"card-dep-badge clickable",onClick:dt=>void ze(dt,Pe),title:`Click to view ${Pe}`,children:[t.jsx(cr,{size:12,style:{verticalAlign:"middle"}})," ",Pe]},Pe))}),e.blockedBy&&t.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${e.blockedBy} (file overlap)`,children:[t.jsx(ja,{size:12,style:{verticalAlign:"middle"}})," ",e.blockedBy]}),(s||e.status==="queued")&&e.column!=="in-progress"&&t.jsxs("span",{className:"queued-badge",children:[t.jsx(Hi,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),(e.assignedAgentId||Ct.length>0)&&t.jsxs("div",{className:"card-agent-row",children:[Ct.length>0&&t.jsx("span",{className:"card-provider-icons","data-testid":"card-provider-icons",children:Ct.map(Pe=>t.jsx(Sn,{provider:Pe,size:"sm"},Pe))}),e.assignedAgentId&&t.jsxs("span",{className:`card-agent-badge${nt?" card-agent-badge--loading":""}`,title:`Assigned to ${q??e.assignedAgentId}`,children:[t.jsx(Tn,{size:11}),t.jsx("span",{className:"card-agent-badge-text","aria-hidden":"true",children:oC(q??e.assignedAgentId,15)}),t.jsxs("span",{className:"visually-hidden",children:["Assigned to ",q??e.assignedAgentId]})]})]}),t.jsx(ta,{slotId:"task-card-badge",projectId:n})]})}const sh=10,_C=300,ih=140;function ah(e,n){return e?e.length>n?e.slice(0,n)+"…":e:""}const ho=i.memo(EC,CC);ho.displayName="TaskCard";function MC({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(Zv,{size:14}):t.jsx(Us,{size:14})}),t.jsx("span",{className:"worktree-label",children:e})]}),n.map(g=>t.jsx(ho,{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(ho,{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 ib=i.memo(MC);ib.displayName="WorktreeGroup";function rh(e){return e.toLowerCase().replace(/[-_./]/g,"")}function AC(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 PC(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 RC(e,n){const s=rh(e),a=rh(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&&AC(s,o)||s.length>=4&&PC(s,o,1))return!0;return!1}function IC(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=>RC(o,r))})}function ys({models:e,value:n,onChange:s,placeholder:a="Select a model…",disabled:r=!1,id:o,label:l,favoriteProviders:c=[],onToggleFavorite:d,favoriteModels:u=[],onToggleModelFavorite:m,noChangeValue:h,noChangeLabel:f="No change"}){const[p,g]=i.useState(!1),[x,w]=i.useState(""),[b,y]=i.useState(0),[S,k]=i.useState(null),[C,v]=i.useState(null),j=i.useRef(null),P=i.useRef(null),U=i.useRef(null),E=i.useRef(null),R=i.useRef(null),L=i.useMemo(()=>IC(e,x),[e,x]),F=i.useMemo(()=>L.reduce((se,re)=>((se[re.provider]??=[]).push(re),se),{}),[L]),M=i.useMemo(()=>{const se=[];for(const re of u){const J=re.indexOf("/");if(J===-1)continue;const B=re.slice(0,J),ve=re.slice(J+1),Ne=L.find(H=>H.provider===B&&H.id===ve);Ne&&se.push({model:Ne,fullId:re})}return se},[u,L]),O=i.useMemo(()=>{const se=Object.entries(F),re=new Set(c);return se.sort(([J],[B])=>{const ve=re.has(J),Ne=re.has(B);if(ve&&!Ne)return-1;if(!ve&&Ne)return 1;if(ve&&Ne){const H=c.indexOf(J),be=c.indexOf(B);if(H!==be)return H-be}return J.localeCompare(B)})},[F,c]),q=typeof h=="string"&&h.length>0,te=i.useMemo(()=>{if(!n||q&&n===h)return null;const se=n.indexOf("/");return se===-1?null:n.slice(0,se)},[q,h,n]),Z=i.useMemo(()=>{const se=[];return q&&se.push({type:"no-change",value:h,label:f}),se.push({type:"default",value:"",label:"Use default"}),se},[q,f,h]),K=i.useMemo(()=>{const se=[...Z];for(const{model:re,fullId:J}of M)se.push({type:"favorite",value:J,label:re.name,provider:re.provider});return O.forEach(([re,J])=>{se.push({type:"provider",value:`__group_${re}`,label:re,provider:re}),J.forEach(B=>{se.push({type:"model",value:`${B.provider}/${B.id}`,label:B.name,provider:B.provider})})}),se},[M,O,Z]),A=i.useMemo(()=>{if(q&&n===h)return f;if(!n)return"Use default";const se=n.indexOf("/");if(se===-1)return n;const re=n.slice(0,se),J=n.slice(se+1);return e.find(ve=>ve.provider===re&&ve.id===J)?.name||n},[q,f,h,n,e]),I=i.useMemo(()=>K.findIndex(se=>se.value===n),[K,n]),$=i.useCallback(()=>{const se=window.visualViewport;return se&&se.height>0&&se.width>0?{width:se.width,height:se.height,offsetTop:se.offsetTop,offsetLeft:se.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),N=i.useCallback(()=>{const{height:se}=$(),re=typeof window.matchMedia=="function",J=re?window.matchMedia("(max-width: 640px)").matches:!1,B=re?window.matchMedia("(max-width: 768px)").matches:!1;return se<=0?320:J?Math.min(se*.6,360):B?Math.min(se*.7,420):320},[$]),G=i.useCallback(()=>{const se=P.current;if(!se)return;const re=se.getBoundingClientRect(),{width:J,height:B,offsetTop:ve,offsetLeft:Ne}=$(),H=16,be=16,ce=4,Me=N(),Le=re.bottom-ve,He=re.top-ve,gt=re.left-Ne,Ue=B-Le,pe=He,Oe=Math.max(Ue-be-ce,160),ze=Math.max(pe-be-ce,160),lt=Ue<Me&&pe>Ue,Be=Math.max(Math.min(lt?ze:Oe,Me),160),ye=Math.min(re.width,J-H*2),Y=Math.min(Math.max(gt,H),J-H-ye)+Ne,_e=lt?Math.max(be+ve,He-Be-ce+ve):Math.min(Le+ce+ve,B+ve-be-Be);k({top:_e,left:Y,width:ye,maxHeight:Be})},[$,N]);i.useEffect(()=>{v(document.body)},[]);const ge=i.useRef(!1);i.useEffect(()=>{if(!p){ge.current=!1;return}if(ge.current||K.length===0)return;const se=K.findIndex((re,J)=>J>=(I>=0?I:0)&&re.type!=="provider");y(se>=0?se:0),ge.current=!0},[p,K,I]),i.useEffect(()=>{p&&ge.current&&(y(0),R.current&&(R.current.scrollTop=0))},[x,p]),i.useEffect(()=>{if(!p)return;G();const se=requestAnimationFrame(()=>E.current?.focus());return()=>cancelAnimationFrame(se)},[p,G]),i.useEffect(()=>{if(!p)return;const se=()=>G();window.addEventListener("resize",se),window.addEventListener("scroll",se,!0);const re=window.visualViewport;return re&&(re.addEventListener("resize",se),re.addEventListener("scroll",se)),()=>{window.removeEventListener("resize",se),window.removeEventListener("scroll",se,!0),re&&(re.removeEventListener("resize",se),re.removeEventListener("scroll",se))}},[p,G]),i.useEffect(()=>{if(!p)return;const se=re=>{const J=re.target,B=j.current?.contains(J),ve=U.current?.contains(J);!B&&!ve&&(g(!1),w(""))};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[p]);const je=i.useCallback(se=>{switch(se.key){case"ArrowDown":if(se.preventDefault(),!p)g(!0);else{let re=b;for(let J=1;J<=K.length;J++){const B=(b+J)%K.length;if(K[B]?.type!=="provider"){re=B;break}}y(re)}break;case"ArrowUp":if(se.preventDefault(),p){let re=b;for(let J=1;J<=K.length;J++){const B=(b-J+K.length)%K.length;if(K[B]?.type!=="provider"){re=B;break}}y(re)}break;case"Enter":if(se.preventDefault(),p){const re=K[b];re&&re.type!=="provider"&&re.type!=="favorite"&&(s(re.value),g(!1),w(""))}else g(!0);break;case"Escape":se.preventDefault(),g(!1),w("");break;case"Tab":p&&(g(!1),w(""));break}},[p,b,K,s]),ke=i.useCallback(se=>{s(se),g(!1),w("")},[s]),ne=i.useCallback(()=>{w(""),E.current?.focus()},[]),qe=i.useCallback(()=>{r||g(se=>!se)},[r]);i.useEffect(()=>{if(p&&R.current){const se=R.current.querySelector(`[data-index="${b}"]`);se&&typeof se.scrollIntoView=="function"&&se.scrollIntoView({block:"nearest"})}},[b,p]);const ee=x.length>0,le=p&&S?t.jsxs("div",{ref:U,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:je,style:{top:`${S.top}px`,left:`${S.left}px`,width:`${S.width}px`,maxHeight:`${S.maxHeight}px`},children:[t.jsxs("div",{className:"model-combobox-search-wrapper",children:[t.jsx("input",{ref:E,type:"text",className:"model-combobox-search",placeholder:"Filter models…",value:x,onChange:se=>w(se.target.value),onClick:se=>se.stopPropagation()}),ee&&t.jsx("button",{type:"button",className:"model-combobox-clear",onClick:ne,"aria-label":"Clear filter",children:"×"})]}),t.jsxs("div",{className:"model-combobox-results-count",children:[L.length," model",L.length!==1?"s":""]}),t.jsxs("div",{ref:R,className:"model-combobox-list",children:[Z.map((se,re)=>t.jsx("div",{"data-index":re,className:`model-combobox-option ${b===re?"model-combobox-option--highlighted":""} ${n===se.value?"model-combobox-option--selected":""}`,onClick:()=>ke(se.value),onMouseEnter:()=>y(re),role:"option","aria-selected":n===se.value,children:t.jsx("span",{className:"model-combobox-option-text model-combobox-option-text--default",children:se.label})},`${se.type}-${se.value}`)),M.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"model-combobox-divider"}),M.map(({model:se,fullId:re},J)=>{const B=J+Z.length,ve=b===B,Ne=n===re;return t.jsxs("div",{"data-index":B,className:`model-combobox-option model-combobox-option--favorite ${ve?"model-combobox-option--highlighted":""} ${Ne?"model-combobox-option--selected":""}`,onClick:()=>ke(re),onMouseEnter:()=>y(B),role:"option","aria-selected":Ne,children:[t.jsxs("span",{className:"model-combobox-option-main",children:[t.jsx("span",{className:"model-combobox-option-icon",children:t.jsx(Sn,{provider:se.provider,size:"sm"})}),t.jsx("span",{className:"model-combobox-option-text",children:se.name})]}),t.jsx("span",{className:"model-combobox-option-id",children:se.id}),m&&t.jsx("button",{type:"button",className:"model-combobox-option-favorite model-combobox-option-favorite--active",onClick:H=>{H.stopPropagation(),m(re)},title:"Remove from favorites","aria-label":`Remove ${se.name} from favorites`,children:"★"})]},re)}),t.jsx("div",{className:"model-combobox-divider"})]}),O.map(([se,re])=>{const J=K.findIndex(Ne=>Ne.value===`__group_${se}`),B=c.includes(se),ve=re.filter(Ne=>{const H=`${Ne.provider}/${Ne.id}`;return!u.includes(H)});return ve.length===0?null:t.jsxs("div",{className:"model-combobox-group",children:[t.jsxs("div",{className:"model-combobox-optgroup","data-index":J,children:[t.jsx(Sn,{provider:se,size:"sm"}),t.jsx("span",{className:"model-combobox-optgroup-text",children:se}),d&&t.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${B?"model-combobox-optgroup-favorite--active":""}`,onClick:Ne=>{Ne.stopPropagation(),d(se)},title:B?"Remove from favorites":"Add to favorites","aria-label":B?`Remove ${se} from favorites`:`Add ${se} to favorites`,children:"★"})]}),ve.map(Ne=>{const H=`${Ne.provider}/${Ne.id}`,be=K.findIndex(He=>He.value===H),ce=b===be,Me=n===H,Le=u.includes(H);return t.jsxs("div",{"data-index":be,className:`model-combobox-option ${ce?"model-combobox-option--highlighted":""} ${Me?"model-combobox-option--selected":""}`,onClick:()=>ke(H),onMouseEnter:()=>y(be),role:"option","aria-selected":Me,children:[t.jsx("span",{className:"model-combobox-option-text",children:Ne.name}),t.jsx("span",{className:"model-combobox-option-id",children:Ne.id}),m&&t.jsx("button",{type:"button",className:`model-combobox-option-favorite ${Le?"model-combobox-option-favorite--active":""}`,onClick:He=>{He.stopPropagation(),m(H)},title:Le?"Remove from favorites":"Add to favorites","aria-label":Le?`Remove ${Ne.name} from favorites`:`Add ${Ne.name} to favorites`,children:Le?"★":"☆"})]},H)})]},se)}),L.length===0&&ee&&t.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",x,"'"]})]})]}):null;return t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:j,className:"model-combobox",onKeyDown:je,children:t.jsxs("button",{ref:P,type:"button",id:o,className:"model-combobox-trigger",onClick:qe,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":l,children:[te&&t.jsx("span",{className:"model-combobox-trigger-icon",children:t.jsx(Sn,{provider:te,size:"sm"})}),t.jsx("span",{className:"model-combobox-trigger-text",children:A||a}),t.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),C&&le?va.createPortal(le,C):null]})}function vu(e,n){return typeof n!="string"||n.length===0?e:`kb:${n}:${e}`}function Dn(e,n){if(typeof window>"u")return null;const s=window.localStorage?.getItem;return typeof s!="function"?null:s.call(window.localStorage,vu(e,n))}function os(e,n,s){if(typeof window>"u")return;const a=window.localStorage?.setItem;typeof a=="function"&&a.call(window.localStorage,vu(e,s),n)}function pr(e,n){if(typeof window>"u")return;const s=window.localStorage?.removeItem;typeof s=="function"&&s.call(window.localStorage,vu(e,n))}const TC=1e4,$C=1e3;function tc(){const[e,n]=i.useState([]),[s,a]=i.useState(!0),[r,o]=i.useState(null),l=i.useRef(null),c=i.useRef(0),d=i.useCallback(async()=>{try{o(null);const b=await _l();n(b)}catch(b){o(b instanceof Error?b.message:"Failed to fetch nodes")}},[]);i.useEffect(()=>{let b=!1;async function y(){a(!0);try{const k=await _l();b||(n(k),o(null))}catch(k){b||o(k instanceof Error?k.message:"Failed to fetch nodes")}finally{b||a(!1)}}y();const S=()=>{if(document.visibilityState!=="visible")return;const k=Date.now();k-c.current<$C||(c.current=k,d())};return document.addEventListener("visibilitychange",S),()=>{b=!0,document.removeEventListener("visibilitychange",S)}},[d]),i.useEffect(()=>{if(!s)return l.current=setInterval(()=>{d()},TC),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,d]);const u=i.useCallback(async b=>{const{projectMappings:y,...S}=b,k=await lS(S);if(y.length>0)try{await K1(k.id,y)}catch(C){const v=C instanceof Error?C.message:"Failed to persist project mappings";let j="";try{await xm(k.id)}catch(P){j=P instanceof Error?P.message:"Failed to unregister node after mapping failure"}throw await d(),j?new Error(`${v}. Cleanup also failed: ${j}`):new Error(v)}return await d(),k},[d]),m=i.useCallback(async(b,y)=>{const S=await dS(b,y);return n(k=>k.map(C=>C.id===b?S:C)),S},[]),h=i.useCallback(async b=>{await xm(b),n(y=>y.filter(S=>S.id!==b))},[]),f=i.useCallback(async b=>{const y=await pS(b);n(S=>S.map(k=>k.id===b?{...k,status:y.status,updatedAt:y.checkedAt}:k))},[]),p=i.useCallback(b=>uS(b),[]),g=i.useCallback(async(b,y)=>{const S=await mS(b,y);return n(k=>k.map(C=>C.id===b?{...C,dockerConfig:S}:C)),S},[]),x=i.useCallback(async b=>{const y=await hS(b);return"persistedVersion"in y?y:{persistedVersion:0,deployedVersion:null,needsRecreate:!1}},[]),w=i.useCallback(async b=>cS(b),[]);return{nodes:e,loading:s,error:r,refresh:d,register:u,update:m,unregister:h,healthCheck:f,fetchDockerConfig:p,patchDockerConfig:g,fetchDockerDiff:x,discoverRemoteProjects:w}}const Ir="kb-quick-entry-text",DC=["image/png","image/jpeg","image/gif","image/webp"];function LC(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function Sc(e,n){return e&&n?`${e}/${n}`:""}function Cc(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 ab({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"&&Dn(Ir,l)||""),[g,x]=i.useState(!1),[w,b]=i.useState(!1),[y,S]=i.useState(!1),k=i.useRef(null),C=i.useRef(null),v=i.useRef(!1),j=i.useRef(l),[P,U]=i.useState([]),E=i.useRef([]),[R,L]=i.useState([]),[F,M]=i.useState(!1),[O,q]=i.useState(""),[te,Z]=i.useState(null),[K,A]=i.useState([]),[I,$]=i.useState(void 0),[N,G]=i.useState(!1),[ge,je]=i.useState(!1),[ke,ne]=i.useState(!1),[qe,ee]=i.useState(!1),[le,se]=i.useState(!1),[re,J]=i.useState(null),[B,ve]=i.useState(void 0),[Ne,H]=i.useState(void 0),[be,ce]=i.useState(void 0),[Me,Le]=i.useState(void 0),[He,gt]=i.useState(void 0),[Ue,pe]=i.useState(void 0),Oe=i.useRef(null),ze=i.useRef(null),lt=i.useRef(null),Be=i.useRef(null),ye=i.useRef(null),Y=i.useRef(null),_e=i.useRef(null),ct=i.useRef(null),[pt,de]=i.useState(null),[Ve,Ee]=i.useState(null),[$e,ut]=i.useState(null),[ht,Se]=i.useState(null),we=i.useRef(null),Ae=i.useRef(null),[he,We]=i.useState(null),[me]=i.useState(()=>typeof document<"u"?document.body:null),[nt,Ct]=i.useState(!1),[wt,$t]=i.useState(null),[Vt,Mt]=i.useState(a??[]),[Dt,Qt]=i.useState([]),[Kt,Bt]=i.useState([]),[on,fn]=i.useState(null),[Jt,an]=i.useState(void 0),[zt,en]=i.useState(!1),[Zt,dn]=i.useState(js),[xe,Fe]=i.useState(void 0),{nodes:Ke}=tc(),[et,Qe]=i.useState(!1),[It,St]=i.useState(!1),Ht=i.useRef(null),jt=i.useRef(null),[ae,De]=i.useState(null),At=d??Dt,Lt=u??Kt,Ft=!e;i.useEffect(()=>{if(a)Mt(a),Ct(!1),$t(null);else{let X=!1;return Ct(!0),$t(null),Os().then(_=>{X||(Mt(_.models),d||Qt(_.favoriteProviders),u||Bt(_.favoriteModels))}).catch(_=>{X||$t(Re(_)||"Failed to load models")}).finally(()=>{X||Ct(!1)}),Xl(l).then(_=>{X||fn(_)}).catch(()=>{}),()=>{X=!0}}},[a,d,u,l]);const Pe=Sc(B,Ne),dt=Sc(be,Me),bt=Sc(He,Ue),_t=!!(B&&Ne),Yt=!!(be&&Me),Xt=!!(He&&Ue),Te=Number(_t)+Number(Yt)+Number(Xt),Ye=Jt?on?.modelPresets?.find(X=>X.id===Jt)?.name??"Models":Te>0?`${Te} model${Te===1?"":"s"}`:"Models",Nt=i.useCallback((X,_)=>{if(!X||!_)return"Using default";const oe=Vt.find(D=>D.provider===X&&D.id===_);return oe?`${oe.provider}/${oe.id}`:`${X}/${_}`},[Vt]);i.useEffect(()=>{p(Dn(Ir,l)||"")},[l]),i.useEffect(()=>{typeof window<"u"&&os(Ir,f,l)},[f,l]),i.useEffect(()=>{j.current!==l&&(j.current=l,A([]),$(void 0),Z(null),G(!1),de(null))},[l]),i.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),i.useEffect(()=>{E.current=P},[P]),i.useEffect(()=>()=>{E.current.forEach(X=>URL.revokeObjectURL(X.previewUrl))},[]);const Ut=i.useCallback(()=>{const X=k.current;if(!X)return;X.style.height="auto";const _=Math.min(X.scrollHeight,200);X.style.height=`${_}px`},[]);i.useEffect(()=>{w&&Ut()},[f,w,Ut]),i.useEffect(()=>{if(!g&&f===""&&k.current){const X=setTimeout(()=>{k.current?.focus()},0);return()=>clearTimeout(X)}},[g,f]),i.useEffect(()=>{F||q("")},[F]),i.useEffect(()=>{if(!et)return;const X=_=>{const oe=_.target,D=Ht.current?.contains(oe),Q=jt.current?.contains(oe);!D&&!Q&&Qe(!1)};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[et]),i.useEffect(()=>{if(!le)return;const X=_=>{const oe=_.target,D=Oe.current?.contains(oe),Q=ze.current?.contains(oe),Ce=oe instanceof Element&&oe.closest?.(".model-combobox-dropdown--portal")!=null;!D&&!Q&&!Ce&&(se(!1),J(null))};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[le]),i.useEffect(()=>{if(!ge)return;const X=_=>{const oe=_.target;ye.current?.contains(oe)||Y.current?.contains(oe)||(je(!1),Ee(null))};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[ge]),i.useEffect(()=>{if(!N)return;const X=_=>{const oe=_.target;lt.current?.contains(oe)||Be.current?.contains(oe)||(G(!1),de(null))};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[N]),i.useEffect(()=>{if(!ke)return;const X=_=>{const oe=_.target;_e.current?.contains(oe)||ct.current?.contains(oe)||(ne(!1),ut(null))};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[ke]);const tn=i.useCallback(()=>{P.forEach(X=>URL.revokeObjectURL(X.previewUrl)),U([]),C.current&&(C.current.value=""),p(""),L([]),Z(null),G(!1),de(null),je(!1),Ee(null),ne(!1),ut(null),ve(void 0),H(void 0),ce(void 0),Le(void 0),gt(void 0),pe(void 0),an(void 0),en(!1),dn(js),Fe(void 0),M(!1),se(!1),Se(null),J(null),Qe(!1),St(!1),b(!1),S(!1),v.current=!0,k.current&&(k.current.style.height="auto"),typeof window<"u"&&pr(Ir,l)},[P,l]),Xn=i.useCallback(X=>{if(!X||X.length===0)return;const _=[];for(let oe=0;oe<X.length;oe++){const D=X[oe];DC.includes(D.type)&&_.push({file:D,previewUrl:URL.createObjectURL(D)})}_.length>0&&U(oe=>[...oe,..._])},[]),fe=i.useCallback(X=>{g||Xn(X.clipboardData?.files)},[Xn,g]),at=i.useCallback(X=>{U(_=>{const oe=_[X];return oe&&URL.revokeObjectURL(oe.previewUrl),_.filter((D,Q)=>Q!==X)})},[]),ot=i.useCallback(async()=>{const X=f.trim();if(!X||g||!e)return;const _=f;x(!0),p("");try{const oe=await e({description:X,column:"triage",dependencies:R.length?R:void 0,...te?{assignedAgentId:te}:{},modelPresetId:Jt,modelProvider:_t?B:void 0,modelId:_t?Ne:void 0,validatorModelProvider:Yt?be:void 0,validatorModelId:Yt?Me:void 0,planningModelProvider:Xt?He:void 0,planningModelId:Xt?Ue:void 0,...zt?{executionMode:"fast"}:{},priority:Zt,nodeId:xe});if(oe&&P.length>0){const D=[];for(const Q of P)try{await Zl(oe.id,Q.file,l)}catch{D.push(Q.file.name)}D.length>0&&n(`Failed to upload: ${D.join(", ")}`,"error")}tn()}catch(oe){p(_),n(Re(oe)||"Failed to create task","error")}finally{x(!1)}},[f,g,e,R,te,_t,B,Ne,Yt,be,Me,Xt,He,Ue,P,l,n,tn,zt,Zt,xe]),rt=i.useCallback(X=>{if(X.key==="Enter"){if(X.shiftKey&&w)return;X.preventDefault(),ot()}else if(X.key==="Escape"){if(X.preventDefault(),re){J(null);return}if(le){se(!1),Se(null);return}if(F){M(!1);return}if(et){Qe(!1);return}if(ge){je(!1),Ee(null);return}if(ke){ne(!1),ut(null);return}if(N){G(!1),de(null);return}f.trim()&&(p(""),k.current&&(k.current.style.height="auto"),typeof window<"u"&&pr(Ir,l)),b(!1),S(!1),k.current?.blur()}},[ot,f,w,F,N,ge,le,re,et,ke,l,S]),mt=i.useCallback(()=>{v.current&&(v.current=!1)},[]),vt=i.useCallback(()=>{c&&b(!0)},[c]),ie=i.useCallback(X=>{L(_=>_.includes(X)?_.filter(oe=>oe!==X):[..._,X])},[]),it=i.useCallback(()=>{const X=window.visualViewport;return X&&X.width>0&&X.height>0?{width:X.width,height:X.height,offsetTop:X.offsetTop,offsetLeft:X.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),Gt=i.useCallback(()=>{const X=Oe.current;if(!X)return;const _=X.getBoundingClientRect(),{width:oe,height:D,offsetTop:Q,offsetLeft:Ce}=it(),Je=16,kt=16,Tt=4,Pt=oe<=768,ln=Math.min(Pt?D*.6:D*.5,360),ts=Math.max(_.width*1.35,320),Pn=Pt?Math.min(oe-Je*2,360):ts,Fn=Math.min(Pn,Math.max(oe-Je*2,240)),Un=_.top-Q,gs=_.bottom-Q,Ln=_.left-Ce,Vn=D-gs,Wn=Un,Kn=Math.max(Vn-kt-Tt,160),Bn=Math.max(Wn-kt-Tt,160),Nn=Vn<ln&&Wn>Vn,Gn=Math.max(Math.min(Nn?Bn:Kn,ln),160),ds=Math.min(Math.max(Ln,Je),oe-Je-Fn)+Ce,Ts=Nn?Math.max(kt+Q,Un-Gn-Tt+Q):Math.min(gs+Tt+Q,D+Q-kt-Gn);Se({top:Ts,left:ds,width:Fn,maxHeight:Gn})},[it]),Cn=i.useCallback(()=>{const X=Ht.current?.querySelector(".refine-button");if(!X)return;const _=X.getBoundingClientRect(),{width:oe,height:D,offsetTop:Q,offsetLeft:Ce}=it(),Je=8,kt=12,Tt=4,Pt=Math.min(200,Math.max(D-kt*2,160)),ln=Math.min(200,oe-Je*2),ts=_.top-Q,Pn=_.bottom-Q,Fn=_.left-Ce,Un=D-Pn,gs=ts,Ln=Un<Pt&&gs>Un,Vn=Math.min(Math.max(Fn,Je),oe-Je-ln)+Ce,Wn=Ln?Math.max(kt+Q,ts-Pt-Tt+Q):Math.min(Pn+Tt+Q,D+Q-kt-Pt);De({top:Wn,left:Vn})},[it]),fs=i.useCallback(()=>{const X=we.current;if(!X)return;const _=X.getBoundingClientRect(),{width:oe,height:D,offsetTop:Q,offsetLeft:Ce}=it(),Je=16,kt=16,Tt=4,Pt=oe<=768,ln=Math.min(Pt?D*.6:D*.5,320),ts=Pt?Math.min(oe-Je*2,360):Math.max(_.width,280),Pn=Math.min(ts,Math.max(oe-Je*2,240)),Fn=_.top-Q,Un=_.bottom-Q,gs=_.left-Ce,Ln=D-Un,Vn=Fn,Wn=Math.max(Ln-kt-Tt,200),Kn=Math.max(Vn-kt-Tt,200),Bn=Ln<ln&&Vn>Ln,Nn=Math.max(Math.min(Bn?Kn:Wn,ln),200),Gn=Math.min(Math.max(gs,Je),oe-Je-Pn)+Ce,ds=Bn?Math.max(kt+Q,Fn-Nn-Tt+Q):Math.min(Un+Tt+Q,D+Q-kt-Nn);We({top:ds,left:Gn,width:Pn,maxHeight:Nn})},[it]),On=i.useCallback(()=>{const X=lt.current?.querySelector("button");if(!X)return;const _=X.getBoundingClientRect(),{width:oe,height:D,offsetTop:Q,offsetLeft:Ce}=it(),Je=16,kt=16,Tt=4,Pt=oe<=768,ln=Math.min(Pt?D*.6:D*.5,320),ts=Pt?Math.min(oe-Je*2,280):Math.max(_.width,240),Pn=Math.min(ts,Math.max(oe-Je*2,200)),Fn=_.top-Q,Un=_.bottom-Q,gs=_.left-Ce,Ln=D-Un,Vn=Fn,Wn=Math.max(Ln-kt-Tt,160),Kn=Math.max(Vn-kt-Tt,160),Bn=Ln<ln&&Vn>Ln,Nn=Math.max(Math.min(Bn?Kn:Wn,ln),160),Gn=Math.min(Math.max(gs,Je),oe-Je-Pn)+Ce,ds=Bn?Math.max(kt+Q,Fn-Nn-Tt+Q):Math.min(Un+Tt+Q,D+Q-kt-Nn);de({top:ds,left:Gn,width:Pn,maxHeight:Nn})},[it]),jn=i.useCallback(()=>{const X=ye.current?.querySelector("button");if(!X)return;const _=X.getBoundingClientRect(),{width:oe,height:D,offsetTop:Q,offsetLeft:Ce}=it(),Je=16,kt=16,Tt=4,Pt=oe<=768,ln=Math.min(Pt?D*.6:D*.5,320),ts=Pt?Math.min(oe-Je*2,280):Math.max(_.width,240),Pn=Math.min(ts,Math.max(oe-Je*2,200)),Fn=_.top-Q,Un=_.bottom-Q,gs=_.left-Ce,Ln=D-Un,Vn=Fn,Wn=Math.max(Ln-kt-Tt,160),Kn=Math.max(Vn-kt-Tt,160),Bn=Ln<ln&&Vn>Ln,Nn=Math.max(Math.min(Bn?Kn:Wn,ln),160),Gn=Math.min(Math.max(gs,Je),oe-Je-Pn)+Ce,ds=Bn?Math.max(kt+Q,Fn-Nn-Tt+Q):Math.min(Un+Tt+Q,D+Q-kt-Nn);Ee({top:ds,left:Gn,width:Pn,maxHeight:Nn})},[it]),zn=i.useCallback(()=>{const X=_e.current?.querySelector("button");if(!X)return;const _=X.getBoundingClientRect(),{width:oe,height:D,offsetTop:Q,offsetLeft:Ce}=it(),Je=16,kt=16,Tt=4,Pt=220,ln=Math.min(Math.max(_.width,200),Math.max(oe-Je*2,200)),ts=_.top-Q,Pn=_.bottom-Q,Fn=_.left-Ce,Un=D-Pn,gs=ts,Ln=Math.max(Un-kt-Tt,160),Vn=Math.max(gs-kt-Tt,160),Wn=Un<Pt&&gs>Un,Kn=Math.max(Math.min(Wn?Vn:Ln,Pt),160),Bn=Math.min(Math.max(Fn,Je),oe-Je-ln)+Ce,Nn=Wn?Math.max(kt+Q,ts-Kn-Tt+Q):Math.min(Pn+Tt+Q,D+Q-kt-Kn);ut({top:Nn,left:Bn,width:ln,maxHeight:Kn})},[it]);i.useEffect(()=>{if(!le)return;const X=()=>Gt();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const _=window.visualViewport;return _&&(_.addEventListener("resize",X),_.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),_&&(_.removeEventListener("resize",X),_.removeEventListener("scroll",X))}},[le,Gt]),i.useEffect(()=>{if(!et)return;const X=()=>Cn();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const _=window.visualViewport;return _&&(_.addEventListener("resize",X),_.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),_&&(_.removeEventListener("resize",X),_.removeEventListener("scroll",X))}},[et,Cn]),i.useEffect(()=>{if(!F)return;const X=()=>fs();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const _=window.visualViewport;return _&&(_.addEventListener("resize",X),_.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),_&&(_.removeEventListener("resize",X),_.removeEventListener("scroll",X))}},[F,fs]),i.useEffect(()=>{if(!N)return;const X=()=>On();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const _=window.visualViewport;return _&&(_.addEventListener("resize",X),_.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),_&&(_.removeEventListener("resize",X),_.removeEventListener("scroll",X))}},[N,On]),i.useEffect(()=>{if(!ge)return;const X=()=>jn();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const _=window.visualViewport;return _&&(_.addEventListener("resize",X),_.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),_&&(_.removeEventListener("resize",X),_.removeEventListener("scroll",X))}},[ge,jn]),i.useEffect(()=>{if(!ke)return;const X=()=>zn();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const _=window.visualViewport;return _&&(_.addEventListener("resize",X),_.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),_&&(_.removeEventListener("resize",X),_.removeEventListener("scroll",X))}},[ke,zn]);const hn=i.useCallback(X=>{const _=Cc(X);gt(_.provider),pe(_.modelId)},[]),Et=i.useCallback(X=>{const _=Cc(X);ve(_.provider),H(_.modelId)},[]),En=i.useCallback(X=>{const _=Cc(X);ce(_.provider),Le(_.modelId)},[]),yn=i.useCallback(async X=>{if(m){m(X);return}const _=Dt,D=_.includes(X)?_.filter(Q=>Q!==X):[X,..._];Qt(D);try{await kn({favoriteProviders:D,favoriteModels:Kt})}catch{Qt(_)}},[Dt,Kt,m]),ls=i.useCallback(async X=>{if(h){h(X);return}const _=Kt,D=_.includes(X)?_.filter(Q=>Q!==X):[X,..._];Bt(D);try{await kn({favoriteProviders:Dt,favoriteModels:D})}catch{Bt(_)}},[Kt,Dt,h]),cs=i.useCallback(()=>{const X=f.trim();if(!X){n("Enter a description first","error");return}r?.(X),tn()},[f,r,n,tn]),Hn=i.useCallback(()=>{const X=f.trim();if(!X){n("Enter a description first","error");return}o?.(X),tn()},[f,o,n,tn]),qn=i.useCallback(()=>{ot()},[ot]),wn=i.useCallback(async X=>{const _=f.trim();if(!(!_||It)){Qe(!1),St(!0);try{const oe=await Cg(_,X,l);p(oe),n("Description refined with AI","success"),k.current&&(k.current.style.height="auto",k.current.style.height=`${Math.min(k.current.scrollHeight,200)}px`)}catch(oe){const D=Eg(oe);n(D,"error")}finally{St(!1)}}},[f,It,n,l]),Zn=(X,_)=>X.length>_?X.slice(0,_)+"…":X,_n=i.useCallback(async()=>{if(a){Mt(a),$t(null),Ct(!1);return}Ct(!0),$t(null);try{const X=await Os();Mt(X.models),d||Qt(X.favoriteProviders),u||Bt(X.favoriteModels)}catch(X){$t(Re(X)||"Failed to load models")}finally{Ct(!1)}},[a,d,u]),ss=i.useCallback(async()=>{if(K.length>0&&I===l){G(!0),On();return}ee(!0);try{const X=await Nr(void 0,l);A(X),$(l),G(!0),On()}catch(X){const _=Re(X);n(_?`Failed to load agents: ${_}`:"Failed to load agents","error"),G(!1)}finally{ee(!1)}},[K.length,I,l,n,On]),es=(te?K.find(X=>X.id===te):void 0)?.name??te,ks=xe?Ke.find(X=>X.id===xe):void 0,Is=y,Ss=i.useCallback(()=>{S(X=>{const _=!X;return b(_),_})},[]);return t.jsxs("div",{className:`quick-entry-box ${y?"quick-entry-box--expanded":"quick-entry-box--collapsed"}`,"data-testid":"quick-entry-box",children:[t.jsx("div",{className:"description-with-refine",children:t.jsxs("div",{className:"quick-entry-main-row",children:[t.jsx("div",{className:"quick-entry-textarea-wrap",children:t.jsx("textarea",{ref:k,className:`quick-entry-input ${w?"quick-entry-input--expanded":""}`,placeholder:g?"Creating...":"Add a task...",value:f,onChange:X=>p(X.target.value),onKeyDown:rt,onPaste:fe,onFocus:vt,onBlur:mt,disabled:g||Ft,"data-testid":"quick-entry-input",rows:2,"aria-controls":"quick-entry-controls","aria-expanded":y})}),t.jsx("button",{type:"button",className:"btn btn-sm quick-entry-toggle",onClick:Ss,"aria-expanded":y,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:y?"Collapse":"Expand",children:y?t.jsx(Ei,{size:14}):t.jsx(rn,{size:14})})]})}),t.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!Is,"aria-hidden":!Is,children:[Is&&!g&&t.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:cs,onMouseDown:X=>X.preventDefault(),disabled:!f.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[t.jsx(_i,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:Hn,onMouseDown:X=>X.preventDefault(),disabled:!f.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[t.jsx(Jl,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),t.jsxs("div",{className:"refine-trigger-wrap",ref:Ht,children:[t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${It?"refine-button--loading":""}`,onClick:()=>{Qe(X=>{const _=!X;return _?Cn():De(null),_})},disabled:!f.trim()||It,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(ps,{size:12,style:{verticalAlign:"middle"}}),It?"Refining...":"Refine"]}),et&&me&&ae&&va.createPortal(t.jsxs("div",{ref:jt,className:"refine-menu refine-menu--portal",onMouseDown:X=>X.preventDefault(),style:{position:"fixed",top:`${ae.top}px`,left:`${ae.left}px`},children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>wn("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:()=>wn("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:()=>wn("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:()=>wn("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:we,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{M(X=>{const _=!X;return _?(se(!1),Se(null),J(null),G(!1),de(null),je(!1),Ee(null),ne(!1),ut(null),fs()):We(null),_})},children:[t.jsx(cr,{size:12,style:{verticalAlign:"middle"}}),R.length>0?`${R.length} deps`:"Deps"]})}),F&&me&&he&&(()=>{const X=O.toLowerCase(),_=(X?s.filter(oe=>oe.id.toLowerCase().includes(X)||oe.title&&oe.title.toLowerCase().includes(X)||oe.description&&oe.description.toLowerCase().includes(X)):[...s]).sort((oe,D)=>{const Q=D.createdAt.localeCompare(oe.createdAt);if(Q!==0)return Q;const Ce=parseInt(oe.id.slice(oe.id.lastIndexOf("-")+1),10)||0;return(parseInt(D.id.slice(D.id.lastIndexOf("-")+1),10)||0)-Ce});return va.createPortal(t.jsxs("div",{ref:Ae,className:"dep-dropdown dep-dropdown--portal",onMouseDown:oe=>oe.preventDefault(),style:{position:"fixed",top:`${he.top}px`,left:`${he.left}px`,width:`${he.width}px`,maxHeight:he.maxHeight?`${he.maxHeight}px`:void 0,overflowY:he.maxHeight?"auto":void 0},children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:O,onChange:oe=>q(oe.target.value),onClick:oe=>oe.stopPropagation()}),_.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):_.map(oe=>t.jsxs("div",{className:`dep-dropdown-item${R.includes(oe.id)?" selected":""}`,onMouseDown:D=>D.preventDefault(),onClick:()=>ie(oe.id),children:[t.jsx("span",{className:"dep-dropdown-id",children:oe.id}),t.jsx("span",{className:"dep-dropdown-title",children:Zn(oe.title||oe.description||oe.id,60)})]},oe.id))]}),me)})(),t.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>C.current?.click(),children:[t.jsx(fg,{size:12,style:{verticalAlign:"middle"}}),P.length>0?`Attach (${P.length})`:"Attach"]}),t.jsxs("button",{ref:Oe,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{M(!1),G(!1),de(null),je(!1),Ee(null),ne(!1),ut(null),J(null),se(!0),Gt()},children:[t.jsx(oo,{size:12,style:{verticalAlign:"middle"}}),Ye]}),t.jsx("div",{className:"node-trigger-wrap",ref:ye,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-node-button",onClick:()=>{M(!1),G(!1),de(null),se(!1),Se(null),J(null),ne(!1),ut(null),je(X=>{const _=!X;return _?jn():Ee(null),_})},children:[t.jsx(co,{size:12,style:{verticalAlign:"middle"}}),` ${ks?.name??"Node"}`,ks&&t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(Ca,{status:ks.status,showLabel:!0})})]})}),ge&&me&&Ve&&va.createPortal(t.jsxs("div",{ref:Y,className:"dep-dropdown node-picker-dropdown node-picker-dropdown--portal",onMouseDown:X=>X.preventDefault(),style:{position:"fixed",top:`${Ve.top}px`,left:`${Ve.left}px`,width:`${Ve.width}px`,maxHeight:Ve.maxHeight?`${Ve.maxHeight}px`:void 0,overflowY:Ve.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${xe==null?" selected":""}`,onMouseDown:X=>X.preventDefault(),onClick:()=>{Fe(void 0),je(!1),Ee(null)},children:t.jsx("span",{className:"node-picker-item-name",children:"Project default / local"})}),Ke.map(X=>t.jsxs("div",{className:`dep-dropdown-item node-picker-item${xe===X.id?" selected":""}`,onMouseDown:_=>_.preventDefault(),onClick:()=>{Fe(X.id),je(!1),Ee(null)},children:[t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(Ca,{status:X.status})}),t.jsx("span",{className:"node-picker-item-name",children:X.name}),t.jsx("span",{className:"node-picker-item-status",children:LC(X.status)})]},X.id))]}),me),t.jsx("div",{className:"agent-trigger-wrap",ref:lt,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{N?(G(!1),de(null)):(je(!1),Ee(null),ne(!1),ut(null),ss())},"data-testid":"quick-entry-agent-button",children:[t.jsx(Tn,{size:12,style:{verticalAlign:"middle"}}),es?` ${es}`:" Agent"]})}),N&&me&&pt&&va.createPortal(t.jsxs("div",{ref:Be,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:X=>X.preventDefault(),style:{position:"fixed",top:`${pt.top}px`,left:`${pt.left}px`,width:`${pt.width}px`,maxHeight:pt.maxHeight?`${pt.maxHeight}px`:void 0,overflowY:pt.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),qe&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!qe&&K.map(X=>t.jsxs("div",{className:`dep-dropdown-item${te===X.id?" selected":""}`,onMouseDown:_=>_.preventDefault(),onClick:()=>{Z(X.id===te?null:X.id),G(!1),de(null)},children:[t.jsx(Tn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:X.role}),t.jsx("span",{className:"dep-dropdown-title",children:X.name})]},X.id)),!qe&&K.length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),te&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:X=>X.preventDefault(),onClick:()=>{Z(null),G(!1),de(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),me),t.jsx("div",{className:"priority-trigger-wrap",ref:_e,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-priority-button",onClick:()=>{M(!1),G(!1),de(null),je(!1),Ee(null),se(!1),Se(null),J(null),ne(X=>{const _=!X;return _?zn():ut(null),_})},children:[t.jsx(Ey,{size:12,style:{verticalAlign:"middle"}}),` ${Zt[0].toUpperCase()}${Zt.slice(1)}`]})}),ke&&me&&$e&&va.createPortal(t.jsxs("div",{ref:ct,className:"dep-dropdown priority-picker-dropdown priority-picker-dropdown--portal",onMouseDown:X=>X.preventDefault(),style:{position:"fixed",top:`${$e.top}px`,left:`${$e.left}px`,width:`${$e.width}px`,maxHeight:$e.maxHeight?`${$e.maxHeight}px`:void 0,overflowY:$e.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select priority"}),oa.map(X=>{const _=`${X[0].toUpperCase()}${X.slice(1)}`;return t.jsx("div",{className:`dep-dropdown-item${Zt===X?" selected":""}`,"data-testid":`quick-entry-priority-option-${X}`,onMouseDown:oe=>oe.preventDefault(),onClick:()=>{dn(X),ne(!1),ut(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:_})},X)})]}),me),t.jsx("button",{type:"button",className:`btn btn-sm ${zt?"btn-primary":""}`,onClick:()=>en(X=>!X),onMouseDown:X=>X.preventDefault(),"aria-pressed":zt,"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:qn,onMouseDown:X=>X.preventDefault(),disabled:!f.trim()||g,"data-testid":"quick-entry-save",title:"Create task",children:[t.jsx(bg,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),P.length>0&&t.jsx("div",{className:"inline-create-previews",children:P.map((X,_)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:X.previewUrl,alt:X.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>at(_),disabled:g,title:"Remove image","data-testid":`quick-entry-preview-remove-${_}`,children:"×"})]},X.previewUrl))}),le&&me&&ht&&va.createPortal(t.jsx("div",{ref:ze,className:"model-nested-menu model-nested-menu--portal",onMouseDown:X=>X.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${ht.top}px`,left:`${ht.left}px`,width:`${ht.width}px`,maxHeight:ht.maxHeight?`${ht.maxHeight}px`:void 0,overflowY:ht.maxHeight?"auto":void 0},children:re===null?t.jsxs("div",{className:"model-menu-items",children:[t.jsxs("button",{type:"button",className:`model-menu-item ${Xt?"model-menu-item--active":""}`,onClick:()=>J("plan"),"data-testid":"model-menu-plan",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(_i,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),t.jsx("span",{className:"model-menu-item-value",children:Xt?Nt(He,Ue):"Using default"}),t.jsx(Mn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${_t?"model-menu-item--active":""}`,onClick:()=>J("executor"),"data-testid":"model-menu-executor",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(ps,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),t.jsx("span",{className:"model-menu-item-value",children:_t?Nt(B,Ne):"Using default"}),t.jsx(Mn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${Yt?"model-menu-item--active":""}`,onClick:()=>J("validator"),"data-testid":"model-menu-validator",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(oo,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Reviewer"]}),t.jsx("span",{className:"model-menu-item-value",children:Yt?Nt(be,Me):"Using default"}),t.jsx(Mn,{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:()=>J(null),"data-testid":"model-submenu-back",children:[t.jsx(rn,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),t.jsxs("div",{className:"model-submenu-header",children:[re==="plan"&&"Plan Model",re==="executor"&&"Executor Model",re==="validator"&&"Reviewer Model"]}),t.jsx(ys,{models:Vt,value:re==="plan"?bt:re==="executor"?Pe:dt,onChange:re==="plan"?hn:re==="executor"?Et:En,placeholder:"Using default",disabled:nt,id:`model-${re}-select`,label:`${re} model`,favoriteProviders:At,onToggleFavorite:yn,favoriteModels:Lt,onToggleModelFavorite:ls}),wt&&t.jsxs("div",{className:"model-submenu-error",children:[t.jsx("span",{children:wt}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:_n,children:"Retry"})]})]})}),me)]}),t.jsx("input",{ref:C,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:X=>{Xn(X.target.files),X.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),t.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function OC(e){return gu(e)||e}function zC(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 FC(e,n,s){const a=e.filter(g=>g.worktree),r=e.filter(g=>!g.worktree),o=new Map;for(const g of a){const x=g.worktree,w=o.get(x)||[];w.push(g),o.set(x,w)}const l=new Map(n.map(g=>[g.id,g])),d=n.filter(g=>g.column==="todo").filter(g=>!g.paused&&(g.dependencies||[]).every(x=>{const w=l.get(x);return w&&(w.column==="done"||w.column==="in-review"||w.column==="archived")})),m=zC(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:OC(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 oh=100,Ec=50,lh=25;function UC({column:e,tasks:n,projectId:s,maxConcurrent:a,onMoveTask:r,onPauseTask:o,onOpenDetail:l,addToast:c,onQuickCreate:d,onNewTask:u,autoMerge:m,onToggleAutoMerge:h,globalPaused:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:x,onUnarchiveTask:w,onDeleteTask:b,onArchiveAllDone:y,collapsed:S,onToggleCollapse:k,allTasks:C,availableModels:v,onPlanningMode:j,onSubtaskBreakdown:P,onOpenDetailWithTab:U,favoriteProviders:E,favoriteModels:R,onToggleFavorite:L,onToggleModelFavorite:F,isSearchActive:M,taskStuckTimeoutMs:O,onOpenMission:q,lastFetchTimeMs:te,workflowStepNameLookup:Z}){const[K,A]=i.useState(!1),[I,$]=i.useState(Ec),[N,G]=i.useState(!1),[ge,je]=i.useState(!1),[ke,ne]=i.useState(!1),[qe,ee]=i.useState(!1),le=i.useRef(null),se=L0(n.length),{confirm:re}=ai();i.useEffect(()=>{if(!N)return;function Y(ct){le.current?.contains(ct.target)||G(!1)}function _e(ct){ct.key==="Escape"&&G(!1)}return document.addEventListener("mousedown",Y),document.addEventListener("keydown",_e),()=>{document.removeEventListener("mousedown",Y),document.removeEventListener("keydown",_e)}},[N]);const J=e==="archived",B=J&&S,ve=!J&&!M&&e!=="in-progress"&&n.length>oh;i.useEffect(()=>{$(Y=>e==="in-progress"||J||n.length<=oh?Ec:Math.min(Math.max(Y,Ec),n.length))},[e,J,n.length]);const Ne=i.useCallback(Y=>{J||(Y.preventDefault(),Y.dataTransfer.dropEffect="move",A(!0))},[J]),H=i.useCallback(Y=>{Y.currentTarget.contains(Y.relatedTarget)||A(!1)},[]),be=i.useCallback(async Y=>{Y.preventDefault(),A(!1);const _e=Y.dataTransfer.getData("text/plain");if(!_e)return;const ct=n.find(pt=>pt.id===_e);if(!(ct&&ct.column===e))try{const de=(C?.find($e=>$e.id===_e)??ct)?.steps.some($e=>$e.status!=="pending")??!1,Ve=(e==="todo"||e==="triage")&&de;let Ee;if(Ve){if(await re({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Ee={preserveProgress:!0};else if(!await re({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await r(_e,e,Ee)}catch(pt){c(Re(pt),"error")}},[c,C,e,re,r,n]),ce=i.useMemo(()=>e!=="in-progress"?[]:FC(n,n,a),[e,n,a]),Me=i.useMemo(()=>ve?n.slice(0,I):n,[ve,n,I]),Le=Math.max(0,n.length-Me.length),He=i.useCallback(()=>{$(Y=>Math.min(Y+lh,n.length))},[n.length]),gt=i.useCallback(async()=>{if(G(!1),!(n.length===0||!await re({title:"Replan All Tasks",message:`Move all ${n.length} todo task${n.length===1?"":"s"} back to planning to be replanned?`}))){je(!0);try{const _e=await Promise.allSettled(n.map(de=>r(de.id,"triage"))),ct=_e.filter(de=>de.status==="rejected").length,pt=_e.length-ct;ct===0?c(`Moved ${pt} task${pt===1?"":"s"} to planning for replanning`,"success"):c(`Moved ${pt} of ${_e.length} tasks; ${ct} failed`,"error")}finally{je(!1)}}},[n,r,c,re]),Ue=i.useMemo(()=>n.filter(Y=>!Y.paused&&!Y.assignedAgentId),[n]),pe=Ue.length,Oe=e==="todo"||e==="in-progress"||e==="in-review",ze=ge||ke||qe,lt=i.useCallback(async()=>{if(!(!o||(G(!1),pe===0)||!await re({title:"Stop All Tasks",message:`Stop all ${pe} ${ns[e].toLowerCase()} task${pe===1?"":"s"}?`,danger:!0}))){ne(!0);try{const _e=await Promise.allSettled(Ue.map(de=>o(de.id))),ct=_e.filter(de=>de.status==="rejected").length,pt=_e.length-ct;ct===0?c(`Stopped ${pt} task${pt===1?"":"s"}`,"success"):c(`Stopped ${pt} of ${_e.length} tasks; ${ct} failed`,"error")}finally{ne(!1)}}},[o,pe,e,Ue,c,re]),Be=i.useCallback(async()=>{if(G(!1),n.length===0||!await re({title:"Move All to Todo",message:`Move all ${n.length} ${ns[e].toLowerCase()} task${n.length===1?"":"s"} to Todo?`}))return;const _e=n.some(pt=>pt.steps.some(de=>de.status!=="pending"));let ct=!1;if(_e){if(await re({title:"Preserve Progress?",message:"Some tasks have completed steps. Keep progress before moving to Todo?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))ct=!0;else if(!await re({title:"Reset Progress?",message:"Reset step progress for tasks before moving to Todo?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}ee(!0);try{const pt=await Promise.allSettled(n.map(Ee=>r(Ee.id,"todo",ct?{preserveProgress:!0}:void 0))),de=pt.filter(Ee=>Ee.status==="rejected").length,Ve=pt.length-de;de===0?c(`Moved ${Ve} task${Ve===1?"":"s"} to Todo`,"success"):c(`Moved ${Ve} of ${pt.length} tasks to Todo; ${de} failed`,"error")}finally{ee(!1)}},[n,e,r,c,re]),ye=i.useCallback(async()=>{if(!(!y||n.length===0||!await re({title:"Archive All Done",message:`Archive all ${n.length} done tasks?`,danger:!0})))try{const _e=await y();c(`Archived ${_e.length} tasks`,"success")}catch(_e){c(Re(_e)||"Failed to archive tasks","error")}},[y,n.length,c,re]);return t.jsxs("div",{className:`column${K?" drag-over":""}${J?" column-archived":""}${B?" column-collapsed":""}`,"data-column":e,onDragOver:Ne,onDragLeave:H,onDrop:be,children:[t.jsxs("div",{className:"column-header",children:[t.jsx("div",{className:`column-dot dot-${e}`}),t.jsx("h2",{children:ns[e]}),t.jsx("span",{className:`column-count${se?" count-flash":""}`,children:n.length}),e==="in-review"&&h&&t.jsxs("label",{className:"auto-merge-toggle",title:m?"Auto-merge enabled":"Auto-merge disabled",children:[t.jsx("input",{type:"checkbox",checked:!!m,onChange:h}),t.jsx("span",{className:"toggle-slider"}),t.jsx("span",{className:"toggle-label",children:"Auto-merge"})]}),u&&t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:u,children:"+ New Task"}),e==="done"&&y&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:ye,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:t.jsx(xo,{})}),J&&k&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:k,title:S?"Expand archived tasks":"Collapse archived tasks","aria-label":S?"Expand archived tasks":"Collapse archived tasks",children:S?t.jsx(rn,{size:16}):t.jsx(Ei,{size:16})}),Oe&&t.jsxs("div",{className:"column-menu",ref:le,children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>G(Y=>!Y),"aria-haspopup":"menu","aria-expanded":N,"aria-label":`${ns[e]} column actions`,title:"Column actions",disabled:ze,children:t.jsx(ly,{})}),N&&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 gt(),disabled:n.length===0||ge,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 lt(),disabled:pe===0||ke||!o,children:["Stop All",t.jsx("span",{className:"column-menu-item-hint",children:n.length===0?"No tasks in this column":pe===0?"No manually pausable tasks":`Pause ${pe} active unassigned task${pe===1?"":"s"}`})]}),t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Be(),disabled:n.length===0||qe,children:["Move All to Todo",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Todo"]})]})]})]})]})]}),!B&&t.jsx("p",{className:"column-desc",children:$0[e]}),!B&&t.jsxs("div",{className:"column-body",children:[e==="triage"&&d&&t.jsx(ab,{onCreate:d,addToast:c,tasks:C??[],availableModels:v,onPlanningMode:j,onSubtaskBreakdown:P,projectId:s,autoExpand:!1,favoriteProviders:E,favoriteModels:R,onToggleFavorite:L,onToggleModelFavorite:F}),e==="in-progress"?ce.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):ce.map(Y=>t.jsx(ib,{label:Y.label,activeTasks:Y.activeTasks,queuedTasks:Y.queuedTasks,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onOpenDetailWithTab:U,taskStuckTimeoutMs:O,onOpenMission:q,lastFetchTimeMs:te,workflowStepNameLookup:Z},Y.label)):n.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):t.jsxs(t.Fragment,{children:[Me.map(Y=>t.jsx(ho,{task:Y,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:x,onUnarchiveTask:w,onDeleteTask:b,onOpenDetailWithTab:U,taskStuckTimeoutMs:O,onOpenMission:q,onMoveTask:r,lastFetchTimeMs:te,workflowStepNameLookup:Z},Y.id)),ve&&Le>0&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:He,children:["Load ",Math.min(lh,Le)," more (",Le," remaining)"]})]}),t.jsx(ta,{slotId:"board-column-footer",projectId:s})]})]})}const rb=i.memo(UC);rb.displayName="Column";function BC(e,n){return e.length!==n.length?!1:e.every((s,a)=>s===n[a])}const ch=new Map;function HC(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 qC({tasks:e,projectId:n,maxConcurrent:s,onMoveTask:a,onPauseTask:r,onOpenDetail:o,addToast:l,onQuickCreate:c,onNewTask:d,autoMerge:u,onToggleAutoMerge:m,globalPaused:h,onUpdateTask:f,onRetryTask:p,onArchiveTask:g,onUnarchiveTask:x,onDeleteTask:w,onArchiveAllDone:b,onLoadArchivedTasks:y,searchQuery:S="",availableModels:k,onPlanningMode:C,onSubtaskBreakdown:v,onOpenDetailWithTab:j,favoriteProviders:P,favoriteModels:U,onToggleFavorite:E,onToggleModelFavorite:R,taskStuckTimeoutMs:L,onOpenMission:F,lastFetchTimeMs:M}){const[O,q]=i.useState(!0),te=i.useRef(!1),{fetchBatch:Z}=K0(n),K=i.useRef(null),[A,I]=i.useState(ch),$=S.trim()!=="",N=i.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),G=i.useCallback(()=>{q(ke=>{const ne=!ke;return!ne&&!te.current&&y&&(te.current=!0,y()),ne})},[y]),ge=i.useMemo(()=>{const ke={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};for(const ee of e){const le=xu(ee.column)?ee.column:Al;(ke[le]??ke[Al]).push(ee)}const ne=N.current,qe={};for(const ee of ea){const le=Wg(ke[ee],ee);qe[ee]=BC(ne[ee],le)?ne[ee]:le}return N.current=qe,qe},[e]);i.useEffect(()=>{let ke=!1;return _o(n).then(ne=>{if(ke)return;const qe=new Map(ne.map(ee=>[ee.id,ee.name]));I(ee=>HC(ee,qe)?ee:qe)}).catch(()=>{ke||I(ne=>ne.size===0?ne:ch)}),()=>{ke=!0}},[n]);const je=i.useMemo(()=>e.filter(ke=>ke.prInfo||ke.issueInfo).map(ke=>ke.id),[e]);return i.useEffect(()=>{if(je.length!==0)return K.current&&clearTimeout(K.current),K.current=setTimeout(()=>{const ke=[];for(let ne=0;ne<je.length;ne+=50)ke.push(je.slice(ne,ne+50));ke.forEach(ne=>{Z(ne)})},500),()=>{K.current&&clearTimeout(K.current)}},[je,Z]),t.jsx(t.Fragment,{children:t.jsx("main",{className:"board",id:"board",children:ea.map(ke=>t.jsx(rb,{column:ke,tasks:ge[ke],projectId:n,maxConcurrent:s,onMoveTask:a,onPauseTask:r,onOpenDetail:o,addToast:l,globalPaused:h,onUpdateTask:f,onRetryTask:p,onArchiveTask:g,onUnarchiveTask:x,onDeleteTask:w,allTasks:e,availableModels:k,onOpenDetailWithTab:j,favoriteProviders:P,favoriteModels:U,onToggleFavorite:E,onToggleModelFavorite:R,isSearchActive:$,taskStuckTimeoutMs:L,onOpenMission:F,lastFetchTimeMs:M,workflowStepNameLookup:A,...ke==="triage"?{onQuickCreate:c,onNewTask:d,onPlanningMode:C,onSubtaskBreakdown:v}:{},...ke==="in-review"?{autoMerge:u,onToggleAutoMerge:m}:{},...ke==="done"?{onArchiveAllDone:b}:{},...ke==="archived"?{collapsed:O,onToggleCollapse:G}:{}},ke))})})}function Ai(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 VC(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let or=0,so=null;function WC(){if(typeof window>"u")return;if(or>0){or+=1;return}const e=document.documentElement,n=document.body;so={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=`-${so.scrollY}px`,n.style.left="0",n.style.right="0",n.style.width="100%",n.style.overflow="hidden",or=1}function KC(){if(typeof window>"u"||or===0||(or-=1,or>0||!so))return;const e=document.documentElement,n=document.body,{htmlOverflow:s,bodyPosition:a,bodyTop:r,bodyLeft:o,bodyRight:l,bodyWidth:c,bodyOverflow:d,scrollY:u}=so;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,so=null,window.scrollTo(0,0)}function vi(e){i.useEffect(()=>{if(!(!e||!VC()))return WC(),()=>{KC()}},[e])}function qi(e){const n=i.useRef(!1),s=i.useCallback(r=>{n.current=r.target===r.currentTarget},[]),a=i.useCallback(r=>{const o=n.current&&r.target===r.currentTarget;n.current=!1,o&&e()},[e]);return{onMouseDown:s,onMouseUp:a}}function GC(e,n){const s={};return(e[e.length-1]===""?[...e,""]:e).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const JC=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,YC=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,QC={};function dh(e,n){return(QC.jsx?YC:JC).test(e)}const XC=/[ \t\n\f\r]/g;function ZC(e){return typeof e=="object"?e.type==="text"?uh(e.value):!1:uh(e)}function uh(e){return e.replace(XC,"")===""}class Io{constructor(n,s,a){this.normal=s,this.property=n,a&&(this.space=a)}}Io.prototype.normal={};Io.prototype.property={};Io.prototype.space=void 0;function ob(e,n){const s={},a={};for(const r of e)Object.assign(s,r.property),Object.assign(a,r.normal);return new Io(s,a,n)}function Od(e){return e.toLowerCase()}class Bs{constructor(n,s){this.attribute=s,this.property=n}}Bs.prototype.attribute="";Bs.prototype.booleanish=!1;Bs.prototype.boolean=!1;Bs.prototype.commaOrSpaceSeparated=!1;Bs.prototype.commaSeparated=!1;Bs.prototype.defined=!1;Bs.prototype.mustUseProperty=!1;Bs.prototype.number=!1;Bs.prototype.overloadedBoolean=!1;Bs.prototype.property="";Bs.prototype.spaceSeparated=!1;Bs.prototype.space=void 0;let eE=0;const sn=Ra(),ms=Ra(),zd=Ra(),yt=Ra(),In=Ra(),lr=Ra(),Vs=Ra();function Ra(){return 2**++eE}const Fd=Object.freeze(Object.defineProperty({__proto__:null,boolean:sn,booleanish:ms,commaOrSpaceSeparated:Vs,commaSeparated:lr,number:yt,overloadedBoolean:zd,spaceSeparated:In},Symbol.toStringTag,{value:"Module"})),_c=Object.keys(Fd);class yu extends Bs{constructor(n,s,a,r){let o=-1;if(super(n,s),mh(this,"space",r),typeof a=="number")for(;++o<_c.length;){const l=_c[o];mh(this,_c[o],(a&Fd[l])===Fd[l])}}}yu.prototype.defined=!0;function mh(e,n,s){s&&(e[n]=s)}function Cr(e){const n={},s={};for(const[a,r]of Object.entries(e.properties)){const o=new yu(a,e.transform(e.attributes||{},a),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(a)&&(o.mustUseProperty=!0),n[a]=o,s[Od(a)]=a,s[Od(o.attribute)]=a}return new Io(n,s,e.space)}const lb=Cr({properties:{ariaActiveDescendant:null,ariaAtomic:ms,ariaAutoComplete:null,ariaBusy:ms,ariaChecked:ms,ariaColCount:yt,ariaColIndex:yt,ariaColSpan:yt,ariaControls:In,ariaCurrent:null,ariaDescribedBy:In,ariaDetails:null,ariaDisabled:ms,ariaDropEffect:In,ariaErrorMessage:null,ariaExpanded:ms,ariaFlowTo:In,ariaGrabbed:ms,ariaHasPopup:null,ariaHidden:ms,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:In,ariaLevel:yt,ariaLive:null,ariaModal:ms,ariaMultiLine:ms,ariaMultiSelectable:ms,ariaOrientation:null,ariaOwns:In,ariaPlaceholder:null,ariaPosInSet:yt,ariaPressed:ms,ariaReadOnly:ms,ariaRelevant:null,ariaRequired:ms,ariaRoleDescription:In,ariaRowCount:yt,ariaRowIndex:yt,ariaRowSpan:yt,ariaSelected:ms,ariaSetSize:yt,ariaSort:null,ariaValueMax:yt,ariaValueMin:yt,ariaValueNow:yt,ariaValueText:null,role:null},transform(e,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function cb(e,n){return n in e?e[n]:n}function db(e,n){return cb(e,n.toLowerCase())}const tE=Cr({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:lr,acceptCharset:In,accessKey:In,action:null,allow:null,allowFullScreen:sn,allowPaymentRequest:sn,allowUserMedia:sn,alt:null,as:null,async:sn,autoCapitalize:null,autoComplete:In,autoFocus:sn,autoPlay:sn,blocking:In,capture:null,charSet:null,checked:sn,cite:null,className:In,cols:yt,colSpan:null,content:null,contentEditable:ms,controls:sn,controlsList:In,coords:yt|lr,crossOrigin:null,data:null,dateTime:null,decoding:null,default:sn,defer:sn,dir:null,dirName:null,disabled:sn,download:zd,draggable:ms,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:sn,formTarget:null,headers:In,height:yt,hidden:zd,high:yt,href:null,hrefLang:null,htmlFor:In,httpEquiv:In,id:null,imageSizes:null,imageSrcSet:null,inert:sn,inputMode:null,integrity:null,is:null,isMap:sn,itemId:null,itemProp:In,itemRef:In,itemScope:sn,itemType:In,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:sn,low:yt,manifest:null,max:null,maxLength:yt,media:null,method:null,min:null,minLength:yt,multiple:sn,muted:sn,name:null,nonce:null,noModule:sn,noValidate:sn,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:sn,optimum:yt,pattern:null,ping:In,placeholder:null,playsInline:sn,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:sn,referrerPolicy:null,rel:In,required:sn,reversed:sn,rows:yt,rowSpan:yt,sandbox:In,scope:null,scoped:sn,seamless:sn,selected:sn,shadowRootClonable:sn,shadowRootDelegatesFocus:sn,shadowRootMode:null,shape:null,size:yt,sizes:null,slot:null,span:yt,spellCheck:ms,src:null,srcDoc:null,srcLang:null,srcSet:null,start:yt,step:null,style:null,tabIndex:yt,target:null,title:null,translate:null,type:null,typeMustMatch:sn,useMap:null,value:ms,width:yt,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:In,axis:null,background:null,bgColor:null,border:yt,borderColor:null,bottomMargin:yt,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:sn,declare:sn,event:null,face:null,frame:null,frameBorder:null,hSpace:yt,leftMargin:yt,link:null,longDesc:null,lowSrc:null,marginHeight:yt,marginWidth:yt,noResize:sn,noHref:sn,noShade:sn,noWrap:sn,object:null,profile:null,prompt:null,rev:null,rightMargin:yt,rules:null,scheme:null,scrolling:ms,standby:null,summary:null,text:null,topMargin:yt,valueType:null,version:null,vAlign:null,vLink:null,vSpace:yt,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:sn,disableRemotePlayback:sn,prefix:null,property:null,results:yt,security:null,unselectable:null},space:"html",transform:db}),nE=Cr({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:Vs,accentHeight:yt,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:yt,amplitude:yt,arabicForm:null,ascent:yt,attributeName:null,attributeType:null,azimuth:yt,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:yt,by:null,calcMode:null,capHeight:yt,className:In,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:yt,diffuseConstant:yt,direction:null,display:null,dur:null,divisor:yt,dominantBaseline:null,download:sn,dx:null,dy:null,edgeMode:null,editable:null,elevation:yt,enableBackground:null,end:null,event:null,exponent:yt,externalResourcesRequired:null,fill:null,fillOpacity:yt,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:lr,g2:lr,glyphName:lr,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:yt,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:yt,horizOriginX:yt,horizOriginY:yt,id:null,ideographic:yt,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:yt,k:yt,k1:yt,k2:yt,k3:yt,k4:yt,kernelMatrix:Vs,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:yt,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:yt,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:yt,overlineThickness:yt,paintOrder:null,panose1:null,path:null,pathLength:yt,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:In,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:yt,pointsAtY:yt,pointsAtZ:yt,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Vs,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Vs,rev:Vs,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Vs,requiredFeatures:Vs,requiredFonts:Vs,requiredFormats:Vs,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:yt,specularExponent:yt,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:yt,strikethroughThickness:yt,string:null,stroke:null,strokeDashArray:Vs,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:yt,strokeOpacity:yt,strokeWidth:null,style:null,surfaceScale:yt,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Vs,tabIndex:yt,tableValues:null,target:null,targetX:yt,targetY:yt,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Vs,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:yt,underlineThickness:yt,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:yt,values:null,vAlphabetic:yt,vMathematical:yt,vectorEffect:null,vHanging:yt,vIdeographic:yt,version:null,vertAdvY:yt,vertOriginX:yt,vertOriginY:yt,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:yt,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:cb}),ub=Cr({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()}}),mb=Cr({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:db}),hb=Cr({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),sE={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"},iE=/[A-Z]/g,hh=/-[a-z]/g,aE=/^data[-\w.:]+$/i;function rE(e,n){const s=Od(n);let a=n,r=Bs;if(s in e.normal)return e.property[e.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&aE.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(hh,lE);a="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!hh.test(o)){let l=o.replace(iE,oE);l.charAt(0)!=="-"&&(l="-"+l),n="data"+l}}r=yu}return new r(a,n)}function oE(e){return"-"+e.toLowerCase()}function lE(e){return e.charAt(1).toUpperCase()}const cE=ob([lb,tE,ub,mb,hb],"html"),wu=ob([lb,nE,ub,mb,hb],"svg");function dE(e){return e.join(" ").trim()}var Ja={},Mc,ph;function uE(){if(ph)return Mc;ph=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,n=/\n/g,s=/^\s*/,a=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,r=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,l=/^[;\s]*/,c=/^\s+|\s+$/g,d=`
|
|
652
|
+
`,u="/",m="*",h="",f="comment",p="declaration";function g(w,b){if(typeof w!="string")throw new TypeError("First argument must be a string");if(!w)return[];b=b||{};var y=1,S=1;function k(M){var O=M.match(n);O&&(y+=O.length);var q=M.lastIndexOf(d);S=~q?M.length-q:S+M.length}function C(){var M={line:y,column:S};return function(O){return O.position=new v(M),U(),O}}function v(M){this.start=M,this.end={line:y,column:S},this.source=b.source}v.prototype.content=w;function j(M){var O=new Error(b.source+":"+y+":"+S+": "+M);if(O.reason=M,O.filename=b.source,O.line=y,O.column=S,O.source=w,!b.silent)throw O}function P(M){var O=M.exec(w);if(O){var q=O[0];return k(q),w=w.slice(q.length),O}}function U(){P(s)}function E(M){var O;for(M=M||[];O=R();)O!==!1&&M.push(O);return M}function R(){var M=C();if(!(u!=w.charAt(0)||m!=w.charAt(1))){for(var O=2;h!=w.charAt(O)&&(m!=w.charAt(O)||u!=w.charAt(O+1));)++O;if(O+=2,h===w.charAt(O-1))return j("End of comment missing");var q=w.slice(2,O-2);return S+=2,k(q),w=w.slice(O),S+=2,M({type:f,comment:q})}}function L(){var M=C(),O=P(a);if(O){if(R(),!P(r))return j("property missing ':'");var q=P(o),te=M({type:p,property:x(O[0].replace(e,h)),value:q?x(q[0].replace(e,h)):h});return P(l),te}}function F(){var M=[];E(M);for(var O;O=L();)O!==!1&&(M.push(O),E(M));return M}return U(),F()}function x(w){return w?w.replace(c,h):h}return Mc=g,Mc}var fh;function mE(){if(fh)return Ja;fh=1;var e=Ja&&Ja.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(Ja,"__esModule",{value:!0}),Ja.default=s;const n=e(uE());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 Ja}var Tr={},gh;function hE(){if(gh)return Tr;gh=1,Object.defineProperty(Tr,"__esModule",{value:!0}),Tr.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 Tr.camelCase=d,Tr}var $r,bh;function pE(){if(bh)return $r;bh=1;var e=$r&&$r.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=e(mE()),s=hE();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,$r=a,$r}var fE=pE();const gE=ig(fE),pb=fb("end"),ku=fb("start");function fb(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 bE(e){const n=ku(e),s=pb(e);if(n&&s)return{start:n,end:s}}function io(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?xh(e.position):"start"in e||"end"in e?xh(e):"line"in e||"column"in e?Ud(e):""}function Ud(e){return vh(e&&e.line)+":"+vh(e&&e.column)}function xh(e){return Ud(e&&e.start)+"-"+Ud(e&&e.end)}function vh(e){return e&&typeof e=="number"?e:1}class Rs 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=io(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}}Rs.prototype.file="";Rs.prototype.name="";Rs.prototype.reason="";Rs.prototype.message="";Rs.prototype.stack="";Rs.prototype.column=void 0;Rs.prototype.line=void 0;Rs.prototype.ancestors=void 0;Rs.prototype.cause=void 0;Rs.prototype.fatal=void 0;Rs.prototype.place=void 0;Rs.prototype.ruleId=void 0;Rs.prototype.source=void 0;const ju={}.hasOwnProperty,xE=new Map,vE=/[A-Z]/g,yE=new Set(["table","tbody","thead","tfoot","tr"]),wE=new Set(["td","th"]),gb="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function kE(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=AE(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=ME(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"?wu:cE,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=bb(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function bb(e,n,s){if(n.type==="element")return jE(e,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return NE(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return CE(e,n,s);if(n.type==="mdxjsEsm")return SE(e,n);if(n.type==="root")return EE(e,n,s);if(n.type==="text")return _E(e,n)}function jE(e,n,s){const a=e.schema;let r=a;n.tagName.toLowerCase()==="svg"&&a.space==="html"&&(r=wu,e.schema=r),e.ancestors.push(n);const o=vb(e,n.tagName,!1),l=PE(e,n);let c=Su(e,n);return yE.has(n.tagName)&&(c=c.filter(function(d){return typeof d=="string"?!ZC(d):!0})),xb(e,l,o,n),Nu(l,c),e.ancestors.pop(),e.schema=a,e.create(n,o,l,s)}function NE(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)}po(e,n.position)}function SE(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);po(e,n.position)}function CE(e,n,s){const a=e.schema;let r=a;n.name==="svg"&&a.space==="html"&&(r=wu,e.schema=r),e.ancestors.push(n);const o=n.name===null?e.Fragment:vb(e,n.name,!0),l=RE(e,n),c=Su(e,n);return xb(e,l,o,n),Nu(l,c),e.ancestors.pop(),e.schema=a,e.create(n,o,l,s)}function EE(e,n,s){const a={};return Nu(a,Su(e,n)),e.create(n,e.Fragment,a,s)}function _E(e,n){return n.value}function xb(e,n,s,a){typeof s!="string"&&s!==e.Fragment&&e.passNode&&(n.node=a)}function Nu(e,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(e.children=s)}}function ME(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 AE(e,n){return s;function s(a,r,o,l){const c=Array.isArray(o.children),d=ku(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 PE(e,n){const s={};let a,r;for(r in n.properties)if(r!=="children"&&ju.call(n.properties,r)){const o=IE(e,r,n.properties[r]);if(o){const[l,c]=o;e.tableCellAlignToStyle&&l==="align"&&typeof c=="string"&&wE.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 RE(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 po(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 po(e,n.position);else o=a.value===null?!0:a.value;s[r]=o}return s}function Su(e,n){const s=[];let a=-1;const r=e.passKeys?new Map:xE;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=bb(e,o,l);c!==void 0&&s.push(c)}return s}function IE(e,n,s){const a=rE(e.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=a.commaSeparated?GC(s):dE(s)),a.property==="style"){let r=typeof s=="object"?s:TE(e,String(s));return e.stylePropertyNameCase==="css"&&(r=$E(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&a.space?sE[a.property]||a.property:a.attribute,s]}}function TE(e,n){try{return gE(n,{reactCompat:!0})}catch(s){if(e.ignoreInvalidStyle)return{};const a=s,r=new Rs("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=gb+"#cannot-parse-style-attribute",r}}function vb(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=dh(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=dh(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(a.type==="Literal"){const r=a.value;return ju.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(a);po(e)}function po(e,n){const s=new Rs("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=gb+"#cannot-handle-mdx-estrees-without-createevaluater",s}function $E(e){const n={};let s;for(s in e)ju.call(e,s)&&(n[DE(s)]=e[s]);return n}function DE(e){let n=e.replace(vE,LE);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function LE(e){return"-"+e.toLowerCase()}const Ac={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"]},OE={};function Cu(e,n){const s=OE,a=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return yb(e,a,r)}function yb(e,n,s){if(zE(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 yh(e.children,n,s)}return Array.isArray(e)?yh(e,n,s):""}function yh(e,n,s){const a=[];let r=-1;for(;++r<e.length;)a[r]=yb(e[r],n,s);return a.join("")}function zE(e){return!!(e&&typeof e=="object")}const wh=document.createElement("i");function Eu(e){const n="&"+e+";";wh.innerHTML=n;const s=wh.textContent;return s.charCodeAt(s.length-1)===59&&e!=="semi"||s===n?!1:s}function Gs(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 ni(e,n){return e.length>0?(Gs(e,e.length,0,n),e):n}const kh={}.hasOwnProperty;function wb(e){const n={};let s=-1;for(;++s<e.length;)FE(n,e[s]);return n}function FE(e,n){let s;for(s in n){const r=(kh.call(e,s)?e[s]:void 0)||(e[s]={}),o=n[s];let l;if(o)for(l in o){kh.call(r,l)||(r[l]=[]);const c=o[l];UE(r[l],Array.isArray(c)?c:c?[c]:[])}}}function UE(e,n){let s=-1;const a=[];for(;++s<n.length;)(n[s].add==="after"?e:a).push(n[s]);Gs(e,0,0,a)}function kb(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 fi(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Ls=la(/[A-Za-z]/),As=la(/[\dA-Za-z]/),BE=la(/[#-'*+\--9=?A-Z^-~]/);function Il(e){return e!==null&&(e<32||e===127)}const Bd=la(/\d/),HE=la(/[\dA-Fa-f]/),qE=la(/[!-/:-@[-`{-~]/);function Wt(e){return e!==null&&e<-2}function An(e){return e!==null&&(e<0||e===32)}function mn(e){return e===-2||e===-1||e===32}const nc=la(/\p{P}|\p{S}/u),_a=la(/\s/);function la(e){return n;function n(s){return s!==null&&s>-1&&e.test(String.fromCharCode(s))}}function Er(e){const n=[];let s=-1,a=0,r=0;for(;++s<e.length;){const o=e.charCodeAt(s);let l="";if(o===37&&As(e.charCodeAt(s+1))&&As(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 pn(e,n,s,a){const r=a?a-1:Number.POSITIVE_INFINITY;let o=0;return l;function l(d){return mn(d)?(e.enter(s),c(d)):n(d)}function c(d){return mn(d)&&o++<r?(e.consume(d),c):(e.exit(s),n(d))}}const VE={tokenize:WE};function WE(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"),pn(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 Wt(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),l)}}const KE={tokenize:GE},jh={tokenize:JE};function GE(e){const n=this,s=[];let a=0,r,o,l;return c;function c(S){if(a<s.length){const k=s[a];return n.containerState=k[1],e.attempt(k[0].continuation,d,u)(S)}return u(S)}function d(S){if(a++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&y();const k=n.events.length;let C=k,v;for(;C--;)if(n.events[C][0]==="exit"&&n.events[C][1].type==="chunkFlow"){v=n.events[C][1].end;break}b(a);let j=k;for(;j<n.events.length;)n.events[j][1].end={...v},j++;return Gs(n.events,C+1,0,n.events.slice(k)),n.events.length=j,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(jh,m,h)(S)}function m(S){return r&&y(),b(a),f(S)}function h(S){return n.parser.lazy[n.now().line]=a!==s.length,l=n.now().offset,g(S)}function f(S){return n.containerState={},e.attempt(jh,p,g)(S)}function p(S){return a++,s.push([n.currentConstruct,n.containerState]),f(S)}function g(S){if(S===null){r&&y(),b(0),e.consume(S);return}return r=r||n.parser.flow(n.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:o}),x(S)}function x(S){if(S===null){w(e.exit("chunkFlow"),!0),b(0),e.consume(S);return}return Wt(S)?(e.consume(S),w(e.exit("chunkFlow")),a=0,n.interrupt=void 0,c):(e.consume(S),x)}function w(S,k){const C=n.sliceStream(S);if(k&&C.push(null),S.previous=o,o&&(o.next=S),o=S,r.defineSkip(S.start),r.write(C),n.parser.lazy[S.start.line]){let v=r.events.length;for(;v--;)if(r.events[v][1].start.offset<l&&(!r.events[v][1].end||r.events[v][1].end.offset>l))return;const j=n.events.length;let P=j,U,E;for(;P--;)if(n.events[P][0]==="exit"&&n.events[P][1].type==="chunkFlow"){if(U){E=n.events[P][1].end;break}U=!0}for(b(a),v=j;v<n.events.length;)n.events[v][1].end={...E},v++;Gs(n.events,P+1,0,n.events.slice(j)),n.events.length=v}}function b(S){let k=s.length;for(;k-- >S;){const C=s[k];n.containerState=C[1],C[0].exit.call(n,e)}s.length=S}function y(){r.write([null]),o=void 0,r=void 0,n.containerState._closeFlow=void 0}}function JE(e,n,s){return pn(e,e.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function fr(e){if(e===null||An(e)||_a(e))return 1;if(nc(e))return 2}function sc(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 Hd={name:"attention",resolveAll:YE,tokenize:QE};function YE(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};Nh(h,-d),Nh(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=ni(u,[["enter",e[a][1],n],["exit",e[a][1],n]])),u=ni(u,[["enter",r,n],["enter",l,n],["exit",l,n],["enter",o,n]]),u=ni(u,sc(n.parser.constructs.insideSpan.null,e.slice(a+1,s),n)),u=ni(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=ni(u,[["enter",e[s][1],n],["exit",e[s][1],n]])):m=0,Gs(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 QE(e,n){const s=this.parser.constructs.attentionMarkers.null,a=this.previous,r=fr(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=fr(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 Nh(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const XE={name:"autolink",tokenize:ZE};function ZE(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||As(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||As(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||Il(p)?s(p):(e.consume(p),d)}function u(p){return p===64?(e.consume(p),m):BE(p)?(e.consume(p),u):s(p)}function m(p){return As(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||As(p))&&a++<63){const g=p===45?f:h;return e.consume(p),g}return s(p)}}const To={partial:!0,tokenize:e2};function e2(e,n,s){return a;function a(o){return mn(o)?pn(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||Wt(o)?n(o):s(o)}}const jb={continuation:{tokenize:n2},exit:s2,name:"blockQuote",tokenize:t2};function t2(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 mn(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(l))}}function n2(e,n,s){const a=this;return r;function r(l){return mn(l)?pn(e,o,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(jb,n,s)(l)}}function s2(e){e.exit("blockQuote")}const Nb={name:"characterEscape",tokenize:i2};function i2(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 qE(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):s(o)}}const Sb={name:"characterReference",tokenize:a2};function a2(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=As,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=HE,m):(e.enter("characterReferenceValue"),o=7,l=Bd,m(h))}function m(h){if(h===59&&r){const f=e.exit("characterReferenceValue");return l===As&&!Eu(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 Sh={partial:!0,tokenize:o2},Ch={concrete:!0,name:"codeFenced",tokenize:r2};function r2(e,n,s){const a=this,r={partial:!0,tokenize:C};let o=0,l=0,c;return d;function d(v){return u(v)}function u(v){const j=a.events[a.events.length-1];return o=j&&j[1].type==="linePrefix"?j[2].sliceSerialize(j[1],!0).length:0,c=v,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),m(v)}function m(v){return v===c?(l++,e.consume(v),m):l<3?s(v):(e.exit("codeFencedFenceSequence"),mn(v)?pn(e,h,"whitespace")(v):h(v))}function h(v){return v===null||Wt(v)?(e.exit("codeFencedFence"),a.interrupt?n(v):e.check(Sh,x,k)(v)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(v))}function f(v){return v===null||Wt(v)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(v)):mn(v)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),pn(e,p,"whitespace")(v)):v===96&&v===c?s(v):(e.consume(v),f)}function p(v){return v===null||Wt(v)?h(v):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(v))}function g(v){return v===null||Wt(v)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),h(v)):v===96&&v===c?s(v):(e.consume(v),g)}function x(v){return e.attempt(r,k,w)(v)}function w(v){return e.enter("lineEnding"),e.consume(v),e.exit("lineEnding"),b}function b(v){return o>0&&mn(v)?pn(e,y,"linePrefix",o+1)(v):y(v)}function y(v){return v===null||Wt(v)?e.check(Sh,x,k)(v):(e.enter("codeFlowValue"),S(v))}function S(v){return v===null||Wt(v)?(e.exit("codeFlowValue"),y(v)):(e.consume(v),S)}function k(v){return e.exit("codeFenced"),n(v)}function C(v,j,P){let U=0;return E;function E(O){return v.enter("lineEnding"),v.consume(O),v.exit("lineEnding"),R}function R(O){return v.enter("codeFencedFence"),mn(O)?pn(v,L,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(O):L(O)}function L(O){return O===c?(v.enter("codeFencedFenceSequence"),F(O)):P(O)}function F(O){return O===c?(U++,v.consume(O),F):U>=l?(v.exit("codeFencedFenceSequence"),mn(O)?pn(v,M,"whitespace")(O):M(O)):P(O)}function M(O){return O===null||Wt(O)?(v.exit("codeFencedFence"),j(O)):P(O)}}}function o2(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 Pc={name:"codeIndented",tokenize:c2},l2={partial:!0,tokenize:d2};function c2(e,n,s){const a=this;return r;function r(u){return e.enter("codeIndented"),pn(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):Wt(u)?e.attempt(l2,l,d)(u):(e.enter("codeFlowValue"),c(u))}function c(u){return u===null||Wt(u)?(e.exit("codeFlowValue"),l(u)):(e.consume(u),c)}function d(u){return e.exit("codeIndented"),n(u)}}function d2(e,n,s){const a=this;return r;function r(l){return a.parser.lazy[a.now().line]?s(l):Wt(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r):pn(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):Wt(l)?r(l):s(l)}}const u2={name:"codeText",previous:h2,resolve:m2,tokenize:p2};function m2(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 h2(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function p2(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)):Wt(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||Wt(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 f2{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&&Dr(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),Dr(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),Dr(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);Dr(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);Dr(this.left,s.reverse())}}}function Dr(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 Cb(e){const n={};let s=-1,a,r,o,l,c,d,u;const m=new f2(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,g2(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 Gs(e,0,Number.POSITIVE_INFINITY,m.slice(0)),!u}function g2(e,n){const s=e.get(n)[1],a=e.get(n)[2];let r=n-1;const o=[];let l=s._tokenizer;l||(l=a.parser[s.contentType](s.start),s._contentTypeTextTrailing&&(l._contentTypeTextTrailing=!0));const c=l.events,d=[],u={};let m,h,f=-1,p=s,g=0,x=0;const w=[x];for(;p;){for(;e.get(++r)[1]!==p;);o.push(r),p._tokenizer||(m=a.sliceStream(p),p.next||m.push(null),h&&l.defineSkip(p.start),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=!0),l.write(m),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=void 0)),h=p,p=p.next}for(p=s;++f<c.length;)c[f][0]==="exit"&&c[f-1][0]==="enter"&&c[f][1].type===c[f-1][1].type&&c[f][1].start.line!==c[f][1].end.line&&(x=f+1,w.push(x),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(l.events=[],p?(p._tokenizer=void 0,p.previous=void 0):w.pop(),f=w.length;f--;){const b=c.slice(w[f],w[f+1]),y=o.pop();d.push([y,y+b.length-1]),e.splice(y,2,b)}for(d.reverse(),f=-1;++f<d.length;)u[g+d[f][0]]=g+d[f][1],g+=d[f][1]-d[f][0]-1;return u}const b2={resolve:v2,tokenize:y2},x2={partial:!0,tokenize:w2};function v2(e){return Cb(e),e}function y2(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):Wt(c)?e.check(x2,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 w2(e,n,s){const a=this;return r;function r(l){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),pn(e,o,"linePrefix")}function o(l){if(l===null||Wt(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 Eb(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||Il(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||Wt(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||An(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||Il(b)?s(b):(e.consume(b),b===92?w:x)}function w(b){return b===40||b===41||b===92?(e.consume(b),x):x(b)}}function _b(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):Wt(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||Wt(p)||c++>999?(e.exit("chunkString"),m(p)):(e.consume(p),d||(d=!mn(p)),p===92?f:h)}function f(p){return p===91||p===92||p===93?(e.consume(p),c++,h):h(p)}}function Mb(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):Wt(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),pn(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),m(f))}function m(f){return f===l||f===null||Wt(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 ao(e,n){let s;return a;function a(r){return Wt(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s=!0,a):mn(r)?pn(e,a,s?"linePrefix":"lineSuffix")(r):n(r)}}const k2={name:"definition",tokenize:N2},j2={partial:!0,tokenize:S2};function N2(e,n,s){const a=this;let r;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return _b.call(a,e,c,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function c(p){return r=fi(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 An(p)?ao(e,u)(p):u(p)}function u(p){return Eb(e,m,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function m(p){return e.attempt(j2,h,h)(p)}function h(p){return mn(p)?pn(e,f,"whitespace")(p):f(p)}function f(p){return p===null||Wt(p)?(e.exit("definition"),a.parser.defined.push(r),n(p)):s(p)}}function S2(e,n,s){return a;function a(c){return An(c)?ao(e,r)(c):s(c)}function r(c){return Mb(e,o,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return mn(c)?pn(e,l,"whitespace")(c):l(c)}function l(c){return c===null||Wt(c)?n(c):s(c)}}const C2={name:"hardBreakEscape",tokenize:E2};function E2(e,n,s){return a;function a(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return Wt(o)?(e.exit("hardBreakEscape"),n(o)):s(o)}}const _2={name:"headingAtx",resolve:M2,tokenize:A2};function M2(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"},Gs(e,a,s-a+1,[["enter",r,n],["enter",o,n],["exit",o,n],["exit",r,n]])),e}function A2(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||An(m)?(e.exit("atxHeadingSequence"),c(m)):s(m)}function c(m){return m===35?(e.enter("atxHeadingSequence"),d(m)):m===null||Wt(m)?(e.exit("atxHeading"),n(m)):mn(m)?pn(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||An(m)?(e.exit("atxHeadingText"),c(m)):(e.consume(m),u)}}const P2=["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"],Eh=["pre","script","style","textarea"],R2={concrete:!0,name:"htmlFlow",resolveTo:$2,tokenize:D2},I2={partial:!0,tokenize:O2},T2={partial:!0,tokenize:L2};function $2(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 D2(e,n,s){const a=this;let r,o,l,c,d;return u;function u(N){return m(N)}function m(N){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(N),h}function h(N){return N===33?(e.consume(N),f):N===47?(e.consume(N),o=!0,x):N===63?(e.consume(N),r=3,a.interrupt?n:A):Ls(N)?(e.consume(N),l=String.fromCharCode(N),w):s(N)}function f(N){return N===45?(e.consume(N),r=2,p):N===91?(e.consume(N),r=5,c=0,g):Ls(N)?(e.consume(N),r=4,a.interrupt?n:A):s(N)}function p(N){return N===45?(e.consume(N),a.interrupt?n:A):s(N)}function g(N){const G="CDATA[";return N===G.charCodeAt(c++)?(e.consume(N),c===G.length?a.interrupt?n:L:g):s(N)}function x(N){return Ls(N)?(e.consume(N),l=String.fromCharCode(N),w):s(N)}function w(N){if(N===null||N===47||N===62||An(N)){const G=N===47,ge=l.toLowerCase();return!G&&!o&&Eh.includes(ge)?(r=1,a.interrupt?n(N):L(N)):P2.includes(l.toLowerCase())?(r=6,G?(e.consume(N),b):a.interrupt?n(N):L(N)):(r=7,a.interrupt&&!a.parser.lazy[a.now().line]?s(N):o?y(N):S(N))}return N===45||As(N)?(e.consume(N),l+=String.fromCharCode(N),w):s(N)}function b(N){return N===62?(e.consume(N),a.interrupt?n:L):s(N)}function y(N){return mn(N)?(e.consume(N),y):E(N)}function S(N){return N===47?(e.consume(N),E):N===58||N===95||Ls(N)?(e.consume(N),k):mn(N)?(e.consume(N),S):E(N)}function k(N){return N===45||N===46||N===58||N===95||As(N)?(e.consume(N),k):C(N)}function C(N){return N===61?(e.consume(N),v):mn(N)?(e.consume(N),C):S(N)}function v(N){return N===null||N===60||N===61||N===62||N===96?s(N):N===34||N===39?(e.consume(N),d=N,j):mn(N)?(e.consume(N),v):P(N)}function j(N){return N===d?(e.consume(N),d=null,U):N===null||Wt(N)?s(N):(e.consume(N),j)}function P(N){return N===null||N===34||N===39||N===47||N===60||N===61||N===62||N===96||An(N)?C(N):(e.consume(N),P)}function U(N){return N===47||N===62||mn(N)?S(N):s(N)}function E(N){return N===62?(e.consume(N),R):s(N)}function R(N){return N===null||Wt(N)?L(N):mn(N)?(e.consume(N),R):s(N)}function L(N){return N===45&&r===2?(e.consume(N),q):N===60&&r===1?(e.consume(N),te):N===62&&r===4?(e.consume(N),I):N===63&&r===3?(e.consume(N),A):N===93&&r===5?(e.consume(N),K):Wt(N)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(I2,$,F)(N)):N===null||Wt(N)?(e.exit("htmlFlowData"),F(N)):(e.consume(N),L)}function F(N){return e.check(T2,M,$)(N)}function M(N){return e.enter("lineEnding"),e.consume(N),e.exit("lineEnding"),O}function O(N){return N===null||Wt(N)?F(N):(e.enter("htmlFlowData"),L(N))}function q(N){return N===45?(e.consume(N),A):L(N)}function te(N){return N===47?(e.consume(N),l="",Z):L(N)}function Z(N){if(N===62){const G=l.toLowerCase();return Eh.includes(G)?(e.consume(N),I):L(N)}return Ls(N)&&l.length<8?(e.consume(N),l+=String.fromCharCode(N),Z):L(N)}function K(N){return N===93?(e.consume(N),A):L(N)}function A(N){return N===62?(e.consume(N),I):N===45&&r===2?(e.consume(N),A):L(N)}function I(N){return N===null||Wt(N)?(e.exit("htmlFlowData"),$(N)):(e.consume(N),I)}function $(N){return e.exit("htmlFlow"),n(N)}}function L2(e,n,s){const a=this;return r;function r(l){return Wt(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 O2(e,n,s){return a;function a(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(To,n,s)}}const z2={name:"htmlText",tokenize:F2};function F2(e,n,s){const a=this;let r,o,l;return c;function c(A){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(A),d}function d(A){return A===33?(e.consume(A),u):A===47?(e.consume(A),C):A===63?(e.consume(A),S):Ls(A)?(e.consume(A),P):s(A)}function u(A){return A===45?(e.consume(A),m):A===91?(e.consume(A),o=0,g):Ls(A)?(e.consume(A),y):s(A)}function m(A){return A===45?(e.consume(A),p):s(A)}function h(A){return A===null?s(A):A===45?(e.consume(A),f):Wt(A)?(l=h,te(A)):(e.consume(A),h)}function f(A){return A===45?(e.consume(A),p):h(A)}function p(A){return A===62?q(A):A===45?f(A):h(A)}function g(A){const I="CDATA[";return A===I.charCodeAt(o++)?(e.consume(A),o===I.length?x:g):s(A)}function x(A){return A===null?s(A):A===93?(e.consume(A),w):Wt(A)?(l=x,te(A)):(e.consume(A),x)}function w(A){return A===93?(e.consume(A),b):x(A)}function b(A){return A===62?q(A):A===93?(e.consume(A),b):x(A)}function y(A){return A===null||A===62?q(A):Wt(A)?(l=y,te(A)):(e.consume(A),y)}function S(A){return A===null?s(A):A===63?(e.consume(A),k):Wt(A)?(l=S,te(A)):(e.consume(A),S)}function k(A){return A===62?q(A):S(A)}function C(A){return Ls(A)?(e.consume(A),v):s(A)}function v(A){return A===45||As(A)?(e.consume(A),v):j(A)}function j(A){return Wt(A)?(l=j,te(A)):mn(A)?(e.consume(A),j):q(A)}function P(A){return A===45||As(A)?(e.consume(A),P):A===47||A===62||An(A)?U(A):s(A)}function U(A){return A===47?(e.consume(A),q):A===58||A===95||Ls(A)?(e.consume(A),E):Wt(A)?(l=U,te(A)):mn(A)?(e.consume(A),U):q(A)}function E(A){return A===45||A===46||A===58||A===95||As(A)?(e.consume(A),E):R(A)}function R(A){return A===61?(e.consume(A),L):Wt(A)?(l=R,te(A)):mn(A)?(e.consume(A),R):U(A)}function L(A){return A===null||A===60||A===61||A===62||A===96?s(A):A===34||A===39?(e.consume(A),r=A,F):Wt(A)?(l=L,te(A)):mn(A)?(e.consume(A),L):(e.consume(A),M)}function F(A){return A===r?(e.consume(A),r=void 0,O):A===null?s(A):Wt(A)?(l=F,te(A)):(e.consume(A),F)}function M(A){return A===null||A===34||A===39||A===60||A===61||A===96?s(A):A===47||A===62||An(A)?U(A):(e.consume(A),M)}function O(A){return A===47||A===62||An(A)?U(A):s(A)}function q(A){return A===62?(e.consume(A),e.exit("htmlTextData"),e.exit("htmlText"),n):s(A)}function te(A){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(A),e.exit("lineEnding"),Z}function Z(A){return mn(A)?pn(e,K,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(A):K(A)}function K(A){return e.enter("htmlTextData"),l(A)}}const _u={name:"labelEnd",resolveAll:q2,resolveTo:V2,tokenize:W2},U2={tokenize:K2},B2={tokenize:G2},H2={tokenize:J2};function q2(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&&Gs(e,0,e.length,s),e}function V2(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=ni(c,e.slice(o+1,o+a+3)),c=ni(c,[["enter",m,n]]),c=ni(c,sc(n.parser.constructs.insideSpan.null,e.slice(o+a+4,l-3),n)),c=ni(c,[["exit",m,n],e[l-2],e[l-1],["exit",u,n]]),c=ni(c,e.slice(l+1)),c=ni(c,[["exit",d,n]]),Gs(e,o,e.length,c),e}function W2(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(fi(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(U2,m,l?m:h)(f):f===91?e.attempt(B2,m,l?u:h)(f):l?m(f):h(f)}function u(f){return e.attempt(H2,m,h)(f)}function m(f){return n(f)}function h(f){return o._balanced=!0,s(f)}}function K2(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 An(h)?ao(e,o)(h):o(h)}function o(h){return h===41?m(h):Eb(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function l(h){return An(h)?ao(e,d)(h):m(h)}function c(h){return s(h)}function d(h){return h===34||h===39||h===40?Mb(e,u,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):m(h)}function u(h){return An(h)?ao(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 G2(e,n,s){const a=this;return r;function r(c){return _b.call(a,e,o,l,"reference","referenceMarker","referenceString")(c)}function o(c){return a.parser.defined.includes(fi(a.sliceSerialize(a.events[a.events.length-1][1]).slice(1,-1)))?n(c):s(c)}function l(c){return s(c)}}function J2(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 Y2={name:"labelStartImage",resolveAll:_u.resolveAll,tokenize:Q2};function Q2(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 X2={name:"labelStartLink",resolveAll:_u.resolveAll,tokenize:Z2};function Z2(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 Rc={name:"lineEnding",tokenize:e_};function e_(e,n){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),pn(e,n,"linePrefix")}}const vl={name:"thematicBreak",tokenize:t_};function t_(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||Wt(u))?(e.exit("thematicBreak"),n(u)):s(u)}function d(u){return u===r?(e.consume(u),a++,d):(e.exit("thematicBreakSequence"),mn(u)?pn(e,c,"whitespace")(u):c(u))}}const zs={continuation:{tokenize:a_},exit:o_,name:"list",tokenize:i_},n_={partial:!0,tokenize:l_},s_={partial:!0,tokenize:r_};function i_(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:Bd(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(vl,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 Bd(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(To,a.interrupt?s:m,e.attempt(n_,f,h))}function m(p){return a.containerState.initialBlankLine=!0,o++,f(p)}function h(p){return mn(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 a_(e,n,s){const a=this;return a.containerState._closeFlow=void 0,e.check(To,r,o);function r(c){return a.containerState.furtherBlankLines=a.containerState.furtherBlankLines||a.containerState.initialBlankLine,pn(e,n,"listItemIndent",a.containerState.size+1)(c)}function o(c){return a.containerState.furtherBlankLines||!mn(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(s_,n,l)(c))}function l(c){return a.containerState._closeFlow=!0,a.interrupt=void 0,pn(e,e.attempt(zs,n,s),"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function r_(e,n,s){const a=this;return pn(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 o_(e){e.exit(this.containerState.type)}function l_(e,n,s){const a=this;return pn(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!mn(o)&&l&&l[1].type==="listItemPrefixWhitespace"?n(o):s(o)}}const _h={name:"setextUnderline",resolveTo:c_,tokenize:d_};function c_(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 d_(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"),mn(u)?pn(e,d,"lineSuffix")(u):d(u))}function d(u){return u===null||Wt(u)?(e.exit("setextHeadingLine"),n(u)):s(u)}}const u_={tokenize:m_};function m_(e){const n=this,s=e.attempt(To,a,e.attempt(this.parser.constructs.flowInitial,r,pn(e,e.attempt(this.parser.constructs.flow,r,e.attempt(b2,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 h_={resolveAll:Pb()},p_=Ab("string"),f_=Ab("text");function Ab(e){return{resolveAll:Pb(e==="text"?g_: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 Pb(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 g_(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 b_={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:jb},x_={91:k2},v_={[-2]:Pc,[-1]:Pc,32:Pc},y_={35:_2,42:vl,45:[_h,vl],60:R2,61:_h,95:vl,96:Ch,126:Ch},w_={38:Sb,92:Nb},k_={[-5]:Rc,[-4]:Rc,[-3]:Rc,33:Y2,38:Sb,42:Hd,60:[XE,z2],91:X2,92:[C2,Nb],93:_u,95:Hd,96:u2},j_={null:[Hd,h_]},N_={null:[42,95]},S_={null:[]},C_=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:N_,contentInitial:x_,disable:S_,document:b_,flow:y_,flowInitial:v_,insideSpan:j_,string:w_,text:k_},Symbol.toStringTag,{value:"Module"}));function E_(e,n,s){let a={_bufferIndex:-1,_index:0,line:s&&s.line||1,column:s&&s.column||1,offset:s&&s.offset||0};const r={},o=[];let l=[],c=[];const d={attempt:j(C),check:j(v),consume:y,enter:S,exit:k,interrupt:j(v,{interrupt:!0})},u={code:null,containerState:{},defineSkip:x,events:[],now:g,parser:e,previous:null,sliceSerialize:f,sliceStream:p,write:h};let m=n.tokenize.call(u,d);return n.resolveAll&&o.push(n),u;function h(R){return l=ni(l,R),w(),l[l.length-1]!==null?[]:(P(n,0),u.events=sc(o,u.events,u),u.events)}function f(R,L){return M_(p(R),L)}function p(R){return __(l,R)}function g(){const{_bufferIndex:R,_index:L,line:F,column:M,offset:O}=a;return{_bufferIndex:R,_index:L,line:F,column:M,offset:O}}function x(R){r[R.line]=R.column,E()}function w(){let R;for(;a._index<l.length;){const L=l[a._index];if(typeof L=="string")for(R=a._index,a._bufferIndex<0&&(a._bufferIndex=0);a._index===R&&a._bufferIndex<L.length;)b(L.charCodeAt(a._bufferIndex));else b(L)}}function b(R){m=m(R)}function y(R){Wt(R)?(a.line++,a.column=1,a.offset+=R===-3?2:1,E()):R!==-1&&(a.column++,a.offset++),a._bufferIndex<0?a._index++:(a._bufferIndex++,a._bufferIndex===l[a._index].length&&(a._bufferIndex=-1,a._index++)),u.previous=R}function S(R,L){const F=L||{};return F.type=R,F.start=g(),u.events.push(["enter",F,u]),c.push(F),F}function k(R){const L=c.pop();return L.end=g(),u.events.push(["exit",L,u]),L}function C(R,L){P(R,L.from)}function v(R,L){L.restore()}function j(R,L){return F;function F(M,O,q){let te,Z,K,A;return Array.isArray(M)?$(M):"tokenize"in M?$([M]):I(M);function I(je){return ke;function ke(ne){const qe=ne!==null&&je[ne],ee=ne!==null&&je.null,le=[...Array.isArray(qe)?qe:qe?[qe]:[],...Array.isArray(ee)?ee:ee?[ee]:[]];return $(le)(ne)}}function $(je){return te=je,Z=0,je.length===0?q:N(je[Z])}function N(je){return ke;function ke(ne){return A=U(),K=je,je.partial||(u.currentConstruct=je),je.name&&u.parser.constructs.disable.null.includes(je.name)?ge():je.tokenize.call(L?Object.assign(Object.create(u),L):u,d,G,ge)(ne)}}function G(je){return R(K,A),O}function ge(je){return A.restore(),++Z<te.length?N(te[Z]):q}}}function P(R,L){R.resolveAll&&!o.includes(R)&&o.push(R),R.resolve&&Gs(u.events,L,u.events.length-L,R.resolve(u.events.slice(L),u)),R.resolveTo&&(u.events=R.resolveTo(u.events,u))}function U(){const R=g(),L=u.previous,F=u.currentConstruct,M=u.events.length,O=Array.from(c);return{from:M,restore:q};function q(){a=R,u.previous=L,u.currentConstruct=F,u.events.length=M,c=O,E()}}function E(){a.line in r&&a.column<2&&(a.column=r[a.line],a.offset+=r[a.line]-1)}}function __(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 M_(e,n){let s=-1;const a=[];let r;for(;++s<e.length;){const o=e[s];let l;if(typeof o=="string")l=o;else switch(o){case-5:{l="\r";break}case-4:{l=`
|
|
653
|
+
`;break}case-3:{l=`\r
|
|
654
|
+
`;break}case-2:{l=n?" ":" ";break}case-1:{if(!n&&r)continue;l=" ";break}default:l=String.fromCharCode(o)}r=o===-2,a.push(l)}return a.join("")}function A_(e){const a={constructs:wb([C_,...(e||{}).extensions||[]]),content:r(VE),defined:[],document:r(KE),flow:r(u_),lazy:{},string:r(p_),text:r(f_)};return a;function r(o){return l;function l(c){return E_(a,o,c)}}}function P_(e){for(;!Cb(e););return e}const Mh=/[\0\t\n\r]/g;function R_(){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(Mh.lastIndex=h,u=Mh.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 I_=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function T_(e){return e.replace(I_,$_)}function $_(e,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),o=r===120||r===88;return kb(s.slice(o?2:1),o?16:10)}return Eu(s)||e}const Rb={}.hasOwnProperty;function D_(e,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),L_(s)(P_(A_(s).document().write(R_()(e,n,!0))))}function L_(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(be),autolinkProtocol:U,autolinkEmail:U,atxHeading:o(B),blockQuote:o(ee),characterEscape:U,characterReference:U,codeFenced:o(le),codeFencedFenceInfo:l,codeFencedFenceMeta:l,codeIndented:o(le,l),codeText:o(se,l),codeTextData:U,data:U,codeFlowValue:U,definition:o(re),definitionDestinationString:l,definitionLabelString:l,definitionTitleString:l,emphasis:o(J),hardBreakEscape:o(ve),hardBreakTrailing:o(ve),htmlFlow:o(Ne,l),htmlFlowData:U,htmlText:o(Ne,l),htmlTextData:U,image:o(H),label:l,link:o(be),listItem:o(Me),listItemValue:f,listOrdered:o(ce,h),listUnordered:o(ce),paragraph:o(Le),reference:N,referenceString:l,resourceDestinationString:l,resourceTitleString:l,setextHeading:o(B),strong:o(He),thematicBreak:o(Ue)},exit:{atxHeading:d(),atxHeadingSequence:C,autolink:d(),autolinkEmail:qe,autolinkProtocol:ne,blockQuote:d(),characterEscapeValue:E,characterReferenceMarkerHexadecimal:ge,characterReferenceMarkerNumeric:ge,characterReferenceValue:je,characterReference:ke,codeFenced:d(w),codeFencedFence:x,codeFencedFenceInfo:p,codeFencedFenceMeta:g,codeFlowValue:E,codeIndented:d(b),codeText:d(O),codeTextData:E,data:E,definition:d(),definitionDestinationString:k,definitionLabelString:y,definitionTitleString:S,emphasis:d(),hardBreakEscape:d(L),hardBreakTrailing:d(L),htmlFlow:d(F),htmlFlowData:E,htmlText:d(M),htmlTextData:E,image:d(te),label:K,labelText:Z,lineEnding:R,link:d(q),listItem:d(),listOrdered:d(),listUnordered:d(),paragraph:d(),referenceString:G,resourceDestinationString:A,resourceTitleString:I,resource:$,setextHeading:d(P),setextHeadingLineSequence:j,setextHeadingText:v,strong:d(),thematicBreak:d()}};Ib(n,(e||{}).mdastExtensions||[]);const s={};return a;function a(pe){let Oe={type:"root",children:[]};const ze={stack:[Oe],tokenStack:[],config:n,enter:c,exit:u,buffer:l,resume:m,data:s},lt=[];let Be=-1;for(;++Be<pe.length;)if(pe[Be][1].type==="listOrdered"||pe[Be][1].type==="listUnordered")if(pe[Be][0]==="enter")lt.push(Be);else{const ye=lt.pop();Be=r(pe,ye,Be)}for(Be=-1;++Be<pe.length;){const ye=n[pe[Be][0]];Rb.call(ye,pe[Be][1].type)&&ye[pe[Be][1].type].call(Object.assign({sliceSerialize:pe[Be][2].sliceSerialize},ze),pe[Be][1])}if(ze.tokenStack.length>0){const ye=ze.tokenStack[ze.tokenStack.length-1];(ye[1]||Ah).call(ze,void 0,ye[0])}for(Oe.position={start:Yi(pe.length>0?pe[0][1].start:{line:1,column:1,offset:0}),end:Yi(pe.length>0?pe[pe.length-2][1].end:{line:1,column:1,offset:0})},Be=-1;++Be<n.transforms.length;)Oe=n.transforms[Be](Oe)||Oe;return Oe}function r(pe,Oe,ze){let lt=Oe-1,Be=-1,ye=!1,Y,_e,ct,pt;for(;++lt<=ze;){const de=pe[lt];switch(de[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{de[0]==="enter"?Be++:Be--,pt=void 0;break}case"lineEndingBlank":{de[0]==="enter"&&(Y&&!pt&&!Be&&!ct&&(ct=lt),pt=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:pt=void 0}if(!Be&&de[0]==="enter"&&de[1].type==="listItemPrefix"||Be===-1&&de[0]==="exit"&&(de[1].type==="listUnordered"||de[1].type==="listOrdered")){if(Y){let Ve=lt;for(_e=void 0;Ve--;){const Ee=pe[Ve];if(Ee[1].type==="lineEnding"||Ee[1].type==="lineEndingBlank"){if(Ee[0]==="exit")continue;_e&&(pe[_e][1].type="lineEndingBlank",ye=!0),Ee[1].type="lineEnding",_e=Ve}else if(!(Ee[1].type==="linePrefix"||Ee[1].type==="blockQuotePrefix"||Ee[1].type==="blockQuotePrefixWhitespace"||Ee[1].type==="blockQuoteMarker"||Ee[1].type==="listItemIndent"))break}ct&&(!_e||ct<_e)&&(Y._spread=!0),Y.end=Object.assign({},_e?pe[_e][1].start:de[1].end),pe.splice(_e||lt,0,["exit",Y,de[2]]),lt++,ze++}if(de[1].type==="listItemPrefix"){const Ve={type:"listItem",_spread:!1,start:Object.assign({},de[1].start),end:void 0};Y=Ve,pe.splice(lt,0,["enter",Ve,de[2]]),lt++,ze++,ct=void 0,pt=!0}}}return pe[Oe][1]._spread=ye,ze}function o(pe,Oe){return ze;function ze(lt){c.call(this,pe(lt),lt),Oe&&Oe.call(this,lt)}}function l(){this.stack.push({type:"fragment",children:[]})}function c(pe,Oe,ze){this.stack[this.stack.length-1].children.push(pe),this.stack.push(pe),this.tokenStack.push([Oe,ze||void 0]),pe.position={start:Yi(Oe.start),end:void 0}}function d(pe){return Oe;function Oe(ze){pe&&pe.call(this,ze),u.call(this,ze)}}function u(pe,Oe){const ze=this.stack.pop(),lt=this.tokenStack.pop();if(lt)lt[0].type!==pe.type&&(Oe?Oe.call(this,pe,lt[0]):(lt[1]||Ah).call(this,pe,lt[0]));else throw new Error("Cannot close `"+pe.type+"` ("+io({start:pe.start,end:pe.end})+"): it’s not open");ze.position.end=Yi(pe.end)}function m(){return Cu(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function f(pe){if(this.data.expectingFirstListItemValue){const Oe=this.stack[this.stack.length-2];Oe.start=Number.parseInt(this.sliceSerialize(pe),10),this.data.expectingFirstListItemValue=void 0}}function p(){const pe=this.resume(),Oe=this.stack[this.stack.length-1];Oe.lang=pe}function g(){const pe=this.resume(),Oe=this.stack[this.stack.length-1];Oe.meta=pe}function x(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function w(){const pe=this.resume(),Oe=this.stack[this.stack.length-1];Oe.value=pe.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function b(){const pe=this.resume(),Oe=this.stack[this.stack.length-1];Oe.value=pe.replace(/(\r?\n|\r)$/g,"")}function y(pe){const Oe=this.resume(),ze=this.stack[this.stack.length-1];ze.label=Oe,ze.identifier=fi(this.sliceSerialize(pe)).toLowerCase()}function S(){const pe=this.resume(),Oe=this.stack[this.stack.length-1];Oe.title=pe}function k(){const pe=this.resume(),Oe=this.stack[this.stack.length-1];Oe.url=pe}function C(pe){const Oe=this.stack[this.stack.length-1];if(!Oe.depth){const ze=this.sliceSerialize(pe).length;Oe.depth=ze}}function v(){this.data.setextHeadingSlurpLineEnding=!0}function j(pe){const Oe=this.stack[this.stack.length-1];Oe.depth=this.sliceSerialize(pe).codePointAt(0)===61?1:2}function P(){this.data.setextHeadingSlurpLineEnding=void 0}function U(pe){const ze=this.stack[this.stack.length-1].children;let lt=ze[ze.length-1];(!lt||lt.type!=="text")&&(lt=gt(),lt.position={start:Yi(pe.start),end:void 0},ze.push(lt)),this.stack.push(lt)}function E(pe){const Oe=this.stack.pop();Oe.value+=this.sliceSerialize(pe),Oe.position.end=Yi(pe.end)}function R(pe){const Oe=this.stack[this.stack.length-1];if(this.data.atHardBreak){const ze=Oe.children[Oe.children.length-1];ze.position.end=Yi(pe.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(Oe.type)&&(U.call(this,pe),E.call(this,pe))}function L(){this.data.atHardBreak=!0}function F(){const pe=this.resume(),Oe=this.stack[this.stack.length-1];Oe.value=pe}function M(){const pe=this.resume(),Oe=this.stack[this.stack.length-1];Oe.value=pe}function O(){const pe=this.resume(),Oe=this.stack[this.stack.length-1];Oe.value=pe}function q(){const pe=this.stack[this.stack.length-1];if(this.data.inReference){const Oe=this.data.referenceType||"shortcut";pe.type+="Reference",pe.referenceType=Oe,delete pe.url,delete pe.title}else delete pe.identifier,delete pe.label;this.data.referenceType=void 0}function te(){const pe=this.stack[this.stack.length-1];if(this.data.inReference){const Oe=this.data.referenceType||"shortcut";pe.type+="Reference",pe.referenceType=Oe,delete pe.url,delete pe.title}else delete pe.identifier,delete pe.label;this.data.referenceType=void 0}function Z(pe){const Oe=this.sliceSerialize(pe),ze=this.stack[this.stack.length-2];ze.label=T_(Oe),ze.identifier=fi(Oe).toLowerCase()}function K(){const pe=this.stack[this.stack.length-1],Oe=this.resume(),ze=this.stack[this.stack.length-1];if(this.data.inReference=!0,ze.type==="link"){const lt=pe.children;ze.children=lt}else ze.alt=Oe}function A(){const pe=this.resume(),Oe=this.stack[this.stack.length-1];Oe.url=pe}function I(){const pe=this.resume(),Oe=this.stack[this.stack.length-1];Oe.title=pe}function $(){this.data.inReference=void 0}function N(){this.data.referenceType="collapsed"}function G(pe){const Oe=this.resume(),ze=this.stack[this.stack.length-1];ze.label=Oe,ze.identifier=fi(this.sliceSerialize(pe)).toLowerCase(),this.data.referenceType="full"}function ge(pe){this.data.characterReferenceType=pe.type}function je(pe){const Oe=this.sliceSerialize(pe),ze=this.data.characterReferenceType;let lt;ze?(lt=kb(Oe,ze==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):lt=Eu(Oe);const Be=this.stack[this.stack.length-1];Be.value+=lt}function ke(pe){const Oe=this.stack.pop();Oe.position.end=Yi(pe.end)}function ne(pe){E.call(this,pe);const Oe=this.stack[this.stack.length-1];Oe.url=this.sliceSerialize(pe)}function qe(pe){E.call(this,pe);const Oe=this.stack[this.stack.length-1];Oe.url="mailto:"+this.sliceSerialize(pe)}function ee(){return{type:"blockquote",children:[]}}function le(){return{type:"code",lang:null,meta:null,value:""}}function se(){return{type:"inlineCode",value:""}}function re(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function J(){return{type:"emphasis",children:[]}}function B(){return{type:"heading",depth:0,children:[]}}function ve(){return{type:"break"}}function Ne(){return{type:"html",value:""}}function H(){return{type:"image",title:null,url:"",alt:null}}function be(){return{type:"link",title:null,url:"",children:[]}}function ce(pe){return{type:"list",ordered:pe.type==="listOrdered",start:null,spread:pe._spread,children:[]}}function Me(pe){return{type:"listItem",spread:pe._spread,checked:null,children:[]}}function Le(){return{type:"paragraph",children:[]}}function He(){return{type:"strong",children:[]}}function gt(){return{type:"text",value:""}}function Ue(){return{type:"thematicBreak"}}}function Yi(e){return{line:e.line,column:e.column,offset:e.offset}}function Ib(e,n){let s=-1;for(;++s<n.length;){const a=n[s];Array.isArray(a)?Ib(e,a):O_(e,a)}}function O_(e,n){let s;for(s in n)if(Rb.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 Ah(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+io({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+io({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+io({start:n.start,end:n.end})+") is still open")}function z_(e){const n=this;n.parser=s;function s(a){return D_(a,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function F_(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 U_(e,n){const s={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,s),[e.applyData(n,s),{type:"text",value:`
|
|
655
|
+
`}]}function B_(e,n){const s=n.value?n.value+`
|
|
656
|
+
`:"",a={},r=n.lang?n.lang.split(/\s+/):[];r.length>0&&(a.className=["language-"+r[0]]);let o={type:"element",tagName:"code",properties:a,children:[{type:"text",value:s}]};return n.meta&&(o.data={meta:n.meta}),e.patch(n,o),o=e.applyData(n,o),o={type:"element",tagName:"pre",properties:{},children:[o]},e.patch(n,o),o}function H_(e,n){const s={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function q_(e,n){const s={type:"element",tagName:"em",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function V_(e,n){const s=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",a=String(n.identifier).toUpperCase(),r=Er(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 W_(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 K_(e,n){if(e.options.allowDangerousHtml){const s={type:"raw",value:n.value};return e.patch(n,s),e.applyData(n,s)}}function Tb(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 G_(e,n){const s=String(n.identifier).toUpperCase(),a=e.definitionById.get(s);if(!a)return Tb(e,n);const r={src:Er(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 J_(e,n){const s={src:Er(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 Y_(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 Q_(e,n){const s=String(n.identifier).toUpperCase(),a=e.definitionById.get(s);if(!a)return Tb(e,n);const r={href:Er(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 X_(e,n){const s={href:Er(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 Z_(e,n,s){const a=e.all(n),r=s?eM(s):$b(n),o={},l=[];if(typeof n.checked=="boolean"){const m=a[0];let h;m&&m.type==="element"&&m.tagName==="p"?h=m:(h={type:"element",tagName:"p",properties:{},children:[]},a.unshift(h)),h.children.length>0&&h.children.unshift({type:"text",value:" "}),h.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:n.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let c=-1;for(;++c<a.length;){const m=a[c];(r||c!==0||m.type!=="element"||m.tagName!=="p")&&l.push({type:"text",value:`
|
|
657
|
+
`}),m.type==="element"&&m.tagName==="p"&&!r?l.push(...m.children):l.push(m)}const d=a[a.length-1];d&&(r||d.type!=="element"||d.tagName!=="p")&&l.push({type:"text",value:`
|
|
658
|
+
`});const u={type:"element",tagName:"li",properties:o,children:l};return e.patch(n,u),e.applyData(n,u)}function eM(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=$b(s[a])}return n}function $b(e){const n=e.spread;return n??e.children.length>1}function tM(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 nM(e,n){const s={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function sM(e,n){const s={type:"root",children:e.wrap(e.all(n))};return e.patch(n,s),e.applyData(n,s)}function iM(e,n){const s={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function aM(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=ku(n.children[1]),d=pb(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 rM(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 oM(e,n){const s={type:"element",tagName:"td",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}const Ph=9,Rh=32;function lM(e){const n=String(e),s=/\r?\n|\r/g;let a=s.exec(n),r=0;const o=[];for(;a;)o.push(Ih(n.slice(r,a.index),r>0,!0),a[0]),r=a.index+a[0].length,a=s.exec(n);return o.push(Ih(n.slice(r),r>0,!1)),o.join("")}function Ih(e,n,s){let a=0,r=e.length;if(n){let o=e.codePointAt(a);for(;o===Ph||o===Rh;)a++,o=e.codePointAt(a)}if(s){let o=e.codePointAt(r-1);for(;o===Ph||o===Rh;)r--,o=e.codePointAt(r-1)}return r>a?e.slice(a,r):""}function cM(e,n){const s={type:"text",value:lM(String(n.value))};return e.patch(n,s),e.applyData(n,s)}function dM(e,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,s),e.applyData(n,s)}const uM={blockquote:F_,break:U_,code:B_,delete:H_,emphasis:q_,footnoteReference:V_,heading:W_,html:K_,imageReference:G_,image:J_,inlineCode:Y_,linkReference:Q_,link:X_,listItem:Z_,list:tM,paragraph:nM,root:sM,strong:iM,table:aM,tableCell:oM,tableRow:rM,text:cM,thematicBreak:dM,toml:Ho,yaml:Ho,definition:Ho,footnoteDefinition:Ho};function Ho(){}const Db=-1,ic=0,ro=1,Tl=2,Mu=3,Au=4,Pu=5,Ru=6,Lb=7,Ob=8,Th=typeof self=="object"?self:globalThis,mM=(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 ic:case Db:return s(l,r);case ro:{const c=s([],r);for(const d of l)c.push(a(d));return c}case Tl:{const c=s({},r);for(const[d,u]of l)c[a(d)]=a(u);return c}case Mu:return s(new Date(l),r);case Au:{const{source:c,flags:d}=l;return s(new RegExp(c,d),r)}case Pu:{const c=s(new Map,r);for(const[d,u]of l)c.set(a(d),a(u));return c}case Ru:{const c=s(new Set,r);for(const d of l)c.add(a(d));return c}case Lb:{const{name:c,message:d}=l;return s(new Th[c](d),r)}case Ob: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 Th[o](l),r)};return a},$h=e=>mM(new Map,e)(0),Ya="",{toString:hM}={},{keys:pM}=Object,Lr=e=>{const n=typeof e;if(n!=="object"||!e)return[ic,n];const s=hM.call(e).slice(8,-1);switch(s){case"Array":return[ro,Ya];case"Object":return[Tl,Ya];case"Date":return[Mu,Ya];case"RegExp":return[Au,Ya];case"Map":return[Pu,Ya];case"Set":return[Ru,Ya];case"DataView":return[ro,s]}return s.includes("Array")?[ro,s]:s.includes("Error")?[Lb,s]:[Tl,s]},qo=([e,n])=>e===ic&&(n==="function"||n==="symbol"),fM=(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]=Lr(l);switch(c){case ic:{let m=l;switch(d){case"bigint":c=Ob,m=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+d);m=null;break;case"undefined":return r([Db],l)}return r([c,m],l)}case ro:{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 Tl:{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 pM(l))(e||!qo(Lr(l[f])))&&m.push([o(f),o(l[f])]);return h}case Mu:return r([c,l.toISOString()],l);case Au:{const{source:m,flags:h}=l;return r([c,{source:m,flags:h}],l)}case Pu:{const m=[],h=r([c,m],l);for(const[f,p]of l)(e||!(qo(Lr(f))||qo(Lr(p))))&&m.push([o(f),o(p)]);return h}case Ru:{const m=[],h=r([c,m],l);for(const f of l)(e||!qo(Lr(f)))&&m.push(o(f));return h}}const{message:u}=l;return r([c,{name:d,message:u}],l)};return o},Dh=(e,{json:n,lossy:s}={})=>{const a=[];return fM(!(n||s),!!n,new Map,a)(e),a},$l=typeof structuredClone=="function"?(e,n)=>n&&("json"in n||"lossy"in n)?$h(Dh(e,n)):structuredClone(e):(e,n)=>$h(Dh(e,n));function gM(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 bM(e,n){return"Back to reference "+(e+1)+(n>1?"-"+n:"")}function xM(e){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=e.options.footnoteBackContent||gM,a=e.options.footnoteBackLabel||bM,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=Er(h.toLowerCase());let p=0;const g=[],x=e.footnoteCounts.get(h);for(;x!==void 0&&++p<=x;){g.length>0&&g.push({type:"text",value:" "});let y=typeof s=="string"?s:s(d,p);typeof y=="string"&&(y={type:"text",value:y}),g.push({type:"element",tagName:"a",properties:{href:"#"+n+"fnref-"+f+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof a=="string"?a:a(d,p),className:["data-footnote-backref"]},children:Array.isArray(y)?y:[y]})}const w=m[m.length-1];if(w&&w.type==="element"&&w.tagName==="p"){const y=w.children[w.children.length-1];y&&y.type==="text"?y.value+=" ":w.children.push({type:"text",value:" "}),w.children.push(...g)}else m.push(...g);const b={type:"element",tagName:"li",properties:{id:n+"fn-"+f},children:e.wrap(m,!0)};e.patch(u,b),c.push(b)}if(c.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...$l(l),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
|
|
659
|
+
`},{type:"element",tagName:"ol",properties:{},children:e.wrap(c,!0)},{type:"text",value:`
|
|
660
|
+
`}]}}const ac=(function(e){if(e==null)return kM;if(typeof e=="function")return rc(e);if(typeof e=="object")return Array.isArray(e)?vM(e):yM(e);if(typeof e=="string")return wM(e);throw new Error("Expected function, string, or object as test")});function vM(e){const n=[];let s=-1;for(;++s<e.length;)n[s]=ac(e[s]);return rc(a);function a(...r){let o=-1;for(;++o<n.length;)if(n[o].apply(this,r))return!0;return!1}}function yM(e){const n=e;return rc(s);function s(a){const r=a;let o;for(o in e)if(r[o]!==n[o])return!1;return!0}}function wM(e){return rc(n);function n(s){return s&&s.type===e}}function rc(e){return n;function n(s,a,r){return!!(jM(s)&&e.call(this,s,typeof a=="number"?a:void 0,r||void 0))}}function kM(){return!0}function jM(e){return e!==null&&typeof e=="object"&&"type"in e}const zb=[],NM=!0,qd=!1,SM="skip";function Fb(e,n,s,a){let r;typeof n=="function"&&typeof s!="function"?(a=s,s=n):r=n;const o=ac(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=zb,g,x,w;if((!n||o(d,u,m[m.length-1]||void 0))&&(p=CM(s(d,m)),p[0]===qd))return p;if("children"in d&&d.children){const b=d;if(b.children&&p[0]!==SM)for(x=(a?b.children.length:-1)+l,w=m.concat(b);x>-1&&x<b.children.length;){const y=b.children[x];if(g=c(y,x,w)(),g[0]===qd)return g;x=typeof g[1]=="number"?g[1]:x+l}}return p}}}function CM(e){return Array.isArray(e)?e:typeof e=="number"?[NM,e]:e==null?zb:[e]}function Iu(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),Fb(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 Vd={}.hasOwnProperty,EM={};function _M(e,n){const s=n||EM,a=new Map,r=new Map,o=new Map,l={...uM,...s.handlers},c={all:u,applyData:AM,definitionById:a,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:l,one:d,options:s,patch:MM,wrap:RM};return Iu(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(Vd.call(c.handlers,f)&&p)return p(c,m,h);if(c.options.passThrough&&c.options.passThrough.includes(f)){if("children"in m){const{children:x,...w}=m,b=$l(w);return b.children=c.all(m),b}return $l(m)}return(c.options.unknownHandler||PM)(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=Lh(g.value)),!Array.isArray(g)&&g.type==="element")){const x=g.children[0];x&&x.type==="text"&&(x.value=Lh(x.value))}Array.isArray(g)?h.push(...g):h.push(g)}}}return h}}function MM(e,n){e.position&&(n.position=bE(e))}function AM(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,$l(o)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function PM(e,n){const s=n.data||{},a="value"in n&&!(Vd.call(s,"hProperties")||Vd.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 RM(e,n){const s=[];let a=-1;for(n&&s.push({type:"text",value:`
|
|
661
|
+
`});++a<e.length;)a&&s.push({type:"text",value:`
|
|
662
|
+
`}),s.push(e[a]);return n&&e.length>0&&s.push({type:"text",value:`
|
|
663
|
+
`}),s}function Lh(e){let n=0,s=e.charCodeAt(n);for(;s===9||s===32;)n++,s=e.charCodeAt(n);return e.slice(n)}function Oh(e,n){const s=_M(e,n),a=s.one(e,void 0),r=xM(s),o=Array.isArray(a)?{type:"root",children:a}:a||{type:"root",children:[]};return r&&o.children.push({type:"text",value:`
|
|
664
|
+
`},r),o}function IM(e,n){return e&&"run"in e?async function(s,a){const r=Oh(s,{file:a,...n});await e.run(r,a)}:function(s,a){return Oh(s,{file:a,...e||n})}}function zh(e){if(e)throw e}var Ic,Fh;function TM(){if(Fh)return Ic;Fh=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 Ic=function d(){var u,m,h,f,p,g,x=arguments[0],w=1,b=arguments.length,y=!1;for(typeof x=="boolean"&&(y=x,x=arguments[1]||{},w=2),(x==null||typeof x!="object"&&typeof x!="function")&&(x={});w<b;++w)if(u=arguments[w],u!=null)for(m in u)h=c(x,m),f=c(u,m),x!==f&&(y&&f&&(o(f)||(p=r(f)))?(p?(p=!1,g=h&&r(h)?h:[]):g=h&&o(h)?h:{},l(x,{name:m,newValue:d(y,g,f)})):typeof f<"u"&&l(x,{name:m,newValue:f}));return x},Ic}var $M=TM();const Tc=ig($M);function Wd(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 DM(){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?LM(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 LM(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 Ni={basename:OM,dirname:zM,extname:FM,join:UM,sep:"/"};function OM(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');$o(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 zM(e){if($o(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 FM(e){$o(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 UM(...e){let n=-1,s;for(;++n<e.length;)$o(e[n]),e[n]&&(s=s===void 0?e[n]:s+"/"+e[n]);return s===void 0?".":BM(s)}function BM(e){$o(e);const n=e.codePointAt(0)===47;let s=HM(e,!n);return s.length===0&&!n&&(s="."),s.length>0&&e.codePointAt(e.length-1)===47&&(s+="/"),n?"/"+s:s}function HM(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 $o(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const qM={cwd:VM};function VM(){return"/"}function Kd(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function WM(e){if(typeof e=="string")e=new URL(e);else if(!Kd(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 KM(e)}function KM(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 $c=["history","path","basename","stem","extname","dirname"];class Ub{constructor(n){let s;n?Kd(n)?s={path:n}:typeof n=="string"||GM(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":qM.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let a=-1;for(;++a<$c.length;){const o=$c[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)$c.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?Ni.basename(this.path):void 0}set basename(n){Lc(n,"basename"),Dc(n,"basename"),this.path=Ni.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?Ni.dirname(this.path):void 0}set dirname(n){Uh(this.basename,"dirname"),this.path=Ni.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?Ni.extname(this.path):void 0}set extname(n){if(Dc(n,"extname"),Uh(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=Ni.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){Kd(n)&&(n=WM(n)),Lc(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?Ni.basename(this.path,this.extname):void 0}set stem(n){Lc(n,"stem"),Dc(n,"stem"),this.path=Ni.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 Rs(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 Dc(e,n){if(e&&e.includes(Ni.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+Ni.sep+"`")}function Lc(e,n){if(!e)throw new Error("`"+n+"` cannot be empty")}function Uh(e,n){if(!e)throw new Error("Setting `"+n+"` requires `path` to be set too")}function GM(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const JM=(function(e){const a=this.constructor.prototype,r=a[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,a),o}),YM={}.hasOwnProperty;class Tu extends JM{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=DM()}copy(){const n=new Tu;let s=-1;for(;++s<this.attachers.length;){const a=this.attachers[s];n.use(...a)}return n.data(Tc(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(Fc("data",this.frozen),this.namespace[n]=s,this):YM.call(this.namespace,n)&&this.namespace[n]||void 0:n?(Fc("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=Vo(n),a=this.parser||this.Parser;return Oc("parse",a),a(String(s),s)}process(n,s){const a=this;return this.freeze(),Oc("process",this.parser||this.Parser),zc("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(o,l){const c=Vo(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);ZM(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(),Oc("processSync",this.parser||this.Parser),zc("processSync",this.compiler||this.Compiler),this.process(n,r),Hh("processSync","process",s),a;function r(o,l){s=!0,zh(o),a=l}}run(n,s,a){Bh(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=Vo(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),Hh("runSync","run",a),r;function o(l,c){zh(l),r=c,a=!0}}stringify(n,s){this.freeze();const a=Vo(s),r=this.compiler||this.Compiler;return zc("stringify",r),Bh(n),r(n,a)}use(n,...s){const a=this.attachers,r=this.namespace;if(Fc("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=Tc(!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];Wd(x)&&Wd(p)&&(p=Tc(!0,x,p)),a[f]=[u,p,...g]}}}}const QM=new Tu().freeze();function Oc(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function zc(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Fc(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 Bh(e){if(!Wd(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Hh(e,n,s){if(!s)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function Vo(e){return XM(e)?e:new Ub(e)}function XM(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function ZM(e){return typeof e=="string"||eA(e)}function eA(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const tA="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",qh=[],Vh={allowDangerousHtml:!0},nA=/^(https?|ircs?|mailto|xmpp)$/i,sA=[{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 bi(e){const n=iA(e),s=aA(e);return rA(n.runSync(n.parse(s),s),e)}function iA(e){const n=e.rehypePlugins||qh,s=e.remarkPlugins||qh,a=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Vh}:Vh;return QM().use(z_).use(s).use(IM,a).use(n)}function aA(e){const n=e.children||"",s=new Ub;return typeof n=="string"&&(s.value=n),s}function rA(e,n){const s=n.allowedElements,a=n.allowElement,r=n.components,o=n.disallowedElements,l=n.skipHtml,c=n.unwrapDisallowed,d=n.urlTransform||oA;for(const m of sA)Object.hasOwn(n,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+tA+m.id,void 0);return Iu(e,u),kE(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 Ac)if(Object.hasOwn(Ac,p)&&Object.hasOwn(m.properties,p)){const g=m.properties[p],x=Ac[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 oA(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||nA.test(e.slice(0,n))?e:""}function Wh(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 lA(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function cA(e,n,s){const r=ac((s||{}).ignore||[]),o=dA(n);let l=-1;for(;++l<o.length;)Fb(e,"text",c);function c(u,m){let h=-1,f;for(;++h<m.length;){const p=m[h],g=f?f.children:void 0;if(r(p,g?g.indexOf(p):void 0,f))return;f=p}if(f)return d(u,m)}function d(u,m){const h=m[m.length-1],f=o[l][0],p=o[l][1];let g=0;const w=h.children.indexOf(u);let b=!1,y=[];f.lastIndex=0;let S=f.exec(u.value);for(;S;){const k=S.index,C={index:S.index,input:S.input,stack:[...m,u]};let v=p(...S,C);if(typeof v=="string"&&(v=v.length>0?{type:"text",value:v}:void 0),v===!1?f.lastIndex=k+1:(g!==k&&y.push({type:"text",value:u.value.slice(g,k)}),Array.isArray(v)?y.push(...v):v&&y.push(v),g=k+S[0].length,b=!0),!f.global)break;S=f.exec(u.value)}return b?(g<u.value.length&&y.push({type:"text",value:u.value.slice(g)}),h.children.splice(w,1,...y)):y=[u],w+y.length}}function dA(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([uA(r[0]),mA(r[1])])}return n}function uA(e){return typeof e=="string"?new RegExp(lA(e),"g"):e}function mA(e){return typeof e=="function"?e:function(){return e}}const Uc="phrasing",Bc=["autolink","link","image","label"];function hA(){return{transforms:[yA],enter:{literalAutolink:fA,literalAutolinkEmail:Hc,literalAutolinkHttp:Hc,literalAutolinkWww:Hc},exit:{literalAutolink:vA,literalAutolinkEmail:xA,literalAutolinkHttp:gA,literalAutolinkWww:bA}}}function pA(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Uc,notInConstruct:Bc},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Uc,notInConstruct:Bc},{character:":",before:"[ps]",after:"\\/",inConstruct:Uc,notInConstruct:Bc}]}}function fA(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Hc(e){this.config.enter.autolinkProtocol.call(this,e)}function gA(e){this.config.exit.autolinkProtocol.call(this,e)}function bA(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 xA(e){this.config.exit.autolinkEmail.call(this,e)}function vA(e){this.exit(e)}function yA(e){cA(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,wA],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,kA]],{ignore:["link","linkReference"]})}function wA(e,n,s,a,r){let o="";if(!Bb(r)||(/^w/i.test(n)&&(s=n+s,n="",o="http://"),!jA(s)))return!1;const l=NA(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 kA(e,n,s,a){return!Bb(a,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function jA(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 NA(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=Wh(e,"(");let o=Wh(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 Bb(e,n){const s=e.input.charCodeAt(e.index-1);return(e.index===0||_a(s)||nc(s))&&(!n||s!==47)}Hb.peek=IA;function SA(){this.buffer()}function CA(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function EA(){this.buffer()}function _A(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function MA(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=fi(this.sliceSerialize(e)).toLowerCase(),s.label=n}function AA(e){this.exit(e)}function PA(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=fi(this.sliceSerialize(e)).toLowerCase(),s.label=n}function RA(e){this.exit(e)}function IA(){return"["}function Hb(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 TA(){return{enter:{gfmFootnoteCallString:SA,gfmFootnoteCall:CA,gfmFootnoteDefinitionLabelString:EA,gfmFootnoteDefinition:_A},exit:{gfmFootnoteCallString:MA,gfmFootnoteCall:AA,gfmFootnoteDefinitionLabelString:PA,gfmFootnoteDefinition:RA}}}function $A(e){let n=!1;return e&&e.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:Hb},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function s(a,r,o,l){const c=o.createTracker(l);let d=c.move("[^");const u=o.enter("footnoteDefinition"),m=o.enter("label");return d+=c.move(o.safe(o.associationId(a),{before:d,after:"]"})),m(),d+=c.move("]:"),a.children&&a.children.length>0&&(c.shift(4),d+=c.move((n?`
|
|
665
|
+
`:" ")+o.indentLines(o.containerFlow(a,c.current()),n?qb:DA))),u(),d}}function DA(e,n,s){return n===0?e:qb(e,n,s)}function qb(e,n,s){return(s?"":" ")+e}const LA=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Vb.peek=BA;function OA(){return{canContainEols:["delete"],enter:{strikethrough:FA},exit:{strikethrough:UA}}}function zA(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:LA}],handlers:{delete:Vb}}}function FA(e){this.enter({type:"delete",children:[]},e)}function UA(e){this.exit(e)}function Vb(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 BA(){return"~"}function HA(e){return e.length}function qA(e,n){const s=n||{},a=(s.align||[]).concat(),r=s.stringLength||HA,o=[],l=[],c=[],d=[];let u=0,m=-1;for(;++m<e.length;){const x=[],w=[];let b=-1;for(e[m].length>u&&(u=e[m].length);++b<e[m].length;){const y=VA(e[m][b]);if(s.alignDelimiters!==!1){const S=r(y);w[b]=S,(d[b]===void 0||S>d[b])&&(d[b]=S)}x.push(y)}l[m]=x,c[m]=w}let h=-1;if(typeof a=="object"&&"length"in a)for(;++h<u;)o[h]=Kh(a[h]);else{const x=Kh(a);for(;++h<u;)o[h]=x}h=-1;const f=[],p=[];for(;++h<u;){const x=o[h];let w="",b="";x===99?(w=":",b=":"):x===108?w=":":x===114&&(b=":");let y=s.alignDelimiters===!1?1:Math.max(1,d[h]-w.length-b.length);const S=w+"-".repeat(y)+b;s.alignDelimiters!==!1&&(y=w.length+y+b.length,y>d[h]&&(d[h]=y),p[h]=y),f[h]=S}l.splice(1,0,f),c.splice(1,0,p),m=-1;const g=[];for(;++m<l.length;){const x=l[m],w=c[m];h=-1;const b=[];for(;++h<u;){const y=x[h]||"";let S="",k="";if(s.alignDelimiters!==!1){const C=d[h]-(w[h]||0),v=o[h];v===114?S=" ".repeat(C):v===99?C%2?(S=" ".repeat(C/2+.5),k=" ".repeat(C/2-.5)):(S=" ".repeat(C/2),k=S):k=" ".repeat(C)}s.delimiterStart!==!1&&!h&&b.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&y==="")&&(s.delimiterStart!==!1||h)&&b.push(" "),s.alignDelimiters!==!1&&b.push(S),b.push(y),s.alignDelimiters!==!1&&b.push(k),s.padding!==!1&&b.push(" "),(s.delimiterEnd!==!1||h!==u-1)&&b.push("|")}g.push(s.delimiterEnd===!1?b.join("").replace(/ +$/,""):b.join(""))}return g.join(`
|
|
666
|
+
`)}function VA(e){return e==null?"":String(e)}function Kh(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 WA(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()),KA);return r(),l}function KA(e,n,s){return">"+(s?"":" ")+e}function GA(e,n){return Gh(e,n.inConstruct,!0)&&!Gh(e,n.notInConstruct,!1)}function Gh(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 Jh(e,n,s,a){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
|
|
667
|
+
`&&GA(s.stack,s.unsafe[r]))return/[ \t]/.test(a.before)?"":" ";return`\\
|
|
668
|
+
`}function JA(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 YA(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 QA(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 XA(e,n,s,a){const r=QA(s),o=e.value||"",l=r==="`"?"GraveAccent":"Tilde";if(YA(e,s)){const h=s.enter("codeIndented"),f=s.indentLines(o,ZA);return h(),f}const c=s.createTracker(a),d=r.repeat(Math.max(JA(o,r)+1,3)),u=s.enter("codeFenced");let m=c.move(d);if(e.lang){const h=s.enter(`codeFencedLang${l}`);m+=c.move(s.safe(e.lang,{before:m,after:" ",encode:["`"],...c.current()})),h()}if(e.lang&&e.meta){const h=s.enter(`codeFencedMeta${l}`);m+=c.move(" "),m+=c.move(s.safe(e.meta,{before:m,after:`
|
|
669
|
+
`,encode:["`"],...c.current()})),h()}return m+=c.move(`
|
|
670
|
+
`),o&&(m+=c.move(o+`
|
|
671
|
+
`)),m+=c.move(d),u(),m}function ZA(e,n,s){return(s?"":" ")+e}function $u(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 eP(e,n,s,a){const r=$u(s),o=r==='"'?"Quote":"Apostrophe",l=s.enter("definition");let c=s.enter("label");const d=s.createTracker(a);let u=d.move("[");return u+=d.move(s.safe(s.associationId(e),{before:u,after:"]",...d.current()})),u+=d.move("]: "),c(),!e.url||/[\0- \u007F]/.test(e.url)?(c=s.enter("destinationLiteral"),u+=d.move("<"),u+=d.move(s.safe(e.url,{before:u,after:">",...d.current()})),u+=d.move(">")):(c=s.enter("destinationRaw"),u+=d.move(s.safe(e.url,{before:u,after:e.title?" ":`
|
|
672
|
+
`,...d.current()}))),c(),e.title&&(c=s.enter(`title${o}`),u+=d.move(" "+r),u+=d.move(s.safe(e.title,{before:u,after:r,...d.current()})),u+=d.move(r),c()),l(),u}function tP(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 fo(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Dl(e,n,s){const a=fr(e),r=fr(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}}Wb.peek=nP;function Wb(e,n,s,a){const r=tP(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=Dl(a.before.charCodeAt(a.before.length-1),u,r);m.inside&&(d=fo(u)+d.slice(1));const h=d.charCodeAt(d.length-1),f=Dl(a.after.charCodeAt(0),h,r);f.inside&&(d=d.slice(0,-1)+fo(h));const p=l.move(r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+d+p}function nP(e,n,s){return s.options.emphasis||"*"}function sP(e,n){let s=!1;return Iu(e,function(a){if("value"in a&&/\r?\n|\r/.test(a.value)||a.type==="break")return s=!0,qd}),!!((!e.depth||e.depth<3)&&Cu(e)&&(n.options.setext||s))}function iP(e,n,s,a){const r=Math.max(Math.min(6,e.depth||1),1),o=s.createTracker(a);if(sP(e,s)){const m=s.enter("headingSetext"),h=s.enter("phrasing"),f=s.containerPhrasing(e,{...o.current(),before:`
|
|
673
|
+
`,after:`
|
|
674
|
+
`});return h(),m(),f+`
|
|
675
|
+
`+(r===1?"=":"-").repeat(f.length-(Math.max(f.lastIndexOf("\r"),f.lastIndexOf(`
|
|
676
|
+
`))+1))}const l="#".repeat(r),c=s.enter("headingAtx"),d=s.enter("phrasing");o.move(l+" ");let u=s.containerPhrasing(e,{before:"# ",after:`
|
|
677
|
+
`,...o.current()});return/^[\t ]/.test(u)&&(u=fo(u.charCodeAt(0))+u.slice(1)),u=u?l+" "+u:l,s.options.closeAtx&&(u+=" "+l),d(),c(),u}Kb.peek=aP;function Kb(e){return e.value||""}function aP(){return"<"}Gb.peek=rP;function Gb(e,n,s,a){const r=$u(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 rP(){return"!"}Jb.peek=oP;function Jb(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 oP(){return"!"}Yb.peek=lP;function Yb(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 lP(){return"`"}function Qb(e,n){const s=Cu(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))}Xb.peek=cP;function Xb(e,n,s,a){const r=$u(s),o=r==='"'?"Quote":"Apostrophe",l=s.createTracker(a);let c,d;if(Qb(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 cP(e,n,s){return Qb(e,s)?"<":"["}Zb.peek=dP;function Zb(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 dP(){return"["}function Du(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 uP(e){const n=Du(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 mP(e){const n=e.options.bulletOrdered||".";if(n!=="."&&n!==")")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOrdered`, expected `.` or `)`");return n}function ex(e){const n=e.options.rule||"*";if(n!=="*"&&n!=="-"&&n!=="_")throw new Error("Cannot serialize rules with `"+n+"` for `options.rule`, expected `*`, `-`, or `_`");return n}function hP(e,n,s,a){const r=s.enter("list"),o=s.bulletCurrent;let l=e.ordered?mP(s):Du(s);const c=e.ordered?l==="."?")":".":uP(s);let d=n&&s.bulletLastUsed?l===s.bulletLastUsed:!1;if(!e.ordered){const m=e.children?e.children[0]:void 0;if((l==="*"||l==="-")&&m&&(!m.children||!m.children[0])&&s.stack[s.stack.length-1]==="list"&&s.stack[s.stack.length-2]==="listItem"&&s.stack[s.stack.length-3]==="list"&&s.stack[s.stack.length-4]==="listItem"&&s.indexStack[s.indexStack.length-1]===0&&s.indexStack[s.indexStack.length-2]===0&&s.indexStack[s.indexStack.length-3]===0&&(d=!0),ex(s)===l&&m){let h=-1;for(;++h<e.children.length;){const f=e.children[h];if(f&&f.type==="listItem"&&f.children&&f.children[0]&&f.children[0].type==="thematicBreak"){d=!0;break}}}}d&&(l=c),s.bulletCurrent=l;const u=s.containerFlow(e,a);return s.bulletLastUsed=l,s.bulletCurrent=o,r(),u}function pP(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 fP(e,n,s,a){const r=pP(s);let o=s.bulletCurrent||Du(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 gP(e,n,s,a){const r=s.enter("paragraph"),o=s.enter("phrasing"),l=s.containerPhrasing(e,a);return o(),r(),l}const bP=ac(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function xP(e,n,s,a){return(e.children.some(function(l){return bP(l)})?s.containerPhrasing:s.containerFlow).call(s,e,a)}function vP(e){const n=e.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}tx.peek=yP;function tx(e,n,s,a){const r=vP(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=Dl(a.before.charCodeAt(a.before.length-1),u,r);m.inside&&(d=fo(u)+d.slice(1));const h=d.charCodeAt(d.length-1),f=Dl(a.after.charCodeAt(0),h,r);f.inside&&(d=d.slice(0,-1)+fo(h));const p=l.move(r+r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+d+p}function yP(e,n,s){return s.options.strong||"*"}function wP(e,n,s,a){return s.safe(e.value,a)}function kP(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 jP(e,n,s){const a=(ex(s)+(s.options.ruleSpaces?" ":"")).repeat(kP(s));return s.options.ruleSpaces?a.slice(0,-1):a}const nx={blockquote:WA,break:Jh,code:XA,definition:eP,emphasis:Wb,hardBreak:Jh,heading:iP,html:Kb,image:Gb,imageReference:Jb,inlineCode:Yb,link:Xb,linkReference:Zb,list:hP,listItem:fP,paragraph:gP,root:xP,strong:tx,text:wP,thematicBreak:jP};function NP(){return{enter:{table:SP,tableData:Yh,tableHeader:Yh,tableRow:EP},exit:{codeText:_P,table:CP,tableData:qc,tableHeader:qc,tableRow:qc}}}function SP(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 CP(e){this.exit(e),this.data.inTable=void 0}function EP(e){this.enter({type:"tableRow",children:[]},e)}function qc(e){this.exit(e)}function Yh(e){this.enter({type:"tableCell",children:[]},e)}function _P(e){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,MP));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(e)}function MP(e,n){return n==="|"?n:e}function AP(e){const n=e||{},s=n.tableCellPadding,a=n.tablePipeAlign,r=n.stringLength,o=s?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
|
|
678
|
+
`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:f,table:l,tableCell:d,tableRow:c}};function l(p,g,x,w){return u(m(p,x,w),p.align)}function c(p,g,x,w){const b=h(p,x,w),y=u([b]);return y.slice(0,y.indexOf(`
|
|
679
|
+
`))}function d(p,g,x,w){const b=x.enter("tableCell"),y=x.enter("phrasing"),S=x.containerPhrasing(p,{...w,before:o,after:o});return y(),b(),S}function u(p,g){return qA(p,{align:g,alignDelimiters:a,padding:s,stringLength:r})}function m(p,g,x){const w=p.children;let b=-1;const y=[],S=g.enter("table");for(;++b<w.length;)y[b]=h(w[b],g,x);return S(),y}function h(p,g,x){const w=p.children;let b=-1;const y=[],S=g.enter("tableRow");for(;++b<w.length;)y[b]=d(w[b],p,g,x);return S(),y}function f(p,g,x){let w=nx.inlineCode(p,g,x);return x.stack.includes("tableCell")&&(w=w.replace(/\|/g,"\\$&")),w}}function PP(){return{exit:{taskListCheckValueChecked:Qh,taskListCheckValueUnchecked:Qh,paragraph:IP}}}function RP(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:TP}}}function Qh(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function IP(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 TP(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=nx.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 $P(){return[hA(),TA(),OA(),NP(),PP()]}function DP(e){return{extensions:[pA(),$A(e),zA(),AP(e),RP()]}}const LP={tokenize:HP,partial:!0},sx={tokenize:qP,partial:!0},ix={tokenize:VP,partial:!0},ax={tokenize:WP,partial:!0},OP={tokenize:KP,partial:!0},rx={name:"wwwAutolink",tokenize:UP,previous:lx},ox={name:"protocolAutolink",tokenize:BP,previous:cx},Vi={name:"emailAutolink",tokenize:FP,previous:dx},Pi={};function zP(){return{text:Pi}}let xa=48;for(;xa<123;)Pi[xa]=Vi,xa++,xa===58?xa=65:xa===91&&(xa=97);Pi[43]=Vi;Pi[45]=Vi;Pi[46]=Vi;Pi[95]=Vi;Pi[72]=[Vi,ox];Pi[104]=[Vi,ox];Pi[87]=[Vi,rx];Pi[119]=[Vi,rx];function FP(e,n,s){const a=this;let r,o;return l;function l(h){return!Gd(h)||!dx.call(a,a.previous)||Lu(a.events)?s(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(h))}function c(h){return Gd(h)?(e.consume(h),c):h===64?(e.consume(h),d):s(h)}function d(h){return h===46?e.check(OP,m,u)(h):h===45||h===95||As(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 UP(e,n,s){const a=this;return r;function r(l){return l!==87&&l!==119||!lx.call(a,a.previous)||Lu(a.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(LP,e.attempt(sx,e.attempt(ix,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function BP(e,n,s){const a=this;let r="",o=!1;return l;function l(h){return(h===72||h===104)&&cx.call(a,a.previous)&&!Lu(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||Il(h)||An(h)||_a(h)||nc(h)?s(h):e.attempt(sx,e.attempt(ix,m),s)(h)}function m(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(h)}}function HP(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 qP(e,n,s){let a,r,o;return l;function l(u){return u===46||u===95?e.check(ax,d,c)(u):u===null||An(u)||_a(u)||u!==45&&nc(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 VP(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(ax,n,o)(l):l===null||An(l)||_a(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&a++,e.consume(l),r}}function WP(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||An(c)||_a(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||An(c)||_a(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 KP(e,n,s){return a;function a(o){return e.consume(o),r}function r(o){return As(o)?s(o):n(o)}}function lx(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||An(e)}function cx(e){return!Ls(e)}function dx(e){return!(e===47||Gd(e))}function Gd(e){return e===43||e===45||e===46||e===95||As(e)}function Lu(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 GP={tokenize:nR,partial:!0};function JP(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:ZP,continuation:{tokenize:eR},exit:tR}},text:{91:{name:"gfmFootnoteCall",tokenize:XP},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:YP,resolveTo:QP}}}}function YP(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=fi(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 QP(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 XP(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||An(h))return s(h);if(h===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return r.includes(fi(a.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),n):s(h)}return An(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 ZP(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||An(g))return s(g);if(g===93){e.exit("chunkString");const x=e.exit("gfmFootnoteDefinitionLabelString");return o=fi(a.sliceSerialize(x)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return An(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),pn(e,p,"gfmFootnoteDefinitionWhitespace")):s(g)}function p(g){return n(g)}}function eR(e,n,s){return e.check(To,n,e.attempt(GP,n,s))}function tR(e){e.exit("gfmFootnoteDefinition")}function nR(e,n,s){const a=this;return pn(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 sR(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&&Gs(f,f.length,0,sc(p,l.slice(u+1,d),c)),Gs(f,f.length,0,[["exit",h,c],["enter",l[d][1],c],["exit",l[d][1],c],["exit",m,c]]),Gs(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=fr(u);if(g===126)return h>1?d(g):(l.consume(g),h++,p);if(h<2&&!s)return d(g);const w=l.exit("strikethroughSequenceTemporary"),b=fr(g);return w._open=!b||b===2&&!!x,w._close=!x||x===2&&!!b,c(g)}}}class iR{constructor(){this.map=[]}add(n,s,a){aR(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 aR(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 rR(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 oR(){return{flow:{null:{name:"table",tokenize:lR,resolveAll:cR}}}}function lR(e,n,s){const a=this;let r=0,o=0,l;return c;function c(E){let R=a.events.length-1;for(;R>-1;){const M=a.events[R][1].type;if(M==="lineEnding"||M==="linePrefix")R--;else break}const L=R>-1?a.events[R][1].type:null,F=L==="tableHead"||L==="tableRow"?v:d;return F===v&&a.parser.lazy[a.now().line]?s(E):F(E)}function d(E){return e.enter("tableHead"),e.enter("tableRow"),u(E)}function u(E){return E===124||(l=!0,o+=1),m(E)}function m(E){return E===null?s(E):Wt(E)?o>1?(o=0,a.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(E),e.exit("lineEnding"),p):s(E):mn(E)?pn(e,m,"whitespace")(E):(o+=1,l&&(l=!1,r+=1),E===124?(e.enter("tableCellDivider"),e.consume(E),e.exit("tableCellDivider"),l=!0,m):(e.enter("data"),h(E)))}function h(E){return E===null||E===124||An(E)?(e.exit("data"),m(E)):(e.consume(E),E===92?f:h)}function f(E){return E===92||E===124?(e.consume(E),h):h(E)}function p(E){return a.interrupt=!1,a.parser.lazy[a.now().line]?s(E):(e.enter("tableDelimiterRow"),l=!1,mn(E)?pn(e,g,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(E):g(E))}function g(E){return E===45||E===58?w(E):E===124?(l=!0,e.enter("tableCellDivider"),e.consume(E),e.exit("tableCellDivider"),x):C(E)}function x(E){return mn(E)?pn(e,w,"whitespace")(E):w(E)}function w(E){return E===58?(o+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(E),e.exit("tableDelimiterMarker"),b):E===45?(o+=1,b(E)):E===null||Wt(E)?k(E):C(E)}function b(E){return E===45?(e.enter("tableDelimiterFiller"),y(E)):C(E)}function y(E){return E===45?(e.consume(E),y):E===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(E),e.exit("tableDelimiterMarker"),S):(e.exit("tableDelimiterFiller"),S(E))}function S(E){return mn(E)?pn(e,k,"whitespace")(E):k(E)}function k(E){return E===124?g(E):E===null||Wt(E)?!l||r!==o?C(E):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(E)):C(E)}function C(E){return s(E)}function v(E){return e.enter("tableRow"),j(E)}function j(E){return E===124?(e.enter("tableCellDivider"),e.consume(E),e.exit("tableCellDivider"),j):E===null||Wt(E)?(e.exit("tableRow"),n(E)):mn(E)?pn(e,j,"whitespace")(E):(e.enter("data"),P(E))}function P(E){return E===null||E===124||An(E)?(e.exit("data"),j(E)):(e.consume(E),E===92?U:P)}function U(E){return E===92||E===124?(e.consume(E),P):P(E)}}function cR(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 iR;for(;++s<e.length;){const p=e[s],g=p[1];p[0]==="enter"?g.type==="tableHead"?(c=!1,d!==0&&(Xh(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=Wo(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=Wo(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=Wo(f,n,o,r,s,h)):l[1]!==0&&(h=Wo(f,n,l,r,s,h)),r=0):r&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(l[3]=s)}for(d!==0&&Xh(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=rR(n.events,s))}return e}function Wo(e,n,s,a,r,o){const l=a===1?"tableHeader":a===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},sr(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const d=sr(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=sr(n.events,s[2]),m=sr(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({},sr(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function Xh(e,n,s,a,r){const o=[],l=sr(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 sr(e,n){const s=e[n],a=s[0]==="enter"?"start":"end";return s[1][a]}const dR={name:"tasklistCheck",tokenize:mR};function uR(){return{text:{91:dR}}}function mR(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 An(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 Wt(d)?n(d):mn(d)?e.check({tokenize:hR},n,s)(d):s(d)}}function hR(e,n,s){return pn(e,a,"whitespace");function a(r){return r===null?s(r):n(r)}}function pR(e){return wb([zP(),JP(),sR(e),oR(),uR()])}const fR={};function xi(e){const n=this,s=e||fR,a=n.data(),r=a.micromarkExtensions||(a.micromarkExtensions=[]),o=a.fromMarkdownExtensions||(a.fromMarkdownExtensions=[]),l=a.toMarkdownExtensions||(a.toMarkdownExtensions=[]);r.push(pR(s)),o.push($P()),l.push(DP(s))}const gR=45e3,bR=3e3,xR=2e3,vR=1500,Zh="fusion:sse-client-id";let Qa=null;const na=new Map;function ep(){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 ux(){if(!(typeof window>"u")){if(Qa)return Qa;try{const e=window.sessionStorage.getItem(Zh);if(e)return Qa=e,e;const n=ep();return window.sessionStorage.setItem(Zh,n),Qa=n,n}catch{return Qa=ep(),Qa}}}function mx(e){if(!(typeof window>"u"))try{return{parsed:new URL(e,window.location.origin),preserveRelativePath:e.startsWith("/")}}catch{return}}function hx(e){return e.origin===window.location.origin&&e.pathname==="/api/events"}function yR(e){const n=ux();if(!n)return e;const s=mx(e);return!s||!hx(s.parsed)?e:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function Ou(e,n){const s=ux();if(!s)return;const a=mx(e);if(!a||!hx(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),Mi(`${r.pathname}${r.search}${r.hash}`)}function wR(e){if(typeof window>"u")return;const n=Ou(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 oc(e){e.keepaliveTimer&&(clearInterval(e.keepaliveTimer),e.keepaliveTimer=null)}function tp(e){if(typeof window>"u"||typeof window.fetch!="function")return;const n=Ou(e.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,a=s?window.setTimeout(()=>s.abort(),vR):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{a!==null&&window.clearTimeout(a)})}function kR(e){oc(e),Ou(e.url,"keepalive")&&(tp(e),e.keepaliveTimer=window.setInterval(()=>{tp(e)},xR))}if(typeof window<"u"){const e=()=>{for(const s of Array.from(na.values()))if(!s.closed){if(oc(s),wR(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(na.values()))a.subscribers.size!==0&&(a.closed=!1,zu(a))};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("pageshow",n)}function Yr(e){e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),e.heartbeatTimer=setTimeout(()=>{px(e)},gR)}function px(e){if(e.heartbeatTimer&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=null),e.es&&(e.es.close(),e.es=null),oc(e),e.nativeListeners.clear(),e.closed||e.subscribers.size===0||e.reconnectTimer)return;const n=na.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=na.get(e.url);s&&s===e&&e.subscribers.size>0&&zu(e)},bR)}}function zu(e){if(e.es||e.closed)return;e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);const n=new EventSource(Mi(yR(e.url)));e.es=n,kR(e),n.addEventListener("open",()=>{Yr(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);px(e)}),n.addEventListener("message",()=>Yr(e)),n.addEventListener("heartbeat",()=>Yr(e)),fx(e),Yr(e)}function fx(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=>{Yr(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 jR(e){e.closed=!0,e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),oc(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.es&&e.es.close(),e.es=null,e.nativeListeners.clear(),na.delete(e.url)}function ii(e,n={}){let s=na.get(e);s||(s={url:e,es:null,subscribers:new Set,nativeListeners:new Map,heartbeatTimer:null,keepaliveTimer:null,reconnectTimer:null,hasOpenedOnce:!1,closed:!1},na.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;zu(s),fx(s),r&&queueMicrotask(()=>{s.subscribers.has(a)&&a.onOpen?.()});let o=!0;return()=>{if(!o)return;o=!1;const l=na.get(e);l&&(l.subscribers.delete(a),l.subscribers.size===0&&jR(l))}}const np=100;function gx(e,n,s){const[a,r]=i.useState([]),[o,l]=i.useState(!1),[c,d]=i.useState(!1),[u,m]=i.useState(null),[h,f]=i.useState(!1),p=i.useRef(null),g=i.useRef(!1),x=i.useRef(0),w=i.useRef(e),b=i.useRef(s),y=i.useRef(n),S=i.useRef(0);(w.current!==e||b.current!==s||y.current!==n)&&(w.current=e,b.current=s,y.current=n,x.current++,g.current=!0,r([]),l(!1),d(!1),m(null),f(!1),p.current&&(p.current(),p.current=null)),i.useEffect(()=>{if(!e||!n){p.current&&(p.current(),p.current=null);return}const j=x.current,P=++S.current;g.current=!1;const U=e,E=s;async function R(){if(!U)return;l(!0),f(!1);try{const F=await sm(U,E,{limit:np});if(g.current||x.current!==j||S.current!==P)return;r(F.entries),d(F.hasMore),m(F.total)}catch{if(g.current||x.current!==j||S.current!==P)return;r([]),d(!1),m(null)}finally{!g.current&&x.current===j&&S.current===P&&l(!1)}const L=E?`?projectId=${encodeURIComponent(E)}`:"";p.current=ii(`/api/tasks/${U}/logs/stream${L}`,{events:{"agent:log":F=>{if(!(g.current||x.current!==j))try{const M=JSON.parse(F.data);r(O=>[...O,M]),m(O=>O!==null?O+1:null)}catch{}}}})}return R(),()=>{g.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const C=i.useCallback(async()=>{if(!e||h)return;const j=x.current,P=a.length,U=e;f(!0);try{const E=await sm(U,s,{limit:np,offset:P});if(g.current||x.current!==j)return;r(R=>[...E.entries,...R]),d(E.hasMore),m(E.total)}catch{}finally{f(!1)}},[e,s,a.length,h]),v=i.useCallback(()=>r([]),[]);return{entries:a,loading:o,clear:v,loadMore:C,hasMore:c,total:u,loadingMore:h}}const sp="fn-agent-log-markdown",ip="fn-agent-log-tool-output";function ap(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 rp(e,n){if(!(typeof window>"u"))try{window.localStorage.setItem(e,n?"true":"false")}catch{}}function NR(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 op={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})},bx=50,SR={triage:"Plan"};function lp(e){return e.scrollHeight-(e.scrollTop+e.clientHeight)<=bx}function Jd(e){return[e.taskId,e.timestamp,e.agent??"",e.type,e.text,e.detail??""].join("|")}function CR(e){const n=new Map;return e.map(s=>{const a=Jd(s),r=n.get(a)??0;return n.set(a,r+1),`${a}|${r}`})}function xx(e){return e==="tool"||e==="tool_result"||e==="tool_error"}function Vc({detail:e}){const[n,s]=i.useState(!1),a=i.useId(),r=e.split(`
|
|
680
|
+
`).length,o=n?"Hide output":`Show output${r>1?` (${r} lines)`:""}`;return t.jsxs("div",{className:"agent-log-tool-detail-wrapper",children:[t.jsxs("button",{type:"button",className:"agent-log-tool-detail-toggle",onClick:()=>s(l=>!l),"aria-expanded":n,"aria-controls":a,"data-testid":"tool-detail-toggle",children:[n?t.jsx(rn,{size:14}):t.jsx(Mn,{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 ER(e,n){return e.agent?xx(e.type)?!0:!n||n.agent!==e.agent||n.type!==e.type:!1}function _R(e,n){const s=[];for(let a=0;a<e.length;a+=1){const{entry:r,hiddenToolBoundaryId:o}=e[a],l=n[a]??`${Jd(r)}|fallback`,c=a>0?e[a-1]:void 0,d=c?.entry,u=ER(r,d)||c!==void 0&&c.hiddenToolBoundaryId!==o;if(r.type==="text"||r.type==="thinking"){const m=[r];let h=a+1;for(;h<e.length;){const p=e[h],g=p.entry;if(g.type!==r.type||g.agent!==r.agent||p.hiddenToolBoundaryId!==o)break;m.push(g),h+=1}const f=n[h-1]??`${Jd(e[h-1].entry)}|fallback`;s.push({kind:r.type,entries:m,key:`${l}->${f}`,showBadge:u}),a=h-1;continue}s.push({kind:"single",entry:r,key:l,showBadge:u})}return s}function MR({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(()=>ap(sp,!0)),[w,b]=i.useState(()=>ap(ip,!0)),[y,S]=i.useState(!1),[k,C]=i.useState(!1),[v,j]=i.useState(!0);i.useEffect(()=>{rp(sp,g)},[g]),i.useEffect(()=>{rp(ip,w)},[w]);const P=i.useMemo(()=>{if(w)return e.map(I=>({entry:I,hiddenToolBoundaryId:0}));const K=[];let A=0;for(const I of e){if(xx(I.type)){A+=1;continue}K.push({entry:I,hiddenToolBoundaryId:A})}return K},[e,w]),U=i.useMemo(()=>P.map(K=>K.entry),[P]),E=i.useMemo(()=>CR(U),[U]),R=i.useMemo(()=>_R(P,E),[P,E]);i.useLayoutEffect(()=>{const K=u.current;if(!K)return;const A=e.length,I=m.current,$=h.current||K.scrollHeight,N=E[0]??null,G=E[E.length-1]??null,ge=f.current!==N,je=p.current!==G;if(A>I)if(I===0)K.scrollTop=K.scrollHeight;else{const ke=$-(K.scrollTop+K.clientHeight)<=bx,ne=je&&!ge,qe=ge&&!je;if(ne&&ke&&(K.scrollTop=K.scrollHeight),qe){const ee=K.scrollHeight-$;ee>0&&(K.scrollTop+=ee)}}m.current=A,h.current=K.scrollHeight,f.current=N,p.current=G,j(lp(K))},[e,E]);const L=i.useCallback(()=>{const K=u.current;K&&j(lp(K))},[]),F=i.useCallback(()=>{const K=u.current;K&&(K.scrollTop=K.scrollHeight,j(!0))},[]),M=i.useCallback(K=>{K.key==="Escape"&&y&&S(!1)},[y]);i.useEffect(()=>{if(y)return document.addEventListener("keydown",M),()=>{document.removeEventListener("keydown",M)}},[y,M]);const O=s?.provider&&s?.modelId,q=a?.provider&&a?.modelId,te=r?.provider&&r?.modelId,Z=i.useMemo(()=>{const K=[];return O&&K.push({role:"Executor",provider:s.provider,modelId:s.modelId}),q&&K.push({role:"Reviewer",provider:a.provider,modelId:a.modelId}),te&&K.push({role:"Planning",provider:r.provider,modelId:r.modelId}),K},[O,s,q,a,te,r]);return n&&e.length===0?t.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:t.jsx("div",{className:"agent-log-loading",children:"Loading agent logs…"})}):e.length===0?t.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:t.jsx("div",{className:"agent-log-empty",children:"No agent output yet."})}):t.jsxs("div",{className:`agent-log-viewer agent-log-viewer--streaming${y?" agent-log-viewer--fullscreen":""}`,"data-testid":"agent-log-viewer",children:[t.jsxs("div",{className:"agent-log-model-header","data-testid":"agent-log-model-header",children:[t.jsxs("div",{className:"agent-log-model-icons",children:[Z.map(K=>t.jsx(Sn,{provider:K.provider,size:"sm"},`${K.role}-${K.provider}-${K.modelId??"default"}`)),t.jsx("button",{className:"agent-log-model-expand-btn",onClick:()=>C(K=>!K),"aria-label":k?"Collapse model details":"Expand model details","aria-expanded":k,"aria-controls":"agent-log-model-details","data-testid":"agent-log-model-expand",children:k?t.jsx(rn,{size:14}):t.jsx(Mn,{size:14})})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>x(K=>!K),"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(K=>!K),"aria-label":w?"Hide tool output":"Show tool output","aria-pressed":w,"data-testid":"agent-log-tool-output-toggle",title:w?"Hide tool calls and results":"Show tool calls and results",children:w?"Tools: On":"Tools: Off"}),t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>S(K=>!K),"aria-label":y?"Exit full screen":"Expand agent log to full screen","data-testid":"agent-log-fullscreen-toggle",title:y?"Exit full screen":"Expand agent log to full screen",children:y?t.jsx(jo,{size:14}):t.jsx(Ql,{size:14})})]}),k&&t.jsxs("div",{id:"agent-log-model-details",className:"agent-log-model-details",children:[t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Executor:"}),O?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Sn,{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:"}),q?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Sn,{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:"}),te?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Sn,{provider:r.provider,size:"sm"}),t.jsxs("span",{children:[r.provider,"/",r.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]})]})]}),t.jsxs("div",{ref:u,className:"agent-log-viewer-scroll",onScroll:L,children:[d!==null&&t.jsxs("div",{className:"agent-log-summary","data-testid":"agent-log-summary",children:["Showing ",U.length," of ",d," entries",!w&&e.length!==U.length?` (${e.length-U.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(xt,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})}),R.map(K=>{const A=K.kind==="single"?K.entry:K.entries[0],I=K.showBadge?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:NR(A.timestamp)}):null,$=K.showBadge?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",SR[A.agent]??A.agent,"]"]}),I]}):null;if(K.kind==="single"){const{entry:G}=K;if(G.type==="tool")return t.jsxs("div",{className:"agent-log-tool",children:[$,t.jsxs("div",{className:"agent-log-tool-title",children:["⚡ ",G.text]}),G.detail?t.jsx(Vc,{detail:G.detail,type:"tool"}):null]},K.key);if(G.type==="tool_result")return t.jsxs("div",{className:"agent-log-tool-result",children:[$,t.jsxs("div",{className:"agent-log-tool-title",children:["✓ ",G.text]}),G.detail?t.jsx(Vc,{detail:G.detail,type:"tool_result"}):null]},K.key);if(G.type==="tool_error")return t.jsxs("div",{className:"agent-log-tool-error",children:[$,t.jsxs("div",{className:"agent-log-tool-title",children:["✗ ",G.text]}),G.detail?t.jsx(Vc,{detail:G.detail,type:"tool_error"}):null]},K.key)}const N=K.kind==="single"?A.text:K.entries.map(G=>G.text).join("");return K.kind==="thinking"?t.jsxs("div",{className:"agent-log-thinking",children:[$,g?t.jsx("div",{className:"markdown-body",children:t.jsx(bi,{remarkPlugins:[xi],components:op,children:N})}):t.jsx("pre",{className:"agent-log-plain-block",children:N})]},K.key):t.jsxs("div",{className:"agent-log-text",children:[$,g?t.jsx("div",{className:"markdown-body",children:t.jsx(bi,{remarkPlugins:[xi],components:op,children:N})}):t.jsx("pre",{className:"agent-log-plain-block",children:N})]},K.key)}),!v&&t.jsxs("button",{type:"button",className:"agent-log-return-to-live",onClick:F,"data-testid":"agent-log-return-to-live",children:[t.jsx(rn,{size:12}),t.jsx("span",{children:"Live"})]})]})]})}function gr(e){return e??void 0}function Ko(e){return{provider:gr(e.modelProvider),modelId:gr(e.modelId)}}function Go(e){return{provider:gr(e.validatorModelProvider),modelId:gr(e.validatorModelId)}}function Jo(e){return{provider:gr(e.planningModelProvider),modelId:gr(e.planningModelId)}}function AR(e,n){return Bg(e,n)}function PR(e,n){return Hg(e,n)}function RR(e,n){return qg(e,n)}function Wc(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 Kc(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function Gc(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function IR(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 TR({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(()=>Ko(e)),[w,b]=i.useState(()=>Ko(e)),[y,S]=i.useState(()=>Go(e)),[k,C]=i.useState(()=>Go(e)),[v,j]=i.useState(()=>Jo(e)),[P,U]=i.useState(()=>Jo(e)),[E,R]=i.useState(()=>e.thinkingLevel??null),[L,F]=i.useState(()=>e.thinkingLevel??null),[M,O]=i.useState(null),q=i.useRef(e.id);i.useEffect(()=>{h(!0),p(null),Os().then(J=>{o(J.models),c(J.favoriteProviders),u(J.favoriteModels)}).catch(J=>{p(J.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const te=i.useCallback(async J=>{const B=l,Ne=B.includes(J)?B.filter(H=>H!==J):[J,...B];c(Ne);try{await kn({favoriteProviders:Ne,favoriteModels:d})}catch{c(B),n("Failed to update favorites","error")}},[l,d,n]),Z=i.useCallback(async J=>{const B=d,Ne=B.includes(J)?B.filter(H=>H!==J):[J,...B];u(Ne);try{await kn({favoriteProviders:l,favoriteModels:Ne})}catch{u(B),n("Failed to update model favorites","error")}},[d,l,n]);i.useEffect(()=>{q.current=e.id;const J=Ko(e),B=Go(e),ve=Jo(e);x(J),b(J),S(B),C(B),j(ve),U(ve);const Ne=e.thinkingLevel??null;R(Ne),F(Ne),O(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const K=i.useMemo(()=>Kc(g),[g]),A=i.useMemo(()=>Kc(y),[y]),I=i.useMemo(()=>Kc(v),[v]),$=i.useMemo(()=>AR(e,a),[e,a]),N=i.useMemo(()=>PR(e,a),[e,a]),G=i.useMemo(()=>RR(e,a),[e,a]),ge=M!==null,je=i.useCallback(async(J,B)=>{const ve=e.id,Ne=w,H=k,be=P;O(J);try{const ce=s?J==="executor"?{modelProvider:B.provider??null,modelId:B.modelId??null}:J==="validator"?{validatorModelProvider:B.provider??null,validatorModelId:B.modelId??null}:{planningModelProvider:B.provider??null,planningModelId:B.modelId??null}:{modelProvider:(J==="executor"?B:w).provider??null,modelId:(J==="executor"?B:w).modelId??null,validatorModelProvider:(J==="validator"?B:k).provider??null,validatorModelId:(J==="validator"?B:k).modelId??null,planningModelProvider:(J==="planning"?B:P).provider??null,planningModelId:(J==="planning"?B:P).modelId??null},Me=await mi(ve,ce);if(q.current!==ve)return;const Le=Ko(Me),He=Go(Me),gt=Jo(Me);b(Le),x(Le),C(He),S(He),U(gt),j(gt),s?.(Me),n(IR(J,{executor:Le,validator:He,planning:gt}[J]),"success")}catch(ce){if(q.current!==ve)return;J==="executor"?x(Ne):J==="validator"?S(H):j(be),n(Re(ce)||"Failed to save model settings","error")}finally{q.current===ve&&O(null)}},[e.id,w,k,P,n,s]),ke=i.useCallback(J=>{const B=Wc(J);x(B),!Gc(B,w)&&je("executor",B)},[w,je]),ne=i.useCallback(J=>{const B=Wc(J);S(B),!Gc(B,k)&&je("validator",B)},[k,je]),qe=i.useCallback(J=>{const B=Wc(J);j(B),!Gc(B,P)&&je("planning",B)},[P,je]),ee=i.useCallback(async J=>{const B=e.id,ve=L,Ne=J===""?null:J;R(Ne),O("thinking");try{const H=await mi(B,{thinkingLevel:Ne});if(q.current!==B)return;const be=H.thinkingLevel??null;F(be),R(be),s?.(H);const ce=a?.defaultThinkingLevel??"off";n(be===null?`Thinking level set to default (${ce})`:`Thinking level set to ${be}`,"success")}catch(H){if(q.current!==B)return;R(ve),n(Re(H)||"Failed to save thinking level","error")}finally{q.current===B&&O(null)}},[e.id,L,a,n,s]),le=!w.provider&&!w.modelId,se=!k.provider&&!k.modelId,re=!P.provider&&!P.modelId;return t.jsxs("div",{className:"model-selector-tab",children:[t.jsx("h4",{children:"Model Configuration"}),t.jsx("p",{className:"model-selector-intro",children:"Override the AI models used for this task. When not specified, project or global defaults are used."}),m?t.jsx("div",{className:"model-selector-loading",children:"Loading available models…"}):f?t.jsxs("div",{className:"model-selector-error",children:["Error loading models: ",f,t.jsx("button",{className:"btn btn-sm",onClick:()=>{h(!0),p(null),Os().then(J=>{o(J.models),c(J.favoriteProviders),u(J.favoriteModels)}).catch(J=>p(J.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:le?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",$.provider&&$.modelId?` (${$.provider}/${$.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[w.provider&&t.jsx(Sn,{provider:w.provider,size:"sm"}),w.provider,"/",w.modelId]})}),t.jsx(ys,{id:"executorModel",label:"Executor Model",value:K,onChange:ke,models:r,disabled:ge,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:te,favoriteModels:d,onToggleModelFavorite:Z}),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:se?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",N.provider&&N.modelId?` (${N.provider}/${N.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[k.provider&&t.jsx(Sn,{provider:k.provider,size:"sm"}),k.provider,"/",k.modelId]})}),t.jsx(ys,{id:"validatorModel",label:"Reviewer Model",value:A,onChange:ne,models:r,disabled:ge,placeholder:"Select reviewer model…",favoriteProviders:l,onToggleFavorite:te,favoriteModels:d,onToggleModelFavorite:Z}),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:re?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",G.provider&&G.modelId?` (${G.provider}/${G.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[P.provider&&t.jsx(Sn,{provider:P.provider,size:"sm"}),P.provider,"/",P.modelId]})}),t.jsx(ys,{id:"planningModel",label:"Planning Model",value:I,onChange:qe,models:r,disabled:ge,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:te,favoriteModels:d,onToggleModelFavorite:Z}),t.jsx("small",{children:"The AI model used for task specification (triage phase)."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"thinkingLevel",children:"Thinking Level"}),t.jsx("div",{className:"model-selector-current",children:L===null?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default (",a?.defaultThinkingLevel??"off",")"]}):t.jsx("span",{className:"model-badge model-badge-custom",children:L})}),t.jsxs("select",{id:"thinkingLevel",value:E??"",onChange:J=>ee(J.target.value),disabled:ge,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:le&&se&&re&&L===null?"Using project or global default models.":"Model settings are up to date."})]})]})}const $R={open:t.jsx(Vl,{size:16}),closed:t.jsx(wo,{size:16}),merged:t.jsx(hg,{size:16})};function DR({taskId:e,projectId:n,prInfo:s,automationStatus:a,autoMerge:r=!1,isManualPrFlow:o=!1,prAuthAvailable:l,onPrCreated:c,onPrUpdated:d,addToast:u}){const[m,h]=i.useState(!1),[f,p]=i.useState(""),[g,x]=i.useState(""),[w,b]=i.useState(!1),[y,S]=i.useState(!1),[k,C]=i.useState(null),v=i.useCallback(async()=>{if(f.trim()){b(!0);try{const E=await Lj(e,{title:f.trim(),body:g.trim()||void 0},n);c(E),h(!1),p(""),x(""),u(`Created PR #${E.number}`,"success")}catch(E){u(Re(E)||"Failed to create PR","error")}finally{b(!1)}}},[e,f,g,n,c,u]),j=i.useCallback(async()=>{if(s){S(!0);try{const E=await Oj(e,n);C(E),d(E.prInfo),u("PR status refreshed","success")}catch(E){u(Re(E)||"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(Ws,{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(Ws,{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(Ws,{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:E=>p(E.target.value),disabled:w,className:"pr-input"}),t.jsx("textarea",{placeholder:"PR description (optional)",value:g,onChange:E=>x(E.target.value),disabled:w,className:"pr-textarea",rows:3}),t.jsxs("div",{className:"pr-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>h(!1),disabled:w,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:v,disabled:!f.trim()||w,children:w?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Ws,{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(bn,{size:14,className:"pr-section-icon--sm"}),"Create PR"]}),o&&t.jsx("div",{className:"pr-hint pr-hint--subtle",children:"Use the footer action to run PR-first completion for this task."}),!l&&t.jsxs("div",{className:"pr-hint pr-hint--subtle",children:["Run ",t.jsx("code",{children:"gh auth login"})," to enable PR creation."]})]});const P=$R[s.status]??t.jsx(Vl,{size:16}),U=k?.blockingReasons??[];return t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Ws,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsxs("div",{className:`pr-card pr-card--status-${s.status}`,children:[t.jsxs("div",{className:"pr-header",children:[t.jsx("span",{className:"pr-status-icon",children:P}),t.jsx("span",{className:`pr-status-badge pr-status-badge--${s.status}`,children:s.status}),t.jsxs("span",{className:"pr-number",children:["#",s.number]}),t.jsx("div",{className:"pr-spacer"}),t.jsx("button",{className:"btn btn-sm pr-refresh-btn",onClick:j,disabled:y,title:"Refresh PR status",children:t.jsx(rs,{size:14,style:{verticalAlign:"middle",opacity:y?.5:1}})})]}),t.jsx("div",{className:"pr-title",children:s.title}),t.jsxs("div",{className:"pr-meta",children:[t.jsx("span",{children:s.headBranch}),t.jsx("span",{className:"pr-meta-arrow",children:"→"}),t.jsx("span",{children:s.baseBranch})]}),a==="merging-pr"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:"fn is merging this pull request automatically."}),a==="awaiting-pr-checks"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:U.length>0?`Waiting for: ${U.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(Ui,{size:14}),s.commentCount]}),t.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[t.jsx(dg,{size:14}),"View on GitHub"]})]})]})]})}const cp=2e3;function LR(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function OR(e){return e==="agent"||e==="system"}function zR({task:e,onTaskUpdated:n,addToast:s,currentAuthor:a="user",projectId:r}){const[o,l]=i.useState(""),[c,d]=i.useState(null),[u,m]=i.useState(""),[h,f]=i.useState(!1),[p,g]=i.useState(null),x=i.useMemo(()=>[...e.comments||[]].sort((j,P)=>new Date(P.createdAt).getTime()-new Date(j.createdAt).getTime()),[e.comments]),w=o.length>cp;async function b(){const j=o.trim();if(j){f(!0);try{const P=await sj(e.id,j,r);l(""),n?.(P),s("Comment added","success")}catch(P){s(Re(P)||"Failed to add comment","error")}finally{f(!1)}}}async function y(j){const P=u.trim();if(P){f(!0);try{const U=await Xk(e.id,j,P,r);d(null),m(""),n?.(U),s("Comment updated","success")}catch(U){s(Re(U)||"Failed to update comment","error")}finally{f(!1)}}}async function S(j){g(j);try{const P=await Zk(e.id,j,r);n?.(P),s("Comment deleted","success")}catch(P){s(Re(P)||"Failed to delete comment","error")}finally{g(null)}}function k(j){j.key==="Enter"&&(j.ctrlKey||j.metaKey)&&(j.preventDefault(),b())}return t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Comments"}),x.length===0?t.jsx("div",{className:"detail-log-empty",children:"No comments yet."}):t.jsx("div",{className:"detail-activity-list",children:x.map(j=>{const P=j.author===a,U=c===j.id,E=OR(j.author);return t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header comments-header-row",children:[t.jsxs("div",{className:"comments-author-row",children:[E?t.jsx("span",{className:"ai-guidance-badge","data-testid":"ai-guidance-badge",children:"AI Guidance"}):t.jsx("strong",{children:j.author}),t.jsx("span",{className:"detail-log-timestamp",children:LR(j)})]}),P&&!U?t.jsxs("div",{className:"comments-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{d(j.id),m(j.text)},children:"Edit"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void S(j.id),disabled:p===j.id,children:p===j.id?"Deleting…":"Delete"})]}):null]}),U?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:u,onChange:R=>m(R.target.value),rows:3,className:"comments-textarea"}),t.jsxs("div",{className:"comments-edit-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{d(null),m("")},disabled:h,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void y(j.id),disabled:h||!u.trim(),children:"Save"})]})]}):t.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:j.text})]},j.id)})}),t.jsxs("div",{className:"comments-compose-form",children:[t.jsx("textarea",{value:o,onChange:j=>l(j.target.value),onKeyDown:k,rows:3,placeholder:"Add a comment",className:"comments-textarea"}),t.jsxs("div",{className:"comments-footer-row",children:[t.jsxs("span",{className:`comments-char-count${w?" comments-char-count--over":""}`,children:[o.length," / ",cp]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void b(),disabled:h||!o.trim()||w,children:h?"Posting…":"Add Comment"})]})]})]})}const dp="Failed to load review data.",FR="No reviewer feedback yet — this task has not produced reviewer-agent feedback in direct mode.";function Or(e){return e?new Date(e).toLocaleString():"Never"}function UR(e){return e==="manual"?"Manual":e==="auto"?"Background":"Initial load"}function BR(e){const n=new Map(e.addressing.map(o=>[o.itemId,o])),s=e.items.map(o=>{const l=n.get(o.id);return{id:o.id,summary:o.summary??o.body.slice(0,120),body:o.body,path:o.path,createdAt:o.createdAt,status:l?.status??"queued",addressing:l,item:o}}),a=new Set(s.map(o=>o.id)),r=e.addressing.filter(o=>!a.has(o.itemId)&&o.snapshot).map(o=>({id:o.itemId,summary:o.snapshot?.summary??o.itemId,body:o.snapshot?.body??o.snapshot?.summary??o.itemId,path:o.snapshot?.filePath,createdAt:o.selectedAt,status:o.status,addressing:o}));return[...s,...r]}function HR({task:e,projectId:n,onTaskUpdated:s,addToast:a}){const[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[m,h]=i.useState(!0),[f,p]=i.useState(null),[g,x]=i.useState(null),[w,b]=i.useState(e.reviewState??null),y=r.length>0&&!d,S=w?.source==="pull-request",k=i.useMemo(()=>w?BR(w):[],[w]);i.useEffect(()=>{let L=!1;return h(!0),p(null),iS(e.id,n).then(F=>{L||(b(F.reviewState),x(F.emptyMessage??null))}).catch(()=>{L||p(dp)}).finally(()=>{L||h(!1)}),()=>{L=!0}},[e.id,n]);const C=i.useMemo(()=>w?w.source==="pull-request"?`${w.summary?.reviewDecision??"REVIEW_REQUIRED"} · ${k.length} review item(s)`:`${w.summary?.summary??"reviewer-agent"} · ${k.length} review item(s)`:"No review feedback captured yet.",[w,k.length]),v=w?w.source==="pull-request"?w.summary?.reviewDecision:w.summary?.verdict:void 0,j=l?"refreshing":w?.refreshStatus??"ready",P=j==="error"?"status-dot status-dot--error":j==="refreshing"?"status-dot status-dot--pending":"status-dot status-dot--online",U=L=>o(F=>F.includes(L)?F.filter(M=>M!==L):[...F,L]),E=async()=>{try{p(null),c(!0);const L=await aS(e.id,n);if(b(L.reviewState),s?.({...e,reviewState:L.reviewState,prInfo:L.prInfo??e.prInfo}),L.reviewState.refreshStatus==="error"){const F=L.reviewState.refreshError??"Failed to refresh review data.";p(F),a(F,"error");return}a("Review refreshed","success")}catch(L){const F=L instanceof Error?L.message:dp;p(F),a(F,"error")}finally{c(!1)}},R=async()=>{try{if(!w)return;p(null),u(!0);const L=k.filter(M=>r.includes(M.id)).map(M=>{if(!M.item)return{id:M.id,source:w.source==="pull-request"?"pr-review":"reviewer-agent",threadId:M.addressing?.snapshot?.threadId,filePath:M.addressing?.snapshot?.filePath,lineNumber:M.addressing?.snapshot?.lineNumber,author:M.addressing?.snapshot?.authorLogin,summary:M.summary,body:M.body,url:M.addressing?.snapshot?.url};const O=M.item;return{id:M.item.id,source:w.source==="pull-request"?"pr-review":"reviewer-agent",threadId:typeof O.threadId=="string"?O.threadId:void 0,filePath:M.item.path,lineNumber:typeof O.line=="number"?O.line:void 0,author:M.item.author?.login,summary:M.item.summary??M.item.body.slice(0,120),body:M.item.body,url:typeof O.url=="string"?O.url:void 0}}),F=await rS(e.id,L,n);b(F.reviewState),s?.({...F.task,reviewState:F.reviewState}),o([]),a("Same-task AI revision started from selected review feedback","success")}catch(L){const F=L instanceof Error?L.message:"Failed to queue revision";p(F),a(F,"error")}finally{u(!1)}};return t.jsxs("div",{className:"task-review-tab",children:[t.jsxs("div",{className:"task-review-tab__header",children:[t.jsxs("div",{className:"task-review-tab__summary-wrap",children:[t.jsx("p",{className:"task-review-tab__summary",children:C}),v?t.jsx("span",{className:`task-review-tab__decision task-review-tab__decision--${v}`,children:v}):null]}),t.jsxs("div",{className:"task-review-tab__actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:E,disabled:l||m,children:l?"Refreshing…":"Refresh"}),t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!y,onClick:R,children:d?"Queueing…":"Request revision"})]})]}),t.jsxs("div",{className:"task-review-tab__meta task-review-tab__refresh-meta","aria-live":"polite",children:[t.jsx("span",{className:P,"aria-hidden":"true"}),t.jsxs("span",{children:[j==="error"?"Refresh failed":j==="refreshing"?"Refreshing":"Up to date"," · Last refreshed: ",Or(w?.lastRefreshedAt)," · ",UR(w?.refreshSource)]})]}),m?t.jsx("div",{className:"task-review-tab__meta",children:"Loading review data…"}):null,!m&&f?t.jsx("div",{className:"task-review-tab__error",children:f}):null,!m&&!f&&!S&&k.length===0?t.jsx("div",{className:"task-review-tab__empty",children:g??FR}):null,!m&&!f&&k.length>0?t.jsx("ul",{className:"task-review-tab__list",children:k.map(L=>t.jsx("li",{className:"task-review-tab__item card",children:t.jsxs("label",{className:"task-review-tab__direct-item task-review-tab__direct-item--selectable",children:[t.jsxs("div",{className:"task-review-tab__summary-wrap",children:[t.jsx("input",{type:"checkbox",checked:r.includes(L.id),onChange:()=>U(L.id)}),t.jsxs("span",{className:"task-review-tab__item-summary",children:[L.path?`${L.path}: `:"",L.summary]}),t.jsx("span",{className:`task-review-tab__status task-review-tab__status--${L.status}`,children:L.status})]}),t.jsx("div",{className:"task-review-tab__meta",children:Or(L.createdAt)}),L.addressing?t.jsxs("div",{className:"task-review-tab__meta",children:["Selected: ",Or(L.addressing.selectedAt),L.addressing.startedAt?` · Started: ${Or(L.addressing.startedAt)}`:"",L.addressing.completedAt?` · Completed: ${Or(L.addressing.completedAt)}`:"",L.addressing.error?` · Error: ${L.addressing.error}`:""]}):null,t.jsx("pre",{className:"task-review-tab__body",children:L.body})]})},L.id))}):null,S&&!m&&!f&&k.length===0?t.jsx("div",{className:"task-review-tab__empty",children:"No review items yet."}):null]})}function qR(e){return e?e.slice(0,7):"Unknown"}function VR({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:qR(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 vx(e){return e.split(`
|
|
681
|
+
`).map((s,a)=>{let r="";return s.startsWith("+")&&!s.startsWith("+++")?r="diff-add":s.startsWith("-")&&!s.startsWith("---")?r="diff-del":s.startsWith("@@")&&(r="diff-hunk"),r?t.jsx("span",{className:r,children:`${s}
|
|
682
|
+
`},a):t.jsx(kl.Fragment,{children:`${s}
|
|
683
|
+
`},a)})}function WR(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function KR({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);Ai(f,e,"fusion:changes-diff-modal-size");const p=qi(l);i.useEffect(()=>{s.length>0&&d===null&&u(0)},[s,d]);const g=i.useCallback(()=>{u(y=>y!==null&&y>0?y-1:y)},[]),x=i.useCallback(()=>{u(y=>y!==null&&y<s.length-1?y+1:y)},[]);if(i.useEffect(()=>{if(!e)return;const y=S=>{if(S.key==="Escape"){l();return}S.key==="ArrowUp"&&(S.metaKey||S.ctrlKey)&&(S.preventDefault(),g()),S.key==="ArrowDown"&&(S.metaKey||S.ctrlKey)&&(S.preventDefault(),x())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[e,l,g,x]),!e)return null;const w=d!==null?s[d]:null,b=o==="done";return t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal changes-diff-modal",ref:f,children:[t.jsxs("div",{className:"modal-header changes-diff-modal-header",children:[t.jsxs("div",{className:"changes-diff-header-title",children:[t.jsx(hi,{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(ql,{})}),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(Mn,{})})]}),t.jsx("button",{className:`btn btn-sm ${m?"btn-primary":""}`,onClick:()=>h(y=>!y),title:m?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(Nl,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx(rs,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(nn,{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(ko,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergeCommitMessage&&t.jsx("div",{className:"commit-diff-message",children:r.mergeCommitMessage}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsx("div",{className:"changes-diff-file-list",children:s.map((y,S)=>t.jsxs("button",{className:`changes-diff-file-item ${d===S?"selected":""}`,onClick:()=>u(S),title:y.path,children:[t.jsx("span",{className:`changes-file-status changes-file-status--${y.status}`,children:WR(y.status)}),t.jsx("span",{className:"changes-diff-file-path",title:y.path,children:t.jsx("bdo",{dir:"ltr",children:y.path})}),t.jsxs("span",{className:"changes-diff-file-stat",children:["+",y.additions," -",y.deletions]})]},y.path))})]}),t.jsx("div",{className:"changes-diff-content",children:w?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"changes-diff-file-header-bar",children:[t.jsx("span",{className:"changes-diff-file-header-name",children:w.path}),t.jsxs("span",{className:"changes-diff-file-header-stats",children:["+",w.additions," -",w.deletions]})]}),w.patch?t.jsx("div",{className:"changes-diff-viewer",children:t.jsx("pre",{className:`changes-diff-patch ${m?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:vx(w.patch)})})}):t.jsx("div",{className:"changes-diff-empty",children:"No diff available for this file."})]}):t.jsxs("div",{className:"changes-diff-empty",children:[t.jsx(hi,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function yx(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function Jc(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(ko,{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(hi,{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:yx("unknown")}),t.jsx("span",{className:"changes-file-path",title:a,children:t.jsx("bdo",{dir:"ltr",children:a})})]})},a))})]})}function GR({taskId:e,worktree:n,projectId:s,column:a,mergeDetails:r,modifiedFiles:o}){const[l,c]=i.useState([]),[d,u]=i.useState({filesChanged:0,additions:0,deletions:0}),[m,h]=i.useState(!0),[f,p]=i.useState(null),[g,x]=i.useState(new Set),[w,b]=i.useState(null),[y,S]=i.useState(!0),[k,C]=i.useState(!1),v=a==="done",j=v&&!!r?.commitSha,P=a==="in-progress"||a==="in-review"||j,U=i.useCallback(async()=>{if(!P){h(!1);return}try{h(!0),p(null);const M=await Pg(e,void 0,s),O=M.files.map(q=>({path:q.path,status:q.status,additions:q.additions,deletions:q.deletions,patch:q.patch}));c(O),u(M.stats),O.length>0&&(x(new Set([O[0].path])),b(0))}catch(M){p(Re(M)||"Failed to load diff")}finally{h(!1)}},[e,s,P]);i.useEffect(()=>{U()},[U]);const E=M=>{x(O=>{const q=new Set(O);if(q.has(M))q.delete(M);else{q.add(M);const te=l.findIndex(Z=>Z.path===M);te!==-1&&b(te)}return q})},R=M=>{if(M<0||M>=l.length)return;const O=l[M].path;x(new Set([O])),b(M)},L=w!==null&&w>0,F=w!==null&&w<l.length-1;if(m)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--loading",children:[t.jsx("div",{className:"loading-spinner"}),t.jsx("span",{children:"Loading changes..."})]})});if(f)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--error",children:[t.jsx(Ps,{size:16}),t.jsxs("span",{children:["Error loading changes: ",f]})]})});if(!v&&!n)return o&&o.length>0?Jc(o,!1):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(hi,{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(v&&!j){if(o&&o.length>0)return Jc(o,!0,r);const M=r?.filesChanged,O=r?.insertions,q=r?.deletions,te=M!=null||O!=null||q!=null;return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(hi,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:te?`Merge summary: ${M??0} file${(M??0)===1?"":"s"} changed, +${O??0} additions, -${q??0} deletions.`:"No merge commit was recorded for this task."})]})})}return l.length===0?o&&o.length>0?Jc(o,v,r):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(hi,{size:24}),t.jsx("p",{children:"No files modified."}),t.jsx("span",{className:"task-changes-state-hint",children:v?"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:[v&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(ko,{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(hi,{size:16}),"Files Changed (",d.filesChanged,")"]}),t.jsxs("span",{className:"task-changes-stats changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",d.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",d.deletions]})]})]}),t.jsxs("div",{className:"changes-header-actions-wrapper",children:[t.jsxs("div",{className:"changes-header-actions",children:[l.length>0&&t.jsxs("div",{className:"changes-nav",children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>L&&R(w-1),disabled:!L,title:"Previous file","aria-label":"Previous file",children:t.jsx(ql,{})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:w!==null?`${w+1}/${l.length}`:`—/${l.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>F&&R(w+1),disabled:!F,title:"Next file","aria-label":"Next file",children:t.jsx(Mn,{})})]}),t.jsx("button",{className:`btn btn-sm ${y?"btn-primary":""}`,onClick:()=>S(M=>!M),title:y?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(Nl,{size:14})})]}),t.jsxs("div",{className:"changes-header-actions-secondary",children:[t.jsx("button",{className:"btn btn-sm",onClick:U,disabled:m,children:"Refresh"}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>C(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:t.jsx(Ql,{})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map(M=>{const O=g.has(M.path);return t.jsxs("div",{className:`changes-file-item ${O?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>E(M.path),children:[t.jsx("span",{className:"changes-file-toggle",children:O?t.jsx(rn,{size:14}):t.jsx(Mn,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${M.status}`,title:M.status,children:yx(M.status)}),t.jsx("span",{className:"changes-file-path",title:M.path,children:t.jsx("bdo",{dir:"ltr",children:M.path})}),t.jsxs("span",{className:"changes-file-stat",title:`+${M.additions} -${M.deletions}`,children:["+",M.additions," -",M.deletions]})]}),O&&M.patch&&t.jsx("div",{className:"changes-file-content",children:t.jsx("pre",{className:`changes-diff-patch ${y?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:vx(M.patch)})})})]},M.path)})}),t.jsx(KR,{isOpen:k,taskId:e,files:l,stats:d,mergeDetails:r,column:a,onClose:()=>C(!1),onRefresh:U})]})}function up(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function JR(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function W6(e,n){const s=JR(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 YR(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}const mp=["image/png","image/jpeg","image/gif","image/webp"];function QR(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 wx({mode:e,description:n,onDescriptionChange:s,title:a,onTitleChange:r,dependencies:o,onDependenciesChange:l,branch:c,onBranchChange:d,baseBranch:u,onBaseBranchChange:m,nodeId:h,onNodeIdChange:f,nodeOptions:p,nodeOverrideDisabled:g=!1,nodeOverrideDisabledReason:x,priority:w,onPriorityChange:b,executorModel:y,onExecutorModelChange:S,validatorModel:k,onValidatorModelChange:C,planningModel:v,onPlanningModelChange:j,thinkingLevel:P,onThinkingLevelChange:U,presetMode:E,onPresetModeChange:R,selectedPresetId:L,onSelectedPresetIdChange:F,selectedWorkflowSteps:M,onWorkflowStepsChange:O,onDefaultOnApplied:q,pendingImages:te,onImagesChange:Z,tasks:K,projectId:A,disabled:I=!1,addToast:$,isActive:N=!0,onAutoSaveDescription:G,onPlanningMode:ge,onSubtaskBreakdown:je,onClose:ke,renderBelowPrimary:ne,renderBelowModelConfiguration:qe,hideDependencies:ee,autoExpandMoreOptionsOnSelection:le=!0,reviewLevel:se,onReviewLevelChange:re,executionMode:J,onExecutionModeChange:B}){const ve=(ee?!1:o.length>0)||te.length>0||M.length>0||E!=="default"||(w??js)!==js||y!==""||k!==""||(v||"")!==""||(P||"")!==""||se!==void 0||J==="fast"||(c||"")!==""||(u||"")!==""||(h||"")!=="",[Ne,H]=i.useState(!1),[be,ce]=i.useState(le?ve:!1),[Me,Le]=i.useState(""),[He,gt]=i.useState([]),[Ue,pe]=i.useState([]),[Oe,ze]=i.useState([]),[lt,Be]=i.useState(!1),[ye,Y]=i.useState(null),[_e,ct]=i.useState([]),[pt,de]=i.useState("idle"),[Ve,Ee]=i.useState(!1),[$e,ut]=i.useState(!1),[ht,Se]=i.useState(!1),we=i.useRef(null),Ae=i.useRef(null),he=i.useRef(null),We=i.useRef(null),me=i.useRef(null),nt=i.useRef(null),Ct=i.useRef(null),wt=i.useRef(!1),$t=i.useRef(ve),Vt=i.useRef(n.trim()),Mt=i.useRef(n.trim());i.useEffect(()=>{N&&(Be(!0),Os().then(ae=>{gt(ae.models),pe(ae.favoriteProviders),ze(ae.favoriteModels)}).catch(()=>{}).finally(()=>Be(!1)),Xl(A).then(ae=>Y(ae)).catch(()=>Y(null)),_o(A).then(ae=>ct(ae.filter(De=>De.enabled))).catch(()=>ct([])))},[N,A]);const Dt=ye?.modelPresets||[],Qt=Dt.find(ae=>ae.id===L),Kt=(ee?!1:o.length>0)||te.length>0||M.length>0||E!=="default"||(w??js)!==js||y!==""||k!==""||(v||"")!==""||(P||"")!==""||se!==void 0||J==="fast"||(c||"")!==""||(u||"")!==""||(h||"")!=="";i.useEffect(()=>{if(e!=="create"||!N||!ye?.autoSelectModelPreset)return;const ae=(ye.defaultPresetBySize,void 0);if(ae){const De=up(ae);F(ae.id),R("preset"),S(De.executorValue),C(De.validatorValue)}},[N,ye,Dt,e]);const Bt=i.useRef(!1);i.useEffect(()=>{if(e!=="create"||!N||Bt.current||_e.length===0)return;const ae=_e.filter(At=>At.defaultOn);if(ae.length===0)return;Bt.current=!0;const De=ae.map(At=>At.id);O(De),q?.(De)},[e,N,_e]),i.useEffect(()=>{N||(Bt.current=!1)},[N]),i.useEffect(()=>{if(!le){$t.current=Kt;return}Kt&&!$t.current&&ce(!0),$t.current=Kt},[Kt,le]),i.useEffect(()=>{be||(H(!1),Le(""))},[be]),i.useEffect(()=>{e!=="edit"||!N||We.current&&(We.current.focus(),We.current.select())},[e,N]),i.useEffect(()=>{if(!Ne)return;const ae=De=>{Ae.current&&!Ae.current.contains(De.target)&&H(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[Ne]),i.useEffect(()=>{(e!=="edit"||I)&&Se(!1)},[e,I]),i.useEffect(()=>{if(e!=="edit"){de("idle");return}const ae=n.trim();Vt.current=ae,Mt.current=ae,de("idle")},[e]),i.useEffect(()=>{if(e!=="edit"||!G||!N)return;const ae=n.trim(),De=Vt.current;if(ae===De||ae===Mt.current){nt.current&&(clearTimeout(nt.current),nt.current=null),wt.current||de("idle");return}return nt.current&&clearTimeout(nt.current),nt.current=setTimeout(async()=>{if(!wt.current){wt.current=!0,de("saving");try{await G(ae),Mt.current=ae,de("saved"),Ct.current&&clearTimeout(Ct.current),Ct.current=setTimeout(()=>{de("idle"),Ct.current=null},2e3)}catch{de("idle")}finally{wt.current=!1,nt.current=null}}},1500),()=>{nt.current&&(clearTimeout(nt.current),nt.current=null)}},[e,n,G,N]),i.useEffect(()=>()=>{nt.current&&clearTimeout(nt.current),Ct.current&&clearTimeout(Ct.current)},[]),i.useEffect(()=>{if(!Ve)return;const ae=De=>{we.current&&!we.current.contains(De.target)&&Ee(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[Ve]);const on=i.useCallback(ae=>{const De=ae.clipboardData?.items;if(De)for(let At=0;At<De.length;At++){const Lt=De[At];if(Lt.type.startsWith("image/")){const Ft=Lt.getAsFile();if(Ft&&mp.includes(Ft.type)){ae.preventDefault(),Z([...te,{file:Ft,previewUrl:URL.createObjectURL(Ft)}]);return}}}},[te,Z]),fn=i.useCallback(ae=>{ae.preventDefault();const De=ae.dataTransfer.files;for(let At=0;At<De.length;At++){const Lt=De[At];if(mp.includes(Lt.type)){Z([...te,{file:Lt,previewUrl:URL.createObjectURL(Lt)}]);return}}},[te,Z]),Jt=i.useCallback(ae=>{const De=te[ae];De&&URL.revokeObjectURL(De.previewUrl),Z(te.filter((At,Lt)=>Lt!==ae))},[te,Z]),an=i.useCallback(ae=>{l(o.includes(ae)?o.filter(De=>De!==ae):[...o,ae])},[o,l]),zt=(ae,De)=>ae.length>De?ae.slice(0,De)+"…":ae,en=i.useCallback(ae=>{s(ae.target.value);const De=ae.target;De.style.height="auto",De.style.height=De.scrollHeight+"px"},[s]),Zt=i.useCallback(()=>{Se(ae=>!ae)},[]),dn=i.useCallback(ae=>{!ht||ae.key!=="Escape"||(ae.preventDefault(),ae.stopPropagation(),Se(!1))},[ht]),xe=i.useCallback(async ae=>{const De=n.trim();if(!(!De||$e)){ut(!0);try{const At=await Cg(De,ae,A);s(At),Ee(!1),$("Description refined with AI","success"),he.current&&(he.current.style.height="auto",he.current.style.height=he.current.scrollHeight+"px")}catch(At){const Lt=Eg(At);$(Lt,"error")}finally{ut(!1)}}},[n,$e,$,s,A]),Fe=i.useCallback(async ae=>{const De=Ue,Lt=De.includes(ae)?De.filter(Ft=>Ft!==ae):[ae,...De];pe(Lt);try{await kn({favoriteProviders:Lt,favoriteModels:Oe})}catch{pe(De)}},[Ue,Oe]),Ke=i.useCallback(async ae=>{const De=Oe,Lt=De.includes(ae)?De.filter(Ft=>Ft!==ae):[ae,...De];ze(Lt);try{await kn({favoriteProviders:Ue,favoriteModels:Lt})}catch{ze(De)}},[Oe,Ue]),et=i.useCallback(ae=>{if(ae<=0)return;const De=[...M];[De[ae-1],De[ae]]=[De[ae],De[ae-1]],O(De)},[M,O]),Qe=i.useCallback(ae=>{if(ae>=M.length-1)return;const De=[...M];[De[ae],De[ae+1]]=[De[ae+1],De[ae]],O(De)},[M,O]),It=i.useCallback(ae=>{O(M.filter(De=>De!==ae))},[M,O]),St=new Map;for(const ae of _e)St.set(ae.id,{name:ae.name,description:ae.description});const Ht=K.filter(ae=>!o.includes(ae.id)).sort((ae,De)=>{const At=De.createdAt.localeCompare(ae.createdAt);if(At!==0)return At;const Lt=parseInt(ae.id.slice(ae.id.lastIndexOf("-")+1),10)||0;return(parseInt(De.id.slice(De.id.lastIndexOf("-")+1),10)||0)-Lt}),jt=Me?Ht.filter(ae=>ae.id.toLowerCase().includes(Me.toLowerCase())||ae.title&&ae.title.toLowerCase().includes(Me.toLowerCase())||ae.description&&ae.description.toLowerCase().includes(Me.toLowerCase())):Ht;return t.jsxs("div",{className:"task-form",onDrop:fn,onDragOver:ae=>ae.preventDefault(),onPaste:on,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:We,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:a||"",onChange:ae=>r(ae.target.value),disabled:I})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:"task-form-description",className:"description-label-row",children:[t.jsx("span",{children:"Description"}),t.jsx("span",{className:`description-auto-save-status${pt==="idle"?"":" is-visible"}`,"aria-live":"polite",children:pt==="saving"?"Saving...":pt==="saved"?"Saved":""})]}),t.jsxs("div",{className:`description-with-refine${ht?" description--fullscreen":""}`,ref:we,onKeyDown:dn,children:[ht&&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:Zt,"aria-label":"Collapse description",title:"Collapse description",children:t.jsx(jo,{size:14})})]}),t.jsx("textarea",{ref:he,autoFocus:e==="create",id:"task-form-description",value:n,onChange:en,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:I||$e}),(()=>{const ae=!!n.trim()&&!I;return t.jsxs(t.Fragment,{children:[!ht&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${ae?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:Zt,"aria-label":"Expand description",title:"Expand description",children:t.jsx(Ql,{size:14})}),ae&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${$e?"refine-button--loading":""}`,onClick:()=>Ee(De=>!De),disabled:$e,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(ps,{size:12,style:{verticalAlign:"middle"}}),$e?"Refining...":"Refine"]})]})})(),Ve&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:ae=>ae.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>xe("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:()=>xe("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:()=>xe("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:()=>xe("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"&&(ge||je)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[ge&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const ae=n.trim();if(!ae){$("Enter a description first","error");return}ke?.(),ge(ae)},disabled:I||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),je&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const ae=n.trim();if(!ae){$("Enter a description first","error");return}ke?.(),je(ae)},disabled:I||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),ne,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>ce(ae=>!ae),"aria-expanded":be,"aria-controls":"task-form-more-options",disabled:I,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),be?t.jsx(Ei,{size:14}):t.jsx(rn,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${be?"":" collapsed"}`,"aria-hidden":!be,hidden:!be,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Attachments"}),te.length>0&&t.jsx("div",{className:"inline-create-previews",children:te.map((ae,De)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:ae.previewUrl,alt:ae.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>Jt(De),disabled:I,title:"Remove image",children:"×"})]},ae.previewUrl))}),t.jsx("input",{ref:me,type:"file",accept:"image/*",onChange:ae=>{const De=ae.target.files?.[0];De&&(Z([...te,{file:De,previewUrl:URL.createObjectURL(De)}]),ae.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>me.current?.click(),disabled:I,children:"Attach Screenshot"}),t.jsx("small",{children:"You can also paste images or drag & drop"})]}),f&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"task-node-select",children:"Execution Node Override"}),t.jsxs("select",{id:"task-node-select",className:"select",value:h??"",onChange:ae=>f(ae.target.value||void 0),disabled:I||g,children:[t.jsx("option",{value:"",children:"Use project default / local"}),(p??[]).map(ae=>t.jsxs("option",{value:ae.id,children:[ae.name," (",YR(ae.status),")"]},ae.id))]}),(()=>{const ae=(p??[]).find(De=>De.id===h);return ae?t.jsx("div",{className:"task-form-node-status",children:t.jsx(Ca,{status:ae.status,showLabel:!0})}):null})(),t.jsx("small",{children:x??"Task override takes priority over project default node routing."})]}),!ee&&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:Ae,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>H(ae=>!ae),disabled:I,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:Me,onChange:ae=>Le(ae.target.value),onClick:ae=>ae.stopPropagation()}),jt.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):jt.map(ae=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(ae.id)?" selected":""}`,onClick:()=>an(ae.id),onMouseDown:De=>De.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:ae.id}),t.jsx("span",{className:"dep-dropdown-title",children:zt(ae.title||ae.description||ae.id,30)})]},ae.id))]})]}),o.length>0&&t.jsx("div",{className:"selected-deps",children:o.map(ae=>t.jsxs("span",{className:"dep-chip",children:[ae,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>an(ae),disabled:I,children:"×"})]},ae))})]})}),(d||m)&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Branch Settings"}),d&&t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"task-working-branch",className:"model-select-label",children:"Working branch"}),t.jsx("input",{id:"task-working-branch",className:"input",value:c||"",onChange:ae=>d(ae.target.value),placeholder:"e.g. feature/my-task",disabled:I})]}),m&&t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"task-base-branch",className:"model-select-label",children:"Merge target / base branch"}),t.jsx("input",{id:"task-base-branch",className:"input",value:u||"",onChange:ae=>m(ae.target.value),placeholder:"e.g. main",disabled:I})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Model Configuration"}),b&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"task-priority",className:"model-select-label",children:"Priority"}),t.jsx("select",{id:"task-priority","data-testid":"task-priority-select",value:w??js,onChange:ae=>b(ae.target.value),disabled:I,children:oa.map(ae=>t.jsx("option",{value:ae,children:ae[0].toUpperCase()+ae.slice(1)},ae))})]}),B&&J!==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:J,onChange:ae=>B(ae.target.value),disabled:I,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),lt?t.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):He.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:E==="preset"?L:E,onChange:ae=>{const De=ae.target.value;if(De==="default"){R("default"),F(""),S(""),C("");return}if(De==="custom"){R("custom"),F("");return}const At=Dt.find(Ft=>Ft.id===De),Lt=up(At);R("preset"),F(De),S(Lt.executorValue),C(Lt.validatorValue)},disabled:I,children:[t.jsx("option",{value:"default",children:"Use default"}),Dt.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,Dt.map(ae=>t.jsx("option",{value:ae.id,children:ae.name},ae.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),E==="preset"&&Qt?t.jsxs("small",{children:["Using preset: ",Qt.name]}):null,E==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>R("custom"),disabled:I,children:"Override"}):null,t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"executor-model",className:"model-select-label",children:"Executor"}),t.jsx(ys,{id:"executor-model",label:"Executor Model",value:y,onChange:ae=>{R("custom"),F(""),S(ae)},models:He,disabled:I||E==="preset",favoriteProviders:Ue,onToggleFavorite:Fe,favoriteModels:Oe,onToggleModelFavorite:Ke})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Reviewer"}),t.jsx(ys,{id:"validator-model",label:"Reviewer Model",value:k,onChange:ae=>{R("custom"),F(""),C(ae)},models:He,disabled:I||E==="preset",favoriteProviders:Ue,onToggleFavorite:Fe,favoriteModels:Oe,onToggleModelFavorite:Ke})]}),j&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),t.jsx(ys,{id:"planning-model",label:"Planning Model",value:v||"",onChange:ae=>{R("custom"),F(""),j(ae)},models:He,disabled:I||E==="preset",favoriteProviders:Ue,onToggleFavorite:Fe,favoriteModels:Oe,onToggleModelFavorite:Ke})]}),U&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"thinking-level",className:"model-select-label",children:"Thinking"}),t.jsxs("select",{id:"thinking-level",value:P||"",onChange:ae=>U(ae.target.value),disabled:I||E==="preset",children:[t.jsxs("option",{value:"",children:["Default (",ye?.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"})]})]}),re&&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:se??"",onChange:ae=>re(ae.target.value===""?void 0:parseInt(ae.target.value,10)),disabled:I,children:[t.jsx("option",{value:"",children:"Default (Auto — triage decides)"}),t.jsx("option",{value:"0",children:"0 — None"}),t.jsx("option",{value:"1",children:"1 — Plan Only"}),t.jsx("option",{value:"2",children:"2 — Plan and Code"}),t.jsx("option",{value:"3",children:"3 — Full"})]})]})]})]}),qe,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:_e.length>0&&_e.map(ae=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${ae.id}`,children:[t.jsx("input",{type:"checkbox",checked:M.includes(ae.id),onChange:De=>{O(De.target.checked?[...M,ae.id]:M.filter(At=>At!==ae.id))},disabled:I}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[ae.name,QR(ae.phase||"pre-merge",ae.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:ae.description})]})]},ae.id))})]}),M.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:"}),M.map((ae,De)=>{const At=St.get(ae);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${ae}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:De+1}),t.jsx("span",{className:"workflow-step-order-name",children:At?.name||ae}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>et(De),disabled:I||De===0,"data-testid":`workflow-step-move-up-${ae}`,title:"Move up",children:t.jsx(Ei,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Qe(De),disabled:I||De===M.length-1,"data-testid":`workflow-step-move-down-${ae}`,title:"Move down",children:t.jsx(rn,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>It(ae),disabled:I,"data-testid":`workflow-step-remove-${ae}`,title:"Remove",children:t.jsx(nn,{})})]})]},ae)})]})]})]})]})}const hp={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 XR(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function ZR(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 eI(e){return e?new Date(e).toLocaleString():null}function tI(e){const n=e.split(`
|
|
684
|
+
`);return n.length<=1?e:`${n.length} lines`}function Yo(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 nI({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 sI({taskId:e,results:n,loading:s,enabledWorkflowSteps:a,canEdit:r,projectId:o,isTaskInProgress:l,onWorkflowStepsChange:c}){const[d,u]=i.useState({}),[m,h]=i.useState({}),[f,p]=i.useState(null),[g,x]=i.useState([]),[w,b]=i.useState(!1),y=n.some(N=>N.status==="pending"),{entries:S}=gx(e,!!l&&y,o);i.useEffect(()=>{let N=!1;return _o(o).then(G=>{N||x(G.filter(ge=>ge.enabled))}).catch(()=>{N||x([])}),()=>{N=!0}},[o]);const k=a??[],C=i.useMemo(()=>g.map(N=>({id:N.id,name:N.name,description:N.description,phase:N.phase||"pre-merge"})),[g]),v=i.useMemo(()=>new Map(C.map(N=>[N.id,N])),[C]),j=N=>{u(G=>({...G,[N]:!G[N]}))},P=N=>{h(G=>{const ge=G[N]??"markdown";return{...G,[N]:ge==="markdown"?"plain":"markdown"}})},U=N=>{p(N)},E=()=>{p(null)};i.useEffect(()=>{if(!f)return;const N=G=>{G.key==="Escape"&&E()};return document.addEventListener("keydown",N),()=>{document.removeEventListener("keydown",N)}},[f]);const R=i.useCallback((N,G)=>{if(c){if(G){if(k.includes(N)){c(k);return}c([...k,N]);return}c(k.filter(ge=>ge!==N))}},[c,k]),L=i.useCallback(N=>{if(!c||N<=0)return;const G=[...k];[G[N-1],G[N]]=[G[N],G[N-1]],c(G)},[c,k]),F=i.useCallback(N=>{if(!c||N>=k.length-1)return;const G=[...k];[G[N],G[N+1]]=[G[N+1],G[N]],c(G)},[c,k]),M=i.useCallback(N=>{c&&c(k.filter(G=>G!==N))},[c,k]),O=n.length>0,q=k.length>0;i.useEffect(()=>{r||b(!1)},[r]);const te=i.useMemo(()=>k.map(N=>{const G=v.get(N);return{id:N,name:G?.name||N,description:G?.description||"Step definition not found.",phase:G?.phase||"pre-merge"}}),[k,v]),Z=()=>!r||!w||s?null:t.jsxs("div",{className:"workflow-results-editor","data-testid":"workflow-steps-editor",children:[t.jsxs("div",{className:"workflow-steps-section",children:[t.jsx("small",{className:"workflow-steps-description",children:"Select steps to run after task implementation completes"}),t.jsx("div",{className:"workflow-steps-list",children:C.map(N=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${N.id}`,children:[t.jsx("input",{type:"checkbox",checked:k.includes(N.id),onChange:G=>R(N.id,G.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[N.name,Yo(N.phase,N.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:N.description})]})]},N.id))})]}),k.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),k.map((N,G)=>{const ge=v.get(N);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${N}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:G+1}),t.jsx("span",{className:"workflow-step-order-name",children:ge?.name||N}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>L(G),disabled:G===0,"data-testid":`workflow-step-move-up-${N}`,title:"Move up",children:t.jsx(Ei,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>F(G),disabled:G===k.length-1,"data-testid":`workflow-step-move-down-${N}`,title:"Move down",children:t.jsx(rn,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>M(N),"data-testid":`workflow-step-remove-${N}`,title:"Remove",children:t.jsx(nn,{})})]})]},N)})]})]}),K=()=>{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(!O)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 N=n.filter(ne=>ne.status==="passed").length,G=n.filter(ne=>ne.status==="failed").length,ge=n.filter(ne=>ne.status==="skipped").length,je=n.filter(ne=>ne.status==="pending").length,ke=[`${n.length} step${n.length!==1?"s":""}`];return N>0&&ke.push(`${N} passed`),G>0&&ke.push(`${G} failed`),ge>0&&ke.push(`${ge} skipped`),je>0&&ke.push(`${je} running`),t.jsxs("div",{className:"workflow-results-list","data-testid":"workflow-results-list",children:[t.jsx("div",{className:"workflow-results-summary-bar","data-testid":"workflow-results-summary",children:ke.join(" · ")}),n.map((ne,qe)=>{const ee=ne.phase||"pre-merge",le=d[ne.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${ne.status}`,"data-testid":`workflow-result-item-${ne.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[ne.workflowStepName,Yo(ee,ne.workflowStepId,"workflow-result-phase")]}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${ne.status}`,"data-testid":`workflow-result-badge-${ne.workflowStepId}`,children:XR(ne.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[ne.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",eI(ne.startedAt)]}),ne.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:ZR(ne.startedAt,ne.completedAt)})]}),ne.status==="pending"&&ne.startedAt?t.jsx(nI,{entries:S,startedAt:ne.startedAt,stepId:ne.workflowStepId}):ne.output?t.jsxs("div",{className:"workflow-result-output-section",children:[t.jsxs("div",{className:"workflow-result-output-header",children:[t.jsx("span",{className:"workflow-result-output-label",children:"Output:"}),t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-toggle",onClick:()=>j(ne.workflowStepId),"data-testid":`workflow-result-toggle-${ne.workflowStepId}`,children:le?"Hide output":"Show output"}),!le&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${ne.workflowStepId}`,children:tI(ne.output)}),le&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-mode-toggle",onClick:()=>P(ne.workflowStepId),"data-testid":`workflow-result-mode-toggle-${ne.workflowStepId}`,title:(m[ne.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(m[ne.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm workflow-result-expand-toggle",onClick:()=>U(ne.workflowStepId),"data-testid":`workflow-result-expand-${ne.workflowStepId}`,title:"Expand output",children:t.jsx(Ql,{size:12})})]})]}),le&&t.jsx("div",{className:`workflow-result-output${(m[ne.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${ne.workflowStepId}`,children:(m[ne.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(bi,{remarkPlugins:[xi],components:hp,children:ne.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:ne.output})})]}):null]},`${ne.workflowStepId}-${qe}`)})]})},A=r?t.jsx("button",{type:"button",className:"modal-edit-btn workflow-results-edit-toggle",onClick:()=>b(N=>!N),"data-testid":"workflow-steps-edit-toggle","aria-label":w?"Done editing workflow steps":"Edit workflow steps",title:w?"Done":"Edit",children:w?t.jsxs(t.Fragment,{children:[t.jsx(hs,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(Ds,{size:14}),"Edit"]})}):null,I=!s&&!O&&q,$=r&&O;return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[I?t.jsxs("div",{className:"workflow-configured-steps","data-testid":"workflow-configured-steps",children:[t.jsxs("div",{className:"workflow-configured-header","data-testid":"workflow-configured-header",children:[t.jsxs("div",{className:"workflow-configured-title-row",children:[t.jsx("h4",{children:"Configured Workflow Steps"}),t.jsxs("span",{className:"workflow-configured-count","data-testid":"workflow-configured-count",children:[te.length," step",te.length===1?"":"s"]})]}),A]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:te.map(N=>t.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${N.id}`,children:[t.jsxs("div",{className:"workflow-configured-name",children:[N.name,Yo(N.phase,N.id,"workflow-configured-phase")]}),t.jsx("p",{className:"workflow-configured-description",children:N.description})]},N.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."}),Z()]}):t.jsxs(t.Fragment,{children:[$&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:"Workflow Steps"}),A]}),K(),Z()]}),f&&(()=>{const N=n.find(je=>je.workflowStepId===f);if(!N)return null;const G=m[N.workflowStepId]??"markdown",ge=N.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:je=>{je.target===je.currentTarget&&E()},"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:N.workflowStepName}),Yo(ge,N.workflowStepId,"workflow-output-modal-phase")]}),t.jsxs("div",{className:"workflow-output-modal-controls",children:[t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-mode-toggle",onClick:()=>P(N.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:G==="markdown"?"Switch to plain text":"Switch to markdown",children:G==="markdown"?"Markdown":"Plain"}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm workflow-output-modal-close",onClick:E,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:t.jsx(nn,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${G==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:G==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(bi,{remarkPlugins:[xi],components:hp,children:N.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:N.output})})})]})})})()]})}function iI(e){return e==="block"?"Block execution":e==="fallback-local"?"Fall back to local":"Not configured"}const aI=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function rI(e){return e!==void 0&&e!=="online"}function oI({task:e,settings:n,addToast:s,onTaskUpdated:a}){const[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState(null),[m,h]=i.useState(e.nodeId??""),[f,p]=i.useState(!1),g=i.useRef(e.id);i.useEffect(()=>{g.current=e.id,h(e.nodeId??""),p(!1)},[e.id,e.nodeId]),i.useEffect(()=>{c(!0),u(null),_l().then(E=>{o(E)}).catch(E=>{u(Re(E)||"Failed to load nodes")}).finally(()=>{c(!1)})},[]);const x=i.useMemo(()=>new Map(r.map(E=>[E.id,E])),[r]),w=i.useMemo(()=>[...r].sort((E,R)=>E.name.localeCompare(R.name)),[r]),b=n,y=e.nodeId??b?.defaultNodeId??null,S=e.nodeId?"Per-task override":b?.defaultNodeId?"Project default":"No routing",k=y?x.get(y):void 0,C=k?`${k.name} (${k.type})`:y?`${y} (node unavailable or unknown)`:"Local (no routing configured)",v=e.column==="in-progress"||aI.has(e.status),j=v||f||l,P=i.useCallback(async E=>{if(E===m)return;const R=e.id,L=m;h(E),p(!0);try{const F=await mi(R,{nodeId:E||null});if(g.current!==R)return;h(F.nodeId??""),a?.(F),s(E?"Node override updated":"Node override cleared","success")}catch(F){if(g.current!==R)return;h(L),s(Re(F)||"Failed to update node override","error")}finally{g.current===R&&p(!1)}},[s,a,m,e.id]),U=i.useCallback(()=>{P("")},[P]);return t.jsxs("div",{className:"routing-tab",children:[t.jsx("h4",{children:"Task Routing"}),t.jsx("p",{className:"routing-tab__intro",children:"View the effective execution node and control per-task node override."}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Routing Summary"}),t.jsxs("div",{className:"routing-summary-grid",role:"list",children:[t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Effective node"}),t.jsxs("span",{className:"routing-summary-value",children:[k?t.jsx(Ca,{status:k.status,compact:!0}):null,C,rI(k?.status)?t.jsx("span",{className:"routing-summary-warning",children:"Unhealthy"}):null]})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Routing source"}),t.jsx("span",{className:"routing-summary-value",children: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:iI(b?.unavailableNodePolicy)})]})]}),v&&y?t.jsx("div",{className:"routing-tab__info-banner",children:"Routing is locked while this task is active. Node override cannot be changed until the task is no longer active."}):null]}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Node Override"}),v?t.jsx("div",{className:"routing-tab__warning-banner",children:"Node override cannot be changed while the task is active."}):null,t.jsx("label",{className:"routing-tab__selector-label",htmlFor:`routing-node-${e.id}`,children:"Select execution node"}),t.jsxs("select",{id:`routing-node-${e.id}`,className:"select routing-tab__selector",value:m,disabled:j,onChange:E=>{P(E.target.value)},children:[t.jsx("option",{value:"",children:"Use project default"}),w.map(E=>t.jsxs("option",{value:E.id,title:`Status: ${E.status}`,children:[E.name," (",E.type,") — ",E.status]},E.id))]}),d?t.jsx("div",{className:"routing-tab__error",children:d}):null,e.nodeId?t.jsxs("div",{className:"routing-tab__override-row",children:[t.jsxs("span",{className:"routing-tab__override-text",children:["Override set to: ",x.get(e.nodeId)?.name??e.nodeId]}),t.jsx("button",{type:"button",className:"btn btn-sm",disabled:v||f,onClick:U,children:"Clear override"})]}):null]})]})}const lI=/^[a-zA-Z0-9_-]{1,64}$/,cI=200;function pp(e){return e?new Date(e).toLocaleString():""}function dI(e,n=cI){return e.length<=n?e:e.substring(0,n)+"…"}function uI({taskId:e,addToast:n,onTaskUpdated:s,projectId:a,canEdit:r=!1}){const[o,l]=i.useState([]),[c,d]=i.useState(!0),[u,m]=i.useState(null),[h,f]=i.useState(""),[p,g]=i.useState(null),[x,w]=i.useState(""),[b,y]=i.useState(null),[S,k]=i.useState([]),[C,v]=i.useState(!1),[j,P]=i.useState(!1),[U,E]=i.useState(""),[R,L]=i.useState(""),[F,M]=i.useState(!1),[O,q]=i.useState(null),[te,Z]=i.useState(null),[K,A]=i.useState(!1),I=i.useCallback(async()=>{try{const ee=await ej(e,a);l(ee)}catch(ee){n(Re(ee)||"Failed to load documents","error")}finally{d(!1)}},[e,a,n]);i.useEffect(()=>{I()},[I]);async function $(ee){u===ee.key?(m(null),f(""),g(null),w(""),y(null),k([]),A(!1)):(m(ee.key),f(ee.content),g(null),w(""),y(null),k([]),A(!1))}async function N(ee){if(b===ee)y(null),k([]);else{y(ee),v(!0);try{const le=await tj(e,ee,a);k(le)}catch(le){n(Re(le)||"Failed to load revisions","error")}finally{v(!1)}}}function G(){u&&(g(u),w(h))}function ge(){g(null),w("")}async function je(){if(!(!p||!x.trim())){M(!0);try{await im(e,p,x,{},a),g(null),w(""),await I();const ee=o.find(le=>le.key===p);ee&&f(ee.content),n("Document saved","success")}catch(ee){n(Re(ee)||"Failed to save document","error")}finally{M(!1)}}}async function ke(){const ee=U.trim(),le=R.trim();if(!ee){n("Document key is required","error");return}if(!lI.test(ee)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!le){n("Content is required","error");return}M(!0);try{await im(e,ee,le,{},a),P(!1),E(""),L(""),await I(),n("Document created","success")}catch(se){n(Re(se)||"Failed to create document","error")}finally{M(!1)}}async function ne(ee){q(ee);try{await nj(e,ee,a),Z(null),q(null),u===ee&&(m(null),f("")),b===ee&&(y(null),k([])),await I(),n("Document deleted","success")}catch(le){n(Re(le)||"Failed to delete document","error")}finally{q(null)}}function qe(ee){f(ee.content),g(null),w("")}return c?t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),t.jsx("div",{className:"detail-log-empty",children:"Loading documents…"})]}):t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),j&&t.jsxs("div",{className:"task-document-create-form",children:[t.jsx("h5",{children:"New Document"}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-key",children:"Key"}),t.jsx("input",{id:"doc-key",type:"text",className:"task-document-key-input",value:U,onChange:ee=>E(ee.target.value),placeholder:"e.g., plan, notes, research",disabled:F}),t.jsx("span",{className:"form-hint",children:"Alphanumeric, hyphens, underscores (1-64 chars)"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-content",children:"Content"}),t.jsx("textarea",{id:"doc-content",value:R,onChange:ee=>L(ee.target.value),rows:6,placeholder:"Enter document content…",disabled:F})]}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{P(!1),E(""),L("")},disabled:F,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void ke(),disabled:F||!U.trim()||!R.trim(),children:F?"Creating…":"Create"})]})]}),o.length===0&&!j?t.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):t.jsx("div",{className:"task-documents-list",children:o.map(ee=>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(ia,{size:14}),t.jsx("span",{className:"task-document-key",children:ee.key}),t.jsxs("span",{className:"task-document-revision-badge",children:["v",ee.revision]})]}),t.jsxs("div",{className:"task-document-meta",children:[t.jsx("span",{className:"task-document-author",children:ee.author}),t.jsx("span",{className:"task-document-timestamp",children:pp(ee.updatedAt||ee.createdAt)})]})]}),u===ee.key&&p!==ee.key&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"task-document-content-header",children:t.jsx("button",{className:"btn btn-sm document-mode-toggle",onClick:()=>A(le=>!le),"aria-label":K?"Switch to plain text":"Switch to markdown","aria-pressed":K,title:K?"Switch to plain text":"Switch to markdown",children:K?"Markdown":"Plain"})}),t.jsx("div",{className:"task-document-content",children:K?t.jsx("div",{className:"task-document-content-markdown",children:t.jsx("div",{className:"markdown-body",children:t.jsx(bi,{remarkPlugins:[xi],children:h})})}):t.jsx("pre",{className:"task-document-content-text",children:h})}),b===ee.key&&t.jsxs("div",{className:"task-document-revisions",children:[t.jsx("h5",{children:"Revision History"}),C?t.jsx("div",{className:"detail-log-empty",children:"Loading…"}):S.length<=1?t.jsx("div",{className:"detail-log-empty",children:"No previous revisions."}):t.jsx("div",{className:"task-document-revision-list",children:S.filter(le=>le.revision<ee.revision).sort((le,se)=>se.revision-le.revision).map(le=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>qe(le),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",le.revision]}),t.jsx("span",{className:"revision-author",children:le.author}),t.jsx("span",{className:"revision-timestamp",children:pp(le.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:dI(le.content,100)})]},le.id))})]})]}),p===ee.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:x,onChange:le=>w(le.target.value),rows:10,disabled:F}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:ge,disabled:F,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void je(),disabled:F||!x.trim(),children:F?"Saving…":"Save"})]})]}),t.jsxs("div",{className:"task-document-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>void $(ee),children:u===ee.key?t.jsxs(t.Fragment,{children:[t.jsx(Ei,{size:14})," Collapse"]}):t.jsxs(t.Fragment,{children:[t.jsx(rn,{size:14})," Expand"]})}),u===ee.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void N(ee.key),children:[t.jsx(lo,{size:14})," History"]}),r&&p!==ee.key&&t.jsx("button",{className:"btn btn-sm",onClick:G,children:"Edit"}),r&&(te===ee.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 ne(ee.key),disabled:O===ee.key,children:O===ee.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Z(null),disabled:O===ee.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>Z(ee.key),children:t.jsx(vn,{size:14})}))]})]})]},ee.key))}),r&&!j&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>P(!0),children:[t.jsx(bn,{size:14})," New Document"]})]})}function Qo(e){return e.toLocaleString()}function Yc(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function zr(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 mI(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=eb(e,n)??0,r=s.reduce((o,l)=>!o||l.durationMs>o.durationMs?l:o,void 0);return{timedStepCount:s.length,totalDurationMs:a,longestStep:r}}function hI({tokenUsage:e,loading:n,task:s}){const a=Date.now(),r=Xg(s?.log??[]),o=r.filter(g=>typeof g.durationMs=="number"),l=o.reduce((g,x)=>g+(x.durationMs??0),0),c=Zg(s?.log)??0,d=typeof s?.timedExecutionMs=="number"?s.timedExecutionMs:Math.max(l,c),u=o.reduce((g,x)=>!g||(x.durationMs??0)>(g.durationMs??0)?x:g,void 0),m=mI(s?.workflowStepResults??[]),f=tb(s?.executionStartedAt,s?.executionCompletedAt,a)??(typeof s?.timedExecutionMs=="number"?s.timedExecutionMs:d+m.totalDurationMs),p=s?.steps?.length??0;return t.jsxs("section",{className:"task-token-stats-panel","aria-label":"Task execution statistics",children:[t.jsx("h4",{children:"Execution & Token Stats"}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Execution Timing"}),t.jsxs("div",{className:"task-token-stats-panel__grid",role:"list","aria-label":"Execution timing metrics",children:[t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Timing events"}),t.jsx("span",{className:"task-token-stats-panel__value",children:r.length.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Timed duration"}),t.jsx("span",{className:"task-token-stats-panel__value",children:zr(d)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Workflow timed steps"}),t.jsx("span",{className:"task-token-stats-panel__value",children:m.timedStepCount.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Workflow runtime"}),t.jsx("span",{className:"task-token-stats-panel__value",children:zr(m.totalDurationMs)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Total execution time"}),t.jsx("span",{className:"task-token-stats-panel__value",children:zr(f)})]})]}),t.jsxs("dl",{className:"task-token-stats-panel__timestamps",children:[t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Longest timing event"}),t.jsx("dd",{children:u?.durationMs?`${u.summary} (${zr(u.durationMs)})`:"No timed events recorded yet."})]}),t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Longest workflow step"}),t.jsx("dd",{children:m.longestStep?`${m.longestStep.name} (${zr(m.longestStep.durationMs)})`:"No completed workflow step timings yet."})]})]})]}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Execution Details"}),t.jsxs("dl",{className:"task-token-stats-panel__details",children:[t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Execution mode"}),t.jsx("dd",{children:s?.executionMode==="fast"?"Fast":"Standard"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Runtime status"}),t.jsx("dd",{children:s?.status??"Not set"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Paused"}),t.jsx("dd",{children:s?.paused?"Yes":"No"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Step progress"}),t.jsx("dd",{children:p>0?`${Math.min((s?.currentStep??0)+1,p)} / ${p}`:"No steps"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Retries (recovery / workflow / merge / task_done)"}),t.jsx("dd",{children:`${s?.recoveryRetryCount??0} / ${s?.workflowStepRetries??0} / ${s?.mergeRetries??0} / ${s?.taskDoneRetryCount??0}`})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Recovery state"}),t.jsx("dd",{children:s?.nextRecoveryAt?`Next recovery at ${Yc(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:Qo(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:Qo(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:Qo(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:Qo(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:Yc(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:Yc(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}const Fu=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function pI(e){let n=null;for(const s of e){if(s.agent!=="executor"||s.type!=="text")continue;const a=s.text.match(/^Executor using model: (.+?)\/(.+)$/);a&&(n={provider:a[1],modelId:a[2]})}return n}function fI(e){let n=null;for(const s of e){if(s.agent!=="reviewer"||s.type!=="text")continue;const a=s.text.match(/^Reviewer using model: (.+?)\/(.+)$/);a&&(n={provider:a[1],modelId:a[2]})}return n}function kx(e){const n=e?.runtimeConfig??void 0,s=typeof n?.model=="string"?n.model.trim():"";if(s){const o=s.indexOf("/");if(o>0&&o<s.length-1)return{provider:s.slice(0,o),modelId:s.slice(o+1)}}const a=typeof n?.modelProvider=="string"?n.modelProvider.trim():"",r=typeof n?.modelId=="string"?n.modelId.trim():"";return{provider:a||void 0,modelId:r||void 0}}function gI(e,n,s,a){const r=pI(n);if(r)return r;if(Fu.has(e.status??"")||e.column==="in-progress"){const o=kx(s);if(o.provider&&o.modelId)return o}return Bg(e,a)}function bI(e,n,s,a){const r=fI(n);if(r)return r;if(Fu.has(e.status??"")||e.column==="in-progress"){const o=kx(s);if(o.provider&&o.modelId)return o}return Hg(e,a)}function xI(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 vI(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const a=xI(n);return a||qg(e,s)}function yI(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 wI(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 kI(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function jI(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 fp(e,n){return e.length>n?e.slice(0,n)+"…":e}function gp(e=[],n=[]){return e.length===n.length&&e.every((s,a)=>s===n[a])}function Qc(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function Xc(e){return e.trim()}function NI(e){const n=e.trim();return n.length>0?n:void 0}function Li(e){return typeof e=="string"&&oa.includes(e)?e:js}function Oi(e){return e==="fast"?"fast":"standard"}function SI(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function CI(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 EI=i.lazy(()=>gn(()=>import("./AgentDetailView-gy_5SUj2.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(e=>({default:e.AgentDetailView})));function _I(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:SI(e.sourceMetadata)};case"research":return{label:"Research",contextInfo:CI(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 Zc=200,MI=new Set(["triage","todo"]);function jx({task:e,projectId:n,tasks:s=[],onOpenDetail:a,onMoveTask:r,onDeleteTask:o,onMergeTask:l,onRetryTask:c,onResetTask:d,onDuplicateTask:u,onTaskUpdated:m,addToast:h,prAuthAvailable:f,initialTab:p="definition",mobileHeaderMode:g="close",embedded:x=!1,onRequestClose:w}){const[b,y]=i.useState(p),[S,k]=i.useState(()=>"prompt"in e?e:null),[C,v]=i.useState(()=>!("prompt"in e));i.useEffect(()=>{if("prompt"in e){k(e),v(!1);return}let z=!1;return v(!0),k(null),Sa(e.id,n).then(ue=>{z||(k(ue),v(!1))}).catch(()=>{z||v(!1)}),()=>{z=!0}},[e.id,n]);const j=S?{...S,...e,prompt:S.prompt,log:S.log}:{...e,prompt:""},P=e.status==="failed"||e.status==="stuck-killed"||e.status==="planning"||e.status==="needs-replan"||(e.stuckKillCount??0)>0||(e.recoveryRetryCount??0)>0||!!e.nextRecoveryAt,[U,E]=i.useState(null),[R,L]=i.useState(null),F=_I(j,{sourceAgentName:U?.name});i.useEffect(()=>{y(p)},[p]),i.useEffect(()=>{te(!1)},[e.id]);const[M,O]=i.useState("activity"),[q,te]=i.useState(!1),[Z,K]=i.useState(e.attachments||[]),[A,I]=i.useState(!1),[$,N]=i.useState(e.dependencies||[]),[G,ge]=i.useState(!1),[je,ke]=i.useState(""),[ne,qe]=i.useState(null),[ee,le]=i.useState([]),[se,re]=i.useState(!1),[J,B]=i.useState(!1),[ve,Ne]=i.useState(!1),[H,be]=i.useState(!1),[ce,Me]=i.useState(!1),[Le,He]=i.useState(j.prompt||""),[gt,Ue]=i.useState(""),[pe,Oe]=i.useState(!1),[ze,lt]=i.useState(""),[Be,ye]=i.useState(!1),[Y,_e]=i.useState(!1),[ct,pt]=i.useState(e.title||""),[de,Ve]=i.useState(e.description||""),[Ee,$e]=i.useState(e.dependencies||[]),[ut,ht]=i.useState(e.branch??""),[Se,we]=i.useState(e.baseBranch??""),[Ae,he]=i.useState(""),[We,me]=i.useState(""),[nt,Ct]=i.useState(""),[wt,$t]=i.useState(""),[Vt,Mt]=i.useState("default"),[Dt,Qt]=i.useState(void 0),[Kt,Bt]=i.useState(js),[on,fn]=i.useState(e.nodeId),[Jt,an]=i.useState(Oi(e.executionMode)),[zt,en]=i.useState(""),[Zt,dn]=i.useState(e.enabledWorkflowSteps||[]),[xe,Fe]=i.useState(e.sourceIssue?.provider??""),[Ke,et]=i.useState(e.sourceIssue?.repository??""),[Qe,It]=i.useState(e.sourceIssue?.externalIssueId??""),[St,Ht]=i.useState(e.sourceIssue?.url??""),[jt,ae]=i.useState([]),[De,At]=i.useState(!1),[Lt,Ft]=i.useState(Li(e.priority)),[Pe,dt]=i.useState(!1),[bt,_t]=i.useState(Oi(e.executionMode)),[Yt,Xt]=i.useState(!1),Te=i.useRef(!1),[Ye,Nt]=i.useState(!1),[Ut,tn]=i.useState(!1),[Xn,fe]=i.useState(!1),at=i.useRef(null),ot=i.useRef(null),rt=i.useRef(null),{getSlotsForId:mt}=Lg(n),ie=mt("task-detail-tab").map((z,ue)=>({entry:z,tabId:`plugin-${z.pluginId}-${ue}`})),it=typeof b=="string"&&b.startsWith("plugin-")?ie.find(z=>z.tabId===b)??null:null;i.useEffect(()=>(Te.current=!0,()=>{Te.current=!1}),[]);const[Gt,Cn]=i.useState(void 0),[fs,On]=i.useState([]),[jn,zn]=i.useState(!1),[hn,Et]=i.useState(e.enabledWorkflowSteps||[]),En=e.column==="in-progress"||Fu.has(e.status);i.useEffect(()=>{pt(e.title||""),Ve(e.description||""),ht(e.branch??""),we(e.baseBranch??""),Fe(e.sourceIssue?.provider??""),et(e.sourceIssue?.repository??""),It(e.sourceIssue?.externalIssueId??""),Ht(e.sourceIssue?.url??""),an(Oi(e.executionMode)),fe(!1),_e(!1)},[e.id,e.title,e.description,e.branch,e.baseBranch,e.sourceIssue,e.executionMode]),i.useEffect(()=>{Et(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),i.useEffect(()=>{Ft(Li(e.priority))},[e.id,e.priority]),i.useEffect(()=>{_t(Oi(e.executionMode))},[e.id,e.executionMode]),i.useEffect(()=>{let z=!1;return Xl(n).then(ue=>{z||Cn(ue)}).catch(()=>{}),()=>{z=!0}},[n]),i.useEffect(()=>{if(b!=="workflow")return;let z=!1;return zn(!0),UN(e.id,n).then(ue=>{z||On(ue)}).catch(ue=>{z||h(`Failed to load workflow results: ${Re(ue)}`,"error")}).finally(()=>{z||zn(!1)}),()=>{z=!0}},[b,e.id,n,h]),i.useEffect(()=>{if(b!=="workflow")return;const z=n?`?projectId=${encodeURIComponent(n)}`:"",ue=Xe=>{try{const ft=JSON.parse(Xe.data);ft.id===e.id&&Array.isArray(ft.workflowStepResults)&&On(ft.workflowStepResults)}catch{}};return ii(`/api/events${z}`,{events:{"task:updated":ue}})},[b,e.id,n]),i.useEffect(()=>{G||ke("")},[G]),i.useEffect(()=>{if(!e.assignedAgentId){qe(null);return}const z=ee.find(Xe=>Xe.id===e.assignedAgentId);if(z){qe(z);return}let ue=!1;return Id(e.assignedAgentId,n).then(Xe=>{ue||qe(Xe)}).catch(()=>{ue||qe(null)}),()=>{ue=!0}},[e.assignedAgentId,n,ee]),i.useEffect(()=>{if(!e.sourceAgentId){E(null);return}const z=ee.find(Xe=>Xe.id===e.sourceAgentId);if(z){E(z);return}let ue=!1;return Promise.resolve(Id(e.sourceAgentId,n)).then(Xe=>{ue||E(Xe??null)}).catch(()=>{ue||E(null)}),()=>{ue=!0}},[e.sourceAgentId,n,ee]),i.useEffect(()=>{re(!1)},[e.id]),i.useEffect(()=>{if(!(Ye||Ut))return;const ue=Xe=>{const ft=Xe.target,qt=at.current?.contains(ft),Ze=rt.current?.contains(ft);!qt&&Ye&&Nt(!1),!Ze&&Ut&&tn(!1)};return document.addEventListener("mousedown",ue),()=>document.removeEventListener("mousedown",ue)},[Ye,Ut]),i.useEffect(()=>{if(!(Ye||Ut))return;const ue=Xe=>{Xe.key==="Escape"&&(Xe.stopPropagation(),Ye&&Nt(!1),Ut&&tn(!1))};return document.addEventListener("keydown",ue),()=>document.removeEventListener("keydown",ue)},[Ye,Ut]),i.useEffect(()=>{Me(!1),He(j.prompt||""),Ue("")},[e.id,j.prompt]);const yn=MI.has(e.column)&&!De,ls=i.useCallback(()=>{if(!yn)return;_e(!0),pt(e.title||""),Ve(e.description||""),$e(e.dependencies||[]),ht(e.branch??""),we(e.baseBranch??"");const z=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",ue=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",Xe=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";he(z),me(ue),Ct(Xe),$t(e.thinkingLevel??""),fn(e.nodeId),Mt(z||ue||Xe?"custom":"default"),en(""),dn(e.enabledWorkflowSteps||[]),an(Oi(e.executionMode)),Fe(e.sourceIssue?.provider??""),et(e.sourceIssue?.repository??""),It(e.sourceIssue?.externalIssueId??""),Ht(e.sourceIssue?.url??""),ae([]),Qt(e.reviewLevel),Bt(Li(e.priority))},[yn,e]),cs=i.useCallback(()=>{_e(!1),pt(e.title||""),Ve(e.description||""),$e(e.dependencies||[]),ht(e.branch??""),we(e.baseBranch??""),fn(e.nodeId),Fe(e.sourceIssue?.provider??""),et(e.sourceIssue?.repository??""),It(e.sourceIssue?.externalIssueId??""),Ht(e.sourceIssue?.url??""),Bt(Li(e.priority)),an(Oi(e.executionMode)),jt.forEach(z=>URL.revokeObjectURL(z.previewUrl)),ae([])},[e.title,e.description,e.dependencies,e.nodeId,e.priority,e.executionMode,jt]),[Hn,qn]=i.useState("idle"),wn=i.useRef(null),Zn=i.useRef(0),_n=i.useCallback(z=>{const ue={},Xe=ct.trim(),ft=de.trim();Xe&&Xe!==(e.title??"")&&(ue.title=Xe),z&&ft&&ft!==(e.description??"")&&(ue.description=ft),gp(Ee,e.dependencies??[])||(ue.dependencies=Ee),gp(Zt,e.enabledWorkflowSteps??[])||(ue.enabledWorkflowSteps=Zt);const qt=ut.trim()||null,Ze=e.branch??null;qt!==Ze&&(ue.branch=qt);const st=Se.trim()||null,Ot=e.baseBranch??null;st!==Ot&&(ue.baseBranch=st);const xn=Qc(Ae),Xs=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";Ae!==Xs&&(ue.modelProvider=xn?.provider??null,ue.modelId=xn?.modelId??null);const ci=Qc(We),as=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";We!==as&&(ue.validatorModelProvider=ci?.provider??null,ue.validatorModelId=ci?.modelId??null);const Jn=Qc(nt),un=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";nt!==un&&(ue.planningModelProvider=Jn?.provider??null,ue.planningModelId=Jn?.modelId??null);const Di=e.thinkingLevel??"";wt!==Di&&(ue.thinkingLevel=wt!==""?wt:null),(e.nodeId??void 0)!==on&&(ue.nodeId=on??null),Dt!==e.reviewLevel&&(ue.reviewLevel=Dt),Kt!==Li(e.priority)&&(ue.priority=Kt),Jt!==Oi(e.executionMode)&&(ue.executionMode=Jt==="fast"?"fast":null);const Es=Xc(xe),qs=Xc(Ke),Ji=Xc(Qe),fa=NI(St);if(Es.length===0&&qs.length===0&&Ji.length===0&&!fa)e.sourceIssue&&(ue.sourceIssue=null);else{if(!Es||!qs||!Ji)return{updates:null,error:"Source issue provider, repository, and issue identifier are required"};const gv=Number.parseInt(Ji,10),cc=e.sourceIssue?.issueNumber??gv;if(!Number.isFinite(cc)||cc<=0)return{updates:null,error:"Source issue identifier must be numeric for new metadata"};const Va={provider:Es,repository:qs,externalIssueId:Ji,issueNumber:cc,...fa?{url:fa}:{}},Wa=e.sourceIssue;(!Wa||Wa.provider!==Va.provider||Wa.repository!==Va.repository||Wa.externalIssueId!==Va.externalIssueId||Wa.issueNumber!==Va.issueNumber||(Wa.url??void 0)!==Va.url)&&(ue.sourceIssue=Va)}return{updates:ue,error:null}},[Se,ut,Ee,de,Jt,Ae,on,nt,Kt,Dt,Zt,Qe,xe,Ke,St,wt,ct,We,e]),ss=i.useCallback(async z=>{const{updates:ue,error:Xe}=_n(z);if(!ue)return qn("error"),Xe&&h(`Failed to update ${e.id}: ${Xe}`,"error"),!1;if(Object.keys(ue).length===0)return!0;const ft=++Zn.current;At(!0),qn("saving");try{const qt=await mi(e.id,ue,n);return ft!==Zn.current?void 0:(m?.(qt),qn("saved"),!0)}catch(qt){return ft===Zn.current&&(qn("error"),h(`Failed to update ${e.id}: ${Re(qt)}`,"error")),!1}finally{Te.current&&ft===Zn.current&&At(!1)}},[h,_n,m,n,e.id]),Ns=i.useCallback(async z=>{await ss(!0)},[ss]),es=i.useCallback(async()=>{await ss(!0)&&(h(`Updated ${e.id}`,"success"),Te.current&&_e(!1))},[h,ss,e.id]);i.useEffect(()=>{if(Y)return wn.current&&clearTimeout(wn.current),wn.current=setTimeout(()=>{ss(!1)},700),()=>{wn.current&&(clearTimeout(wn.current),wn.current=null)}},[Y,ct,Ee,ut,Se,Ae,We,nt,wt,on,Dt,Kt,Jt,Zt,xe,Ke,Qe,St,ss]);const ks=i.useCallback(async z=>{const ue=Li(z),Xe=Li(e.priority);if(ue===Xe){Ft(Xe);return}const ft=Lt;Ft(ue),dt(!0);try{const qt=await mi(e.id,{priority:ue},n);Ft(Li(qt.priority)),m?.(qt),h(`Priority updated to ${Li(qt.priority)}`,"success")}catch(qt){Ft(ft),h(`Failed to update ${e.id}: ${Re(qt)}`,"error")}finally{Te.current&&dt(!1)}},[e.id,e.priority,n,Lt,m,h]),Is=i.useCallback(async()=>{const ue=Oi(e.executionMode)==="fast"?"standard":"fast",Xe=bt;_t(ue),Xt(!0);try{const ft=await mi(e.id,{executionMode:ue==="fast"?"fast":null},n),qt=Oi(ft.executionMode);_t(qt),m?.(ft),h(`Execution mode updated to ${qt}`,"success")}catch(ft){_t(Xe),h(`Failed to update ${e.id}: ${Re(ft)}`,"error")}finally{Te.current&&Xt(!1)}},[e.id,e.executionMode,n,bt,m,h]),Ss=i.useCallback(z=>{Y&&(z.key==="Escape"?(z.preventDefault(),cs()):z.key==="Enter"&&(z.ctrlKey||z.metaKey)&&(z.preventDefault(),es()))},[Y,cs,es]);i.useEffect(()=>{if(Y)return document.addEventListener("keydown",Ss),()=>document.removeEventListener("keydown",Ss)},[Y,Ss]);const X=i.useRef(null),{nodes:_}=tc(),{confirm:oe}=ai(),{entries:D,loading:Q,loadMore:Ce,hasMore:Je,total:kt,loadingMore:Tt}=gx(e.id,b==="logs"&&M==="agent-log",n),Pt=i.useCallback(()=>{w?.()},[w]);i.useEffect(()=>{if(x)return;const z=ue=>{ue.key==="Escape"&&!Y&&Pt()};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[x,Pt,Y]);const ln=i.useCallback(async z=>{try{const ue=e.steps.some(qt=>qt.status!=="pending"),Xe=(z==="todo"||z==="triage")&&ue;let ft;if(Xe){if(await oe({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))ft={preserveProgress:!0};else if(!await oe({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,z,ft),Pt(),h(`Moved to ${ns[z]}`,"success")}catch(ue){h(Re(ue),"error")}},[e.id,e.steps,r,Pt,h,oe]),ts=i.useCallback(async()=>{if(await oe({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0}))try{await o(e.id),Pt(),h(`Deleted ${e.id}`,"info")}catch(ue){const Xe=jI(ue);if(!Xe||Xe.dependentIds.length===0){h(Re(ue),"error");return}const ft=Xe.dependentIds.join(", ");if(!await oe({title:"Force Delete Task",message:`${e.id} is a dependency of ${ft}.
|
|
685
|
+
|
|
686
|
+
Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await o(e.id,{removeDependencyReferences:!0}),Pt(),h(`Deleted ${e.id} after removing dependency references`,"info")}catch(Ze){h(Re(Ze),"error")}}},[e.id,o,Pt,h,oe]),Pn=i.useCallback(async()=>{await oe({title:"Merge Task",message:`Merge ${e.id} into the current branch?`})&&(Pt(),h(`Merging ${e.id}...`,"info"),l(e.id).then(ue=>{const Xe=ue.merged?`Merged ${e.id} (branch: ${ue.branch})`:`Closed ${e.id} (${ue.error||"no branch to merge"})`;h(Xe,"success")}).catch(ue=>{h(Re(ue),"error")}))},[e.id,l,Pt,h,oe]),Fn=i.useCallback(()=>{c&&(Pt(),c(e.id).then(()=>{h(`Retried ${e.id}`,"success")}).catch(z=>{h(Re(z),"error")}))},[e.id,c,Pt,h]),Un=i.useCallback(()=>{d&&window.confirm(`This will erase all progress for ${e.id} and start the task from scratch. Continue?`)&&(Pt(),d(e.id).then(()=>{h(`Reset ${e.id} — fresh run will be allocated`,"success")}).catch(z=>{h(Re(z),"error")}))},[e.id,d,Pt,h]),gs=i.useCallback(async()=>{if(!(!u||!await oe({title:"Duplicate Task",message:`Duplicate ${e.id}? This will create a new task in Triage with the same description and prompt.`})))try{const ue=await u(e.id);Pt(),h(`Duplicated ${e.id} → ${ue.id}`,"success")}catch(ue){h(Re(ue),"error")}},[e.id,u,Pt,h,oe]),Ln=i.useCallback(async()=>{try{e.paused?(await Hk(e.id,n),h(`Unpaused ${e.id}`,"success")):(await kg(e.id,n),h(`Paused ${e.id}`,"success")),Pt()}catch(z){h(Re(z),"error")}},[e.id,e.paused,Pt,h]),Vn=i.useCallback(async()=>{try{await Kk(e.id,n),h(`Plan approved — ${e.id} moved to Todo`,"success"),Pt()}catch(z){h(Re(z),"error")}},[e.id,Pt,h]),Wn=i.useCallback(async()=>{if(await oe({title:"Reject Plan",message:"Reject this plan? The specification will be discarded and regenerated.",danger:!0}))try{await Gk(e.id,n),h(`Plan rejected — ${e.id} returned to Planning for replanning`,"info"),Pt()}catch(ue){h(Re(ue),"error")}},[e.id,Pt,h,oe]),Kn=i.useCallback(async()=>{if(await oe({title:"Rebuild Plan",message:"Rebuild the plan for this task? The task will move to planning for replanning."}))try{await aj(e.id,n),Pt(),h(`Replanning ${e.id}...`,"info")}catch(ue){h(Re(ue),"error")}},[e.id,n,Pt,h,oe]),Bn=i.useCallback(()=>{Oe(!0),lt("")},[]),Nn=i.useCallback(()=>{Nt(!1),tn(!1)},[]),Gn=i.useCallback(z=>{Nn(),ln(z)},[Nn]),ds=i.useCallback(z=>{Nn(),z()},[Nn]),Ts=i.useCallback(()=>{Nn(),Pn()},[Nn,Pn]),Ri=i.useCallback(()=>{Oe(!1),lt(""),ye(!1)},[]),ca=i.useCallback(async()=>{if(!ze.trim()){h("Please enter feedback describing what needs refinement","error");return}if(ze.length>2e3){h("Feedback must be 2000 characters or less","error");return}ye(!0);try{const z=await rj(e.id,ze.trim(),n);h(`Refinement task created: ${z.id}`,"success"),Pt()}catch(z){h(Re(z),"error")}finally{ye(!1)}},[e.id,ze,h,Pt]),ri=i.useCallback(async z=>{I(!0);try{const ue=await Zl(e.id,z,n);K(Xe=>[...Xe,ue]),h("Screenshot attached","success")}catch(ue){h(Re(ue),"error")}finally{I(!1)}},[e.id,h]),Ta=i.useCallback(async z=>{const ue=z.target.files?.[0];ue&&(await ri(ue),X.current&&(X.current.value=""))},[ri]);i.useEffect(()=>{const z=ue=>{const Xe=ue.clipboardData?.items;if(Xe)for(let ft=0;ft<Xe.length;ft++){const qt=Xe[ft];if(qt.type.startsWith("image/")){const Ze=qt.getAsFile();if(Ze){ue.preventDefault(),ri(Ze);return}}}};return document.addEventListener("paste",z),()=>document.removeEventListener("paste",z)},[ri]);const $a=i.useCallback(z=>{z.preventDefault()},[]),Qs=i.useCallback(z=>{z.preventDefault();const ue=z.dataTransfer.files;for(let Xe=0;Xe<ue.length;Xe++){const ft=ue[Xe];if(ft.type.startsWith("image/")){ri(ft);return}}},[ri]),oi=i.useCallback(async z=>{try{await Qk(e.id,z,n),K(ue=>ue.filter(Xe=>Xe.filename!==z)),h("Attachment deleted","info")}catch(ue){h(Re(ue),"error")}},[e.id,h]),Ii=i.useCallback(async z=>{const ue=hn;Et(z);try{const Xe=await mi(e.id,{enabledWorkflowSteps:z},n);h("Workflow steps updated","success"),m?.(Xe)}catch(Xe){Et(ue),h(`Failed to update workflow steps: ${Re(Xe)}`,"error")}},[e.id,n,hn,m,h]),da=i.useCallback(async()=>{B(!0);try{const z=await Nr(void 0,n);le(z),re(!0)}catch(z){h(`Failed to load agents: ${Re(z)}`,"error"),re(!1)}finally{B(!1)}},[n,h]),Da=i.useCallback(async z=>{try{const ue=await gm(e.id,z,n),Xe=ee.find(ft=>ft.id===z)??null;qe(Xe||(ft=>ft?.id===z?ft:null)),re(!1),m?.(ue),h("Assigned agent updated","success")}catch(ue){h(`Failed to assign agent: ${Re(ue)}`,"error")}},[e.id,n,ee,m,h]),La=i.useCallback(async()=>{try{const z=await gm(e.id,null,n);qe(null),re(!1),m?.(z),h("Agent unassigned","success")}catch(z){h(`Failed to unassign agent: ${Re(z)}`,"error")}},[e.id,n,m,h]),ua=i.useCallback(async z=>{const ue=[...$,z];N(ue);try{await mi(e.id,{dependencies:ue},n)}catch(Xe){N($),h(Re(Xe),"error")}},[e.id,$,h]),ma=i.useCallback(async(z,ue)=>{z.stopPropagation();const Xe=$.filter(ft=>ft!==ue);N(Xe);try{await mi(e.id,{dependencies:Xe},n)}catch(ft){N($),h(Re(ft),"error")}},[e.id,$,h]),Ti=i.useCallback(async z=>{try{const ue=await Sa(z,n);a(ue)}catch{h(`Failed to load dependency ${z}`,"error")}},[a,h]),Oa=i.useCallback(async z=>{Ne(!0);try{await mi(j.id,{prompt:z},n),h("Spec updated","success"),S&&(S.prompt=z)}catch(ue){throw h(Re(ue),"error"),ue}finally{Ne(!1)}},[j,S,h]),ha=i.useCallback(async z=>{be(!0);try{await ij(e.id,z,n),h("AI revision requested. Task moved to planning.","success"),Pt()}catch(ue){const Xe=Re(ue);Xe.includes("done")||Xe.includes("archived")?h("Cannot request revision: Task must be in 'triage', 'todo', 'in-progress', or 'in-review' column.","error"):h(Xe,"error")}finally{be(!1)}},[e.id,h,Pt]),Mr=i.useCallback(()=>{Me(!0),He(j.prompt||""),Ue("")},[j.prompt]),li=i.useCallback(()=>{Me(!1),He(j.prompt||""),Ue("")},[j.prompt]),Hs=i.useCallback(async()=>{if(Le===(j.prompt||"")){li();return}Me(!1);try{await Oa(Le)}catch(z){throw Me(!0),z}},[Le,j.prompt,Oa,li]),za=i.useCallback(async()=>{gt.trim()&&await ha(gt.trim())},[gt,ha]),Fa=i.useCallback(z=>{z.key==="Escape"?(z.preventDefault(),li()):z.key==="Enter"&&(z.ctrlKey||z.metaKey)&&(z.preventDefault(),Hs())},[li,Hs]),$i=s.filter(z=>z.id!==e.id&&!$.includes(z.id)).sort((z,ue)=>{const Xe=ue.createdAt.localeCompare(z.createdAt);if(Xe!==0)return Xe;const ft=parseInt(z.id.slice(z.id.lastIndexOf("-")+1),10)||0;return(parseInt(ue.id.slice(ue.id.lastIndexOf("-")+1),10)||0)-ft}),Ua=ne?.name??e.assignedAgentId??null,Ba=i.useMemo(()=>{const z=[];return j.modelProvider&&z.push(j.modelProvider),j.validatorModelProvider&&!z.includes(j.validatorModelProvider)&&z.push(j.validatorModelProvider),j.planningModelProvider&&!z.includes(j.planningModelProvider)&&z.push(j.planningModelProvider),z},[j.modelProvider,j.validatorModelProvider,j.planningModelProvider]),Ha=Td[e.column]||[],yi=["todo","in-progress"],pa=e.column==="in-review"?yi:Ha,us=pa[0],Ki=pa.slice(1),Cs=Ki.length>0,Gi=i.useCallback(()=>{Nt(!1),ot.current?.focus()},[]),qa=i.useCallback(z=>{if(!Cs){us&&Gn(us);return}const ue=z.currentTarget.querySelector(".detail-move-btn__arrow");if(!!(z.target instanceof Element&&z.target.closest(".detail-move-btn__arrow")||ue&&z.clientX>0&&z.clientX>=ue.getBoundingClientRect().left)){Nt(ft=>!ft),tn(!1);return}us&&Gn(us)},[Cs,us,Gn]),Ge=i.useCallback(z=>{!Cs||!(z.key==="ArrowDown"||z.altKey&&z.key==="ArrowDown")||(z.preventDefault(),Nt(!0),tn(!1))},[Cs]),Rt=i.useCallback(z=>{z.key==="Escape"&&(z.preventDefault(),z.stopPropagation(),Gi())},[Gi]);i.useEffect(()=>{if(!Ye)return;at.current?.querySelector(".detail-move-menu-item")?.focus()},[Ye]);const cn={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…","merging-fix":"Merging fixes…"},is=e.status?cn[e.status]:void 0,Rn=Gt?.mergeStrategy??"direct",$s=Gt?.autoMerge??!1,V=Rn==="pull-request"&&!$s;let Ie="Merge & Close";return V&&!is&&(e.prInfo?e.prInfo.status==="open"?Ie="Check PR Status":e.prInfo.status==="merged"&&(Ie="Finish & Close"):Ie="Start PR Review"),t.jsxs("div",{className:x?"task-detail-content task-detail-content--embedded":"task-detail-content",onDragOver:$a,onDrop:Qs,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:ns[e.column]})]}),t.jsxs("div",{className:"modal-header-actions",children:[!Y&&yn&&t.jsx("button",{className:"modal-edit-btn",onClick:ls,title:"Edit task","aria-label":"Edit task",children:t.jsx(Ds,{size:14})}),!x&&g==="back"&&t.jsxs("button",{className:"modal-close task-detail-mobile-back",onClick:Pt,"aria-label":"Back to task list",type:"button",children:[t.jsx(Aa,{"aria-hidden":"true"}),t.jsx("span",{children:"Back"})]}),!x&&g!=="back"&&t.jsx("button",{className:"modal-close",onClick:Pt,"aria-label":"Close",type:"button",children:"×"})]})]}),t.jsxs("div",{className:`detail-body${b==="logs"&&M==="agent-log"&&!Y?" detail-body--agent-log":""}`,children:[Y?t.jsx("div",{className:"modal-edit-form",children:t.jsx(wx,{mode:"edit",title:ct,onTitleChange:pt,description:de,onDescriptionChange:Ve,dependencies:Ee,onDependenciesChange:$e,branch:ut,onBranchChange:ht,baseBranch:Se,onBaseBranchChange:we,executorModel:Ae,onExecutorModelChange:he,validatorModel:We,onValidatorModelChange:me,planningModel:nt,onPlanningModelChange:Ct,thinkingLevel:wt,onThinkingLevelChange:$t,presetMode:Vt,onPresetModeChange:Mt,selectedPresetId:zt,onSelectedPresetIdChange:en,selectedWorkflowSteps:Zt,onWorkflowStepsChange:dn,pendingImages:jt,onImagesChange:ae,tasks:s.filter(z=>z.id!==e.id),projectId:n,disabled:De,addToast:h,isActive:Y,onAutoSaveDescription:Ns,reviewLevel:Dt,onReviewLevelChange:Qt,priority:Kt,onPriorityChange:Bt,nodeId:on,onNodeIdChange:fn,nodeOptions:_,nodeOverrideDisabled:En,nodeOverrideDisabledReason:En?"Execution node override is locked while a task is active/in progress.":void 0,executionMode:Jt,onExecutionModeChange:an,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:xe,onChange:z=>Fe(z.target.value),disabled:De,"data-testid":"task-source-provider-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Repository (e.g. owner/repo)",value:Ke,onChange:z=>et(z.target.value),disabled:De,"data-testid":"task-source-repository-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:Qe,onChange:z=>It(z.target.value),disabled:De,"data-testid":"task-source-external-id-input"}),t.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:St,onChange:z=>Ht(z.target.value),disabled:De,"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 z=e.title||e.description||e.id,ue=!q&&z.length>Zc;return t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"detail-title",children:ue?z.slice(0,Zc)+"…":z}),z.length>Zc&&t.jsx("button",{className:"detail-description-toggle",onClick:()=>te(!q),children:q?"Show less":"Show more"})]})})(),t.jsxs("div",{className:"detail-meta",children:[t.jsxs("label",{className:`card-priority-badge card-priority-badge--${Lt} detail-priority-chip ${Pe?"detail-priority-chip--saving":""}`,children:[t.jsx("span",{children:"Priority:"}),t.jsx("select",{className:"detail-priority-select",value:Lt,onChange:z=>{ks(z.target.value)},disabled:Pe,"aria-label":"Task priority",children:oa.map(z=>t.jsx("option",{value:z,children:z},z))})]}),t.jsxs("button",{type:"button",className:`btn btn-sm detail-execution-mode-toggle ${bt==="fast"?"detail-execution-mode-toggle--fast":""} ${Yt?"detail-execution-mode-toggle--saving":""}`,onClick:()=>{Is()},disabled:Yt,"aria-label":`Execution mode: ${bt}`,"aria-pressed":bt==="fast",children:[t.jsx(Qn,{"aria-hidden":"true"}),t.jsx("span",{children:bt==="fast"?"Fast":"Standard"})]}),F&&t.jsxs("div",{className:"detail-provenance",children:[t.jsx(Us,{"aria-hidden":"true"}),t.jsxs("span",{children:[j.sourceType==="agent_heartbeat"?t.jsxs(t.Fragment,{children:["Created by"," ",F.sourceAgentId?t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>L(F.sourceAgentId),children:F.label}):F.label]}):t.jsxs(t.Fragment,{children:["Created via ",F.label]}),F.parentTaskId&&t.jsxs(t.Fragment,{children:[" ","of"," ",t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>Ti(F.parentTaskId),children:F.parentTaskId})]}),F.contextInfo?` (${F.contextInfo})`:""]})]}),(e.prInfo?.number||e.mergeDetails?.prNumber)&&t.jsxs("div",{className:"detail-provenance detail-pr-link-row",children:[t.jsx(Us,{"aria-hidden":"true"}),t.jsxs("span",{children:["PR"," ",e.prInfo?.url?t.jsxs("a",{className:"detail-provenance-link",href:e.prInfo.url,target:"_blank",rel:"noopener noreferrer",children:["#",e.prInfo.number]}):t.jsxs("span",{children:["#",e.prInfo?.number??e.mergeDetails?.prNumber]})]})]}),t.jsxs("div",{className:"detail-timestamps",children:["Created ",new Date(e.createdAt).toLocaleDateString()," · Updated"," ",new Date(e.updatedAt).toLocaleDateString()]})]})]}),e.status==="failed"&&e.error&&t.jsxs("div",{className:"detail-error-alert",children:[t.jsx("span",{className:"detail-error-icon",children:"⚠"}),t.jsxs("div",{className:"detail-error-content",children:[t.jsx("div",{className:"detail-error-title",children:"Task Failed"}),t.jsx("div",{className:"detail-error-message",children:e.error})]})]}),!Y&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"detail-tabs",children:[t.jsx("button",{className:`detail-tab${b==="definition"?" detail-tab-active":""}`,onClick:()=>y("definition"),children:"Definition"}),t.jsx("button",{className:`detail-tab${b==="logs"?" detail-tab-active":""}`,onClick:()=>y("logs"),children:"Logs"}),(e.column==="in-progress"||e.column==="in-review"||e.column==="done")&&t.jsx("button",{className:`detail-tab${b==="changes"?" detail-tab-active":""}`,onClick:()=>y("changes"),children:"Changes"}),t.jsx("button",{className:`detail-tab${b==="review"?" detail-tab-active":""}`,onClick:()=>y("review"),children:"Review"}),t.jsx("button",{className:`detail-tab${b==="comments"?" detail-tab-active":""}`,onClick:()=>y("comments"),children:"Comments"}),t.jsx("button",{className:`detail-tab${b==="documents"?" detail-tab-active":""}`,onClick:()=>y("documents"),children:"Documents"}),t.jsx("button",{className:`detail-tab${b==="model"?" detail-tab-active":""}`,onClick:()=>y("model"),children:"Model"}),t.jsx("button",{className:`detail-tab${b==="workflow"?" detail-tab-active":""}`,onClick:()=>y("workflow"),children:"Workflow"}),t.jsx("button",{className:`detail-tab${b==="stats"?" detail-tab-active":""}`,onClick:()=>y("stats"),children:"Stats"}),t.jsx("button",{className:`detail-tab${b==="routing"?" detail-tab-active":""}`,onClick:()=>y("routing"),children:"Routing"}),ie.map(({entry:z,tabId:ue})=>t.jsx("button",{className:`detail-tab${b===ue?" detail-tab-active":""}`,onClick:()=>y(ue),children:z.slot.label},`plugin-tab-${z.pluginId}-${ue}`))]}),b==="workflow"?t.jsx("div",{className:"detail-section",children:t.jsx(sI,{taskId:e.id,results:fs,loading:jn,enabledWorkflowSteps:hn,canEdit:yn,projectId:n,isTaskInProgress:e.column==="in-progress"&&e.status!=="paused",onWorkflowStepsChange:Ii})}):b==="model"?t.jsx("div",{className:"detail-section",children:t.jsx(TR,{task:e,addToast:h,onTaskUpdated:m,settings:Gt})}):b==="logs"?t.jsxs("div",{className:`detail-section${M==="agent-log"?" detail-section--agent-log":""}`,children:[t.jsxs("div",{className:"log-subview-toggle",children:[t.jsx("button",{className:`log-subview-btn${M==="activity"?" log-subview-btn-active":""}`,onClick:()=>O("activity"),children:"Activity"}),t.jsx("button",{className:`log-subview-btn${M==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>O("agent-log"),children:"Agent Log"})]}),M==="agent-log"?t.jsx(MR,{entries:D,loading:Q,executorModel:gI(e,D,ne,Gt),validatorModel:bI(e,D,ne,Gt),planningModel:vI(e,D,Gt),hasMore:Je,onLoadMore:Ce,loadingMore:Tt,totalCount:kt}):t.jsxs("div",{className:"detail-activity",children:[t.jsx("h4",{children:"Activity"}),j.activityLogTruncatedCount?t.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",j.log.length," activity entries."]}):null,j.log&&j.log.length>0?t.jsx("div",{className:"detail-activity-list",children:[...j.log].reverse().map((z,ue)=>t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-timestamp",children:wI(z.timestamp)}),t.jsx("span",{className:"detail-log-action",children:z.action})]}),z.outcome&&t.jsx("div",{className:"detail-log-outcome",children:z.outcome})]},ue))}):t.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):b==="changes"?t.jsx(GR,{taskId:e.id,worktree:e.worktree,projectId:n,column:e.column,mergeDetails:e.mergeDetails,modifiedFiles:e.modifiedFiles}):b==="review"?t.jsx(HR,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):b==="comments"?t.jsx(zR,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):b==="documents"?t.jsx(uI,{taskId:e.id,addToast:h,projectId:n,onTaskUpdated:m,canEdit:yn}):it?t.jsx("div",{className:"detail-section",children:t.jsx(ta,{slotId:"task-detail-tab",projectId:n,pluginIds:[it.entry.pluginId]})}):b==="stats"?t.jsx("div",{className:"detail-section",children:t.jsx(hI,{tokenUsage:j.tokenUsage,loading:C,task:j})}):b==="routing"?t.jsx("div",{className:"detail-section",children:t.jsx(oI,{task:e,settings:Gt,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(bi,{remarkPlugins:[xi],children:e.summary})})]}),t.jsx(VR,{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(Us,{"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":Xn,"aria-label":Xn?"Collapse source issue details":"Expand source issue details",onClick:()=>fe(z=>!z),children:t.jsx(Mn,{size:16,className:Xn?"detail-source-chevron--expanded":void 0})})]}),Xn&&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:[Ba.length>0&&t.jsx("span",{className:"detail-provider-icons","data-testid":"detail-provider-icons",children:Ba.map(z=>t.jsx(Sn,{provider:z,size:"sm"},z))}),t.jsxs("span",{className:"detail-meta-label",children:[t.jsx(Tn,{size:14,className:"detail-meta-label-icon"}),"Agent"]})]}),t.jsxs("div",{className:"detail-agent-actions",children:[Ua?t.jsxs("span",{className:"detail-agent-chip",children:[t.jsx(Tn,{size:14}),Ua,t.jsx("button",{className:"detail-agent-clear",onClick:()=>void La(),title:"Unassign agent",children:t.jsx(nn,{size:12})})]}):t.jsx("button",{className:"btn btn-sm",onClick:()=>{se?re(!1):da()},children:"Assign Agent"}),se&&t.jsxs("div",{className:"agent-picker-dropdown",children:[J&&t.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!J&&ee.map(z=>t.jsxs("button",{className:`agent-picker-item${e.assignedAgentId===z.id?" selected":""}`,onClick:()=>void Da(z.id),children:[t.jsx(Tn,{size:14}),t.jsx("span",{className:"agent-picker-name",children:z.name}),t.jsx("span",{className:"agent-picker-role",children:z.role})]},z.id)),!J&&ee.length===0&&t.jsx("div",{className:"agent-picker-empty",children:"No agents available"})]})]})]})}),t.jsxs("div",{className:"detail-section detail-step-progress",children:[t.jsx("h4",{children:"Progress"}),j.steps&&j.steps.length>0?t.jsxs("div",{className:"step-progress-wrapper",children:[t.jsx("div",{className:"step-progress-bar",children:j.steps.map((z,ue)=>t.jsx("div",{className:`step-progress-segment step-progress-segment--${z.status}`,"data-tooltip":`${z.name} (${z.status})`,style:{backgroundColor:yI(z.status)}},ue))}),t.jsxs("span",{className:"step-progress-label",children:[j.steps.filter(z=>z.status==="done").length,"/",j.steps.length," step",j.steps.length===1?"":"s"]})]}):t.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),t.jsxs("div",{className:"detail-section",children:[!ce&&t.jsx("div",{className:"detail-spec-edit-trigger",children:t.jsx("button",{className:"btn btn-sm",onClick:Mr,children:"Edit"})}),ce?t.jsxs("div",{className:"spec-editor-edit-mode",children:[t.jsx("textarea",{className:"spec-editor-textarea",value:Le,onChange:z=>He(z.target.value),onKeyDown:Fa,disabled:ve,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:li,disabled:ve,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Hs(),disabled:Le===(j.prompt||"")||ve,children:ve?"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:gt,onChange:z=>Ue(z.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:H,rows:4,maxLength:2e3}),t.jsxs("div",{className:"spec-editor-revision-actions",children:[t.jsxs("span",{className:"spec-editor-char-count",children:[gt.length,"/2000"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void za(),disabled:!gt.trim()||H,children:H?"Requesting…":"Request AI Revision"})]})]})]}):C?t.jsx("div",{className:"spec-loading",children:"Loading specification…"}):j.prompt?t.jsx("div",{className:"markdown-body",children:t.jsx(bi,{remarkPlugins:[xi],children:j.prompt.replace(/^#\s+[^\n]*\n+/,"")})}):t.jsx("div",{className:"detail-prompt",children:"(no prompt)"})]}),t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Attachments"}),Z.length>0?t.jsx("div",{className:"detail-attachments-grid",children:Z.map(z=>{const ue=Mi(`/api/tasks/${e.id}/attachments/${z.filename}`);return t.jsxs("div",{className:"detail-attachment-card",children:[t.jsx("a",{className:"detail-attachment-link",href:ue,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{src:ue,alt:z.originalName,className:"detail-attachment-image"})}),t.jsxs("div",{className:"detail-attachment-meta",children:[z.originalName," (",kI(z.size),")"]}),t.jsx("button",{className:"detail-attachment-delete",onClick:()=>oi(z.filename),title:"Delete attachment",children:"×"})]},z.filename)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no attachments)"}),t.jsx("input",{className:"detail-hidden-file-input",ref:X,type:"file",accept:"image/*",onChange:Ta}),t.jsx("button",{className:"btn btn-sm",onClick:()=>X.current?.click(),disabled:A,children:A?"Uploading…":"Attach Screenshot"})]}),t.jsxs("div",{className:"detail-deps",children:[t.jsx("h4",{children:"Dependencies"}),$.length>0?t.jsx("ul",{className:"detail-dep-list",children:$.map(z=>{const ue=s.find(ft=>ft.id===z),Xe=ue?.title||ue?.description||z;return t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>Ti(z),onKeyDown:ft=>{(ft.key==="Enter"||ft.key===" ")&&(ft.preventDefault(),Ti(z))},role:"link",tabIndex:0,title:`Click to view ${z}`,children:[t.jsx("span",{className:"detail-dep-id",children:z}),t.jsx("span",{className:"detail-dep-label",children:fp(Xe,40)})]}),t.jsx("button",{className:"dep-remove-btn",onClick:ft=>ma(ft,z),title:`Remove dependency ${z}`,children:"×"})]},z)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no dependencies)"}),t.jsxs("div",{className:"dep-trigger-wrap",children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{G&&ke(""),ge(z=>!z)},children:"Add Dependency"}),G&&(()=>{const z=je.toLowerCase(),ue=z?$i.filter(Xe=>Xe.id.toLowerCase().includes(z)||Xe.title&&Xe.title.toLowerCase().includes(z)||Xe.description&&Xe.description.toLowerCase().includes(z)):$i;return t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:je,onChange:Xe=>ke(Xe.target.value),onClick:Xe=>Xe.stopPropagation()}),ue.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):ue.map(Xe=>t.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{ua(Xe.id),ge(!1)},children:[t.jsx("span",{className:"dep-dropdown-id",children:Xe.id}),t.jsx("span",{className:"dep-dropdown-title",children:fp(Xe.title||Xe.description||Xe.id,30)})]},Xe.id))]})})()]})]}),e.column==="in-review"&&t.jsx("div",{className:"detail-section detail-pr-section",children:t.jsx(DR,{taskId:e.id,projectId:n,prInfo:e.prInfo,automationStatus:e.status??null,autoMerge:Gt?.autoMerge??!1,isManualPrFlow:V,prAuthAvailable:f??!1,onPrCreated:z=>{e.prInfo=z},onPrUpdated:z=>{e.prInfo=z},addToast:h})})]})]})]}),t.jsx("div",{className:"modal-actions",children:Y?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"modal-edit-hint",children:Hn==="saving"?"Autosaving…":Hn==="saved"?"Saved":Hn==="error"?"Save failed":"Changes autosave as you edit"}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("button",{className:"btn btn-sm",onClick:cs,disabled:De,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void es(),disabled:De,children:De?"Saving…":"Save"})]}):t.jsxs(t.Fragment,{children:[e.column==="triage"&&e.status==="awaiting-approval"&&j.prompt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Vn,children:"Approve Plan"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:Wn,children:"Reject Plan"})]}),e.column==="triage"&&e.status!=="awaiting-approval"&&!P&&t.jsx("button",{className:"btn btn-sm btn-danger",onClick:ts,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(e.column!=="triage"||e.status==="awaiting-approval"||P||e.paused)&&t.jsxs("div",{className:"detail-actions-dropdown",ref:rt,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{tn(z=>!z),Nt(!1)},"aria-haspopup":"menu","aria-expanded":Ut,children:["Actions",t.jsx(rn,{size:12})]}),Ut&&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:()=>ds(ts),children:"Delete"}),u&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ds(gs),children:"Duplicate"}),(e.column==="done"||e.column==="in-review")&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ds(Bn),children:"Refine"}),t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ds(Kn),children:"Respecify"}),P&&c&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ds(Fn),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:()=>ds(Un),children:"Reset"}),e.column!=="done"&&!e.assignedAgentId&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ds(Ln),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:at,children:e.column==="in-review"?t.jsxs("div",{className:"detail-move-actions-in-review",children:[t.jsxs("div",{children:[t.jsxs("button",{ref:ot,className:"btn btn-primary btn-sm detail-move-btn",onClick:qa,onKeyDown:Ge,disabled:!us,"aria-label":us?`Move to ${ns[us]}`:void 0,"aria-haspopup":Cs?"menu":void 0,"aria-expanded":Cs?Ye:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",us?ns[us]:""]}),Cs&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(rn,{size:12})})]}),Ye&&Cs&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:Rt,children:Ki.map(z=>t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>Gn(z),onKeyDown:Rt,children:z==="in-progress"?"Back to In Progress":`Move to ${ns[z]}`},z))})]}),is?t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:is}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Ts,children:Ie})]}):t.jsxs("div",{children:[t.jsxs("button",{ref:ot,className:"btn btn-primary btn-sm detail-move-btn",onClick:qa,onKeyDown:Ge,disabled:!us,"aria-label":us?`Move to ${ns[us]}`:void 0,"aria-haspopup":Cs?"menu":void 0,"aria-expanded":Cs?Ye:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",us?ns[us]:""]}),Cs&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(rn,{size:12})})]}),Ye&&Cs&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:Rt,children:Ki.map(z=>t.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>Gn(z),onKeyDown:Rt,children:["Move to ",ns[z]]},z))})]})})]})}),pe&&t.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:Ri,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal detail-refine-modal",onClick:z=>z.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:Ri,"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:ze,onChange:z=>lt(z.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:[ze.length,"/2000 characters"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:ca,disabled:!ze.trim()||Be,children:Be?"Creating...":"Create Refinement Task"})]})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:Ri,disabled:Be,children:"Cancel"})})]})}),R&&t.jsx(i.Suspense,{fallback:null,children:t.jsx(EI,{agentId:R,projectId:n,onClose:()=>L(null),addToast:h})})]})}function AI({onClose:e,...n}){const s=i.useRef(null);Ai(s,!0,"task-detail-modal-size"),vi(!0);const a=qi(e);return t.jsx("div",{className:"modal-overlay open",...a,role:"dialog","aria-modal":"true",children:t.jsx("div",{className:"modal modal-lg task-detail-modal",ref:s,children:t.jsx(jx,{...n,onRequestClose:e})})})}const Xo={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},bp=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function xp(e){return e==="merging-fix"?"Merging fixes…":e}const Nx=["title","status","column","dependencies","progress"],PI=["title","status","column"];function RI(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function II(e){return e==="online"?"●":e==="connecting"?"◐":e==="error"?"✕":"○"}function vp(e){try{const n=Dn("kb-dashboard-list-columns",e);if(n){const a=JSON.parse(n).filter(r=>Nx.includes(r));if(a.length>0)return new Set(a)}}catch{}return new Set(PI)}function yp(e){try{const n=Dn("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function wp(e){try{const n=Dn("kb-dashboard-list-collapsed",e);if(n){const a=JSON.parse(n).filter(r=>ea.includes(r));if(a.length>0)return new Set(a)}}catch{}return new Set}function kp(e){try{const n=Dn("kb-dashboard-selected-tasks",e);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function jp(e){try{const n=Dn("kb-dashboard-list-selected-task",e);if(typeof n=="string"&&n.trim().length>0)return n}catch{}return null}function Np(e){try{const s=Dn("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 Ll=280,Yd=.65,Zo=16;function Qd(e){return Math.max(Ll,e*Yd)}function el(e,n){const s=Qd(n);return Math.min(Math.max(e,Ll),s)}function TI(e){return e.status==="executing"||e.column==="in-progress"}function Sp(e){const n=Qg(e);return n.total===0||!TI(e)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function $I({tasks:e,onMoveTask:n,onRetryTask:s,onDeleteTask:a,onMergeTask:r,onResetTask:o,onDuplicateTask:l,onOpenDetail:c,addToast:d,globalPaused:u,onNewTask:m,onQuickCreate:h,availableModels:f,favoriteProviders:p=[],favoriteModels:g=[],onToggleFavorite:x,onToggleModelFavorite:w,onPlanningMode:b,onSubtaskBreakdown:y,onTasksUpdated:S,projectId:k,projectName:C,taskStuckTimeoutMs:v,searchQuery:j="",lastFetchTimeMs:P,prAuthAvailable:U}){const[E,R]=i.useState(null),[L,F]=i.useState("asc"),[M,O]=i.useState(null),[q,te]=i.useState(null),[Z,K]=i.useState(null),I=Ys()==="mobile",{confirm:$}=ai(),[N,G]=i.useState(()=>vp(k)),[ge,je]=i.useState(()=>yp(k)),[ke,ne]=i.useState(()=>wp(k));i.useEffect(()=>{typeof window<"u"&&os("kb-dashboard-list-columns",JSON.stringify([...N]),k)},[k,N]),i.useEffect(()=>{typeof window<"u"&&os("kb-dashboard-hide-done",ge.toString(),k)},[ge,k]),i.useEffect(()=>{typeof window<"u"&&os("kb-dashboard-list-collapsed",JSON.stringify([...ke]),k)},[ke,k]);const[qe,ee]=i.useState(!1),[le,se]=i.useState(!1),[re,J]=i.useState(()=>kp(k)),[B,ve]=i.useState(()=>jp(k)),[Ne,H]=i.useState(null),[be,ce]=i.useState(()=>Np(k)),Me=i.useRef(null),Le=i.useRef(null);i.useEffect(()=>{G(vp(k)),je(yp(k)),ne(wp(k)),J(kp(k));const xe=jp(k);ve(xe),H(xe?e.find(Fe=>Fe.id===xe)??null:null),ce(Np(k))},[k,e]),i.useEffect(()=>{typeof window<"u"&&os("kb-dashboard-selected-tasks",JSON.stringify([...re]),k)},[k,re]),i.useEffect(()=>{if(!(typeof window>"u")){if(B){os("kb-dashboard-list-selected-task",B,k);return}pr("kb-dashboard-list-selected-task",k)}},[k,B]),i.useEffect(()=>{if(!B){H(null);return}const xe=e.find(Fe=>Fe.id===B);xe&&H(Fe=>!Fe||Fe.id!==B?xe:{...Fe,...xe})},[B,e]),i.useEffect(()=>{if(I||typeof ResizeObserver>"u")return;const xe=Me.current;if(!xe)return;const Fe=()=>{const et=el(be,xe.clientWidth);et!==be&&ce(et)};Fe();const Ke=new ResizeObserver(Fe);return Ke.observe(xe),()=>Ke.disconnect()},[I,be]),i.useEffect(()=>{if(I||typeof ResizeObserver>"u")return;const xe=Le.current,Fe=Me.current;if(!xe||!Fe)return;let Ke=null,et=xe.offsetWidth;const Qe=new ResizeObserver(()=>{const It=el(xe.offsetWidth,Fe.clientWidth);It!==et&&(et=It,Ke&&clearTimeout(Ke),Ke=setTimeout(()=>{try{os("kb-dashboard-list-sidebar-width",String(It),k)}catch{}},200))});return Qe.observe(xe),()=>{Qe.disconnect(),Ke&&clearTimeout(Ke)}},[I,k]);const He=i.useCallback(()=>{se(xe=>(xe&&J(new Set),!xe))},[]),gt=i.useCallback(xe=>{J(Fe=>{const Ke=new Set(Fe);return Ke.has(xe)?Ke.delete(xe):Ke.add(xe),Ke})},[]),Ue=i.useCallback(()=>{J(new Set)},[]),pe=i.useCallback(xe=>{G(Fe=>{const Ke=new Set(Fe);return Ke.has(xe)?Ke.size>1&&Ke.delete(xe):Ke.add(xe),Ke})},[]),Oe={title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},ze=i.useCallback(xe=>{if(E===xe){F(Fe=>Fe==="asc"?"desc":"asc");return}R(xe),F("asc")},[E]),lt=i.useCallback(xe=>{K(Fe=>Fe===xe?null:xe)},[]),Be=i.useCallback(xe=>{ne(Fe=>{const Ke=new Set(Fe);return Ke.has(xe)?Ke.delete(xe):Ke.add(xe),Ke})},[]),ye=i.useCallback(()=>{K(null)},[]),Y=i.useMemo(()=>{let xe=j?e.filter(et=>et.id.toLowerCase().includes(j.toLowerCase())||et.title&&et.title.toLowerCase().includes(j.toLowerCase())||et.description.toLowerCase().includes(j.toLowerCase())):[...e];ge&&!Z&&(xe=xe.filter(et=>et.column!=="done"&&et.column!=="archived"));const Fe=Z?xe.filter(et=>et.column===Z):xe,Ke={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};Fe.forEach(et=>{const Qe=xu(et.column)?et.column:Al;Ke[Qe].push(et)});for(const et of ea){if(!E){Ke[et]=Wg(Ke[et],et);continue}Ke[et]=[...Ke[et]].sort((Qe,It)=>{let St=0;switch(E){case"title":St=(Qe.title||Qe.description).localeCompare(It.title||It.description);break;case"status":St=(Qe.status||"").localeCompare(It.status||"");break;case"column":St=Qe.column.localeCompare(It.column);break}return L==="asc"?St:-St})}return Ke},[e,j,E,L,ge,Z]),_e=i.useMemo(()=>Object.values(Y).reduce((xe,Fe)=>xe+Fe.length,0),[Y]),ct=i.useMemo(()=>e.filter(xe=>xe.column==="done"||xe.column==="archived").length,[e]),pt=i.useMemo(()=>ge?ct:0,[ge,ct]),de=i.useCallback(()=>{const xe=Object.values(Y).flat().filter(Fe=>Fe.column!=="archived").map(Fe=>Fe.id);J(Fe=>{if(xe.every(et=>Fe.has(et))){const et=new Set(Fe);return xe.forEach(Qe=>et.delete(Qe)),et}else return new Set([...Fe,...xe])})},[Y]),Ve=i.useMemo(()=>{const xe=Object.values(Y).flat().filter(Fe=>Fe.column!=="archived");return xe.length===0?!1:xe.every(Fe=>re.has(Fe.id))},[Y,re]),Ee=i.useMemo(()=>{const xe=Object.values(Y).flat().filter(Ke=>Ke.column!=="archived");if(xe.length===0)return!1;const Fe=xe.filter(Ke=>re.has(Ke.id)).length;return Fe>0&&Fe<xe.length},[Y,re]),[$e,ut]=i.useState("__no_change__"),[ht,Se]=i.useState("__no_change__"),[we,Ae]=i.useState("__no_change__"),[he,We]=i.useState([]),[me,nt]=i.useState(!1),Ct=i.useMemo(()=>we&&we!=="__no_change__"?he.find(xe=>xe.id===we):void 0,[he,we]),[wt,$t]=i.useState(!1);i.useEffect(()=>{if(re.size===0)return;let xe=!1;return(async()=>{nt(!0);try{const Ke=await _l();xe||We(Ke)}catch(Ke){console.error("Failed to fetch nodes for bulk edit",Ke),xe||We([])}finally{xe||nt(!1)}})(),()=>{xe=!0}},[re.size]);const Vt=i.useCallback(async()=>{if(re.size===0)return;const xe=Array.from(re).filter(Ke=>{const et=e.find(Qe=>Qe.id===Ke);return et&&et.column!=="archived"});if(xe.length===0){d("No valid tasks to update (archived tasks cannot be modified)","error");return}const Fe={taskIds:xe};if($e!=="__no_change__")if($e==="")Fe.modelProvider=null,Fe.modelId=null;else{const Ke=$e.indexOf("/");Ke!==-1&&(Fe.modelProvider=$e.slice(0,Ke),Fe.modelId=$e.slice(Ke+1))}if(ht!=="__no_change__")if(ht==="")Fe.validatorModelProvider=null,Fe.validatorModelId=null;else{const Ke=ht.indexOf("/");Ke!==-1&&(Fe.validatorModelProvider=ht.slice(0,Ke),Fe.validatorModelId=ht.slice(Ke+1))}if(we!=="__no_change__"&&(we===""?Fe.nodeId=null:Fe.nodeId=we),Object.keys(Fe).length===1){d("No changes to apply","info");return}$t(!0);try{const Ke=await Dk(Fe.taskIds,Fe.modelProvider,Fe.modelId,Fe.validatorModelProvider,Fe.validatorModelId,void 0,void 0,Fe.nodeId,k);S&&S(Ke.updated),d(`Updated ${xe.length} task${xe.length===1?"":"s"}`,"success"),Ue(),ut("__no_change__"),Se("__no_change__"),Ae("__no_change__")}catch(Ke){d(Re(Ke)||"Failed to update models","error")}finally{$t(!1)}},[re,e,$e,ht,we,k,d,Ue,S]),Mt=i.useCallback(xe=>{if(I){c(xe,{origin:"list-mobile"});return}ve(xe.id),H(xe)},[I,c]),Dt=i.useRef(null),Qt=i.useRef(null);i.useEffect(()=>()=>{Dt.current&&clearTimeout(Dt.current)},[]);const Kt=i.useCallback(xe=>{if(ve(xe.id),H(xe),"prompt"in xe){Qt.current=null,Dt.current&&(clearTimeout(Dt.current),Dt.current=null);return}Qt.current=xe.id,Dt.current&&clearTimeout(Dt.current),Dt.current=setTimeout(()=>{Dt.current=null,Qt.current===xe.id&&Sa(xe.id,k).then(Ke=>{Qt.current===Ke.id&&H(et=>!et||et.id!==Ke.id?et:{...et,...Ke})}).catch(()=>{})},200)},[k]),Bt=i.useCallback((xe,Fe)=>{if(Fe.paused){xe.preventDefault();return}xe.dataTransfer.setData("text/plain",Fe.id),xe.dataTransfer.effectAllowed="move",O(Fe.id)},[]),on=i.useCallback(()=>{O(null),te(null)},[]),fn=i.useCallback(xe=>{if(I)return;xe.preventDefault();const Fe=Me.current;if(!Fe)return;const Ke=Fe.getBoundingClientRect(),et=It=>{const St=It.clientX-Ke.left;ce(el(St,Ke.width))},Qe=()=>{window.removeEventListener("mousemove",et),window.removeEventListener("mouseup",Qe)};window.addEventListener("mousemove",et),window.addEventListener("mouseup",Qe)},[I]),Jt=i.useCallback(xe=>{if(I)return;const Fe=Me.current?.clientWidth??0,Ke=be/Yd+Zo,et=Math.max(Fe,Ke),Qe=Qd(et);if(xe.key==="ArrowLeft"||xe.key==="ArrowRight"){xe.preventDefault();const It=xe.key==="ArrowLeft"?-Zo:Zo;ce(St=>el(St+It,et));return}if(xe.key==="Home"){xe.preventDefault(),ce(Ll);return}xe.key==="End"&&(xe.preventDefault(),ce(Qe))},[I,be]),an=i.useCallback((xe,Fe)=>{xe.preventDefault(),xe.dataTransfer.dropEffect="move",te(Fe)},[]),zt=i.useCallback(()=>{te(null)},[]),en=i.useCallback(async(xe,Fe)=>{xe.preventDefault(),te(null);const Ke=xe.dataTransfer.getData("text/plain");if(Ke){if(Fe==="archived"){d("Tasks can only be archived via the archive button","error");return}try{const Qe=e.find(Ht=>Ht.id===Ke)?.steps.some(Ht=>Ht.status!=="pending")??!1,It=(Fe==="todo"||Fe==="triage")&&Qe;let St;if(It){if(await $({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))St={preserveProgress:!0};else if(!await $({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await n(Ke,Fe,St)}catch(et){d(Re(et),"error")}}},[n,d,e,$]),Zt=xe=>!E||E!==xe?t.jsx(rg,{size:14,className:"sort-icon"}):L==="asc"?t.jsx(ka,{size:14,className:"sort-icon active"}):t.jsx(vo,{size:14,className:"sort-icon active"}),dn=xe=>t.jsxs("div",{id:xe,className:"list-view-options-panel",children:[t.jsx("div",{className:"list-view-options-columns",children:Nx.map(Fe=>{const Ke=N.has(Fe),et=Ke&&N.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${et?" disabled":""}`,title:et?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:Ke,onChange:()=>pe(Fe),disabled:et}),t.jsx("span",{children:Oe[Fe]})]},Fe)})}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>je(Fe=>!Fe),"aria-pressed":ge,title:ge?"Show done tasks":"Hide done tasks",children:[ge?t.jsx(kr,{size:14}):t.jsx(ou,{size:14}),ge?"Show Done":"Hide Done"]}),t.jsx("div",{className:"list-drop-zones list-drop-zones--sidebar",children:ea.map(Fe=>{const Ke=e.filter(St=>St.column===Fe).length,et=Fe==="done"||Fe==="archived",Qe=ge&&et?0:Ke,It=ge&&et&&Ke>0;return t.jsxs("div",{className:`list-drop-zone${q===Fe?" drag-over":""}${Z===Fe?" active":""}`,onClick:()=>lt(Fe),onDragOver:St=>an(St,Fe),onDragLeave:zt,onDrop:St=>en(St,Fe),"data-column":Fe,children:[t.jsx("span",{className:`list-section-dot dot-${Fe}`}),t.jsx("span",{className:"drop-zone-label",children:ns[Fe]}),t.jsx("span",{className:"drop-zone-count",children:It?`${Qe} of ${Ke}`:Ke})]},Fe)})})]});return t.jsxs("div",{className:"list-view",children:[I&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"list-toolbar",children:[t.jsx("button",{className:"btn btn-sm",onClick:He,"aria-pressed":le,children:le?"Done Editing":"Bulk Edit"}),t.jsxs("button",{className:"btn btn-sm list-view-options-toggle",onClick:()=>ee(xe=>!xe),"aria-expanded":qe,"aria-controls":"list-view-options-panel-mobile",children:[t.jsx(Ku,{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:Z?`${_e} of ${e.length} tasks in ${ns[Z]}`:`${_e} of ${e.length} tasks`})]}),qe?t.jsx("div",{className:"list-toolbar-mobile-options",children:dn("list-view-options-panel-mobile")}):null]}),t.jsx("div",{className:"list-table-container",children:t.jsxs("div",{className:I?"":"list-split-layout","data-testid":I?void 0:"list-split-layout",ref:Me,children:[t.jsxs("div",{className:I?"":"list-split-sidebar","data-testid":I?void 0:"list-split-sidebar",ref:Le,style:I?void 0:{width:`${be}px`},children:[!I&&t.jsxs("aside",{className:"list-sidebar-controls","aria-label":"List controls",children:[t.jsxs("div",{className:"list-sidebar-controls__header",children:[t.jsxs("p",{className:"list-stats",children:[Z?`${_e} of ${e.length} tasks in ${ns[Z]}`:`${_e} of ${e.length} tasks`,pt>0&&!Z&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",pt," hidden)"]})]}),t.jsxs("div",{className:"list-sidebar-controls__actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:He,"aria-pressed":le,children:le?"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:[Z?t.jsx("button",{className:"btn btn-sm",onClick:ye,"aria-label":"Clear column filter",children:`Filter: ${ns[Z]}`}):null,ge?t.jsx("span",{className:"list-sidebar-chip",children:"Done hidden"}):null,le?t.jsx("span",{className:"list-sidebar-chip",children:"Bulk edit"}):null,le&&re.size>0?t.jsx("button",{className:"btn btn-sm",onClick:Ue,children:`${re.size} selected`}):null]})]}),t.jsxs("button",{className:"btn btn-sm list-view-options-toggle",onClick:()=>ee(xe=>!xe),"aria-expanded":qe,"aria-controls":"list-view-options-panel",children:[t.jsx(Ku,{size:14}),"View options"]}),qe&&dn("list-view-options-panel"),le&&re.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(ys,{models:f,value:$e,onChange:ut,label:"Executor Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:p,onToggleFavorite:x,favoriteModels:g,onToggleModelFavorite:w})}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(ys,{models:f,value:ht,onChange:Se,label:"Reviewer Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:p,onToggleFavorite:x,favoriteModels:g,onToggleModelFavorite:w})}),t.jsxs("div",{className:"bulk-edit-dropdown bulk-edit-node-wrap",children:[t.jsxs("select",{className:"select bulk-node-select",value:we,onChange:xe=>Ae(xe.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"}),he.map(xe=>t.jsx("option",{value:xe.id,children:`${II(xe.status)} ${xe.name||xe.id} (${RI(xe.status)})`},xe.id))]}),Ct?t.jsx(Ca,{status:Ct.status,showLabel:!0}):null]}),t.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:Vt,disabled:wt||$e==="__no_change__"&&ht==="__no_change__"&&we==="__no_change__",children:wt?"Applying...":"Apply"})]})]}),t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx(ab,{onCreate:h??(async()=>d("Task creation not available","error")),addToast:d,tasks:e,availableModels:f,onPlanningMode:b,onSubtaskBreakdown:y,projectId:k,autoExpand:!1,favoriteProviders:p,favoriteModels:g,onToggleFavorite:x,onToggleModelFavorite:w})}),_e===0?t.jsx("div",{className:"list-empty",children:j?"No tasks match your filter":"No tasks yet"}):I?t.jsx("div",{className:"list-cards",children:ea.map(xe=>{if(Z&&xe!==Z||ge&&(xe==="done"||xe==="archived")&&!Z)return null;const Fe=Y[xe],Ke=Fe.length===0;if(j&&Ke)return null;const et=ke.has(xe);return t.jsxs(i.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${et?" list-section-header--collapsed":""}`,onClick:()=>Be(xe),"aria-expanded":!et,role:"button",tabIndex:0,onKeyDown:Qe=>{(Qe.key==="Enter"||Qe.key===" ")&&(Qe.preventDefault(),Be(xe))},children:[t.jsx(Mn,{size:14,className:`list-section-chevron${et?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${xe}`}),t.jsx("span",{className:"list-section-title",children:ns[xe]}),t.jsx("span",{className:"list-section-count",children:Fe.length})]}),!et&&t.jsx(t.Fragment,{children:Ke?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):Fe.map(Qe=>{const It=Qe.status==="failed",St=Qe.paused===!0,Ht=Rl(Qe,v,P),jt=!u&&!It&&!St&&!Ht&&(Qe.column==="in-progress"||bp.has(Qe.status)),ae=typeof Qe.status=="string"&&Qe.status.trim().length>0,De=!!(Qe.dependencies&&Qe.dependencies.length>0),At=Sp(Qe),Lt=At.hasProgress,Ft=le;return t.jsxs("div",{className:`list-card${jt?" agent-active":""}${Ft?" list-card--selectable":""}`,onClick:()=>Mt(Qe),"data-id":Qe.id,children:[Ft&&t.jsx("label",{className:"list-card-checkbox",onClick:Pe=>Pe.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:re.has(Qe.id),onChange:Pe=>{Pe.stopPropagation(),gt(Qe.id)},onClick:Pe=>Pe.stopPropagation(),disabled:Qe.column==="archived","aria-label":`Select ${Qe.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:Qe.id}),Qe.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(Qn,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),t.jsx("span",{className:"list-card-spacer"}),St&&Qe.pausedByAgentId?t.jsx("span",{className:"list-status-badge paused",children:"paused by agent"}):Ht?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):ae?t.jsx("span",{className:`list-status-badge list-status-badge--${Qe.column}${It?" failed":""}${jt?" pulsing":""}`,children:xp(Qe.status??"")}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:Qe.title||Qe.description})}),(De||Lt)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[De&&t.jsxs("span",{className:"list-dep-badge",title:Qe.dependencies.join(", "),children:[t.jsx(cr,{size:12})," ",Qe.dependencies.length]}),Lt&&t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${At.percent}%`,backgroundColor:Xo[Qe.column]}})}),t.jsx("span",{className:"list-progress-label",children:At.label})]})]})]},Qe.id)})})]},xe)})}):t.jsxs("table",{className:"list-table",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[le&&t.jsx("th",{className:"list-header-cell list-header-checkbox",children:t.jsx("input",{type:"checkbox",checked:Ve,ref:xe=>{xe&&(xe.indeterminate=Ee)},onChange:de,"aria-label":"Select all visible tasks"})}),N.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>ze("title"),children:["Title ",Zt("title")]}),N.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>ze("status"),children:["Status ",Zt("status")]}),N.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>ze("column"),children:["Column ",Zt("column")]}),N.has("dependencies")&&t.jsx("th",{className:"list-header-cell",children:"Dependencies"}),N.has("progress")&&t.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),t.jsx("tbody",{children:ea.map(xe=>{if(Z&&xe!==Z||ge&&(xe==="done"||xe==="archived")&&!Z)return null;const Fe=Y[xe],Ke=Fe.length===0;if(j&&Ke)return null;const et=ke.has(xe);return t.jsxs(i.Fragment,{children:[t.jsx("tr",{className:`list-section-header${et?" list-section-header--collapsed":""}`,onClick:()=>Be(xe),"aria-expanded":!et,children:t.jsxs("th",{colSpan:N.size+(le?1:0),className:"list-section-cell",children:[t.jsx(Mn,{size:14,className:`list-section-chevron${et?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${xe}`}),t.jsx("span",{className:"list-section-title",children:ns[xe]}),t.jsx("span",{className:"list-section-count",children:Fe.length})]})}),!et&&t.jsx(t.Fragment,{children:Ke?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:N.size+(le?1:0),className:"list-empty-cell",children:"No tasks"})}):Fe.map(Qe=>{const It=Qe.status==="failed",St=Qe.paused===!0,Ht=Rl(Qe,v,P),jt=!u&&!It&&!St&&!Ht&&(Qe.column==="in-progress"||bp.has(Qe.status)),ae=M===Qe.id;return t.jsxs("tr",{className:`list-row${It?" failed":""}${St?" paused":""}${Ht?" stuck":""}${jt?" agent-active":""}${ae?" dragging":""}${B===Qe.id?" list-row--selected":""}`,onClick:()=>Mt(Qe),draggable:!St,onDragStart:De=>Bt(De,Qe),onDragEnd:on,"data-id":Qe.id,children:[le&&t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:re.has(Qe.id),onChange:De=>{De.stopPropagation(),gt(Qe.id)},onClick:De=>De.stopPropagation(),disabled:Qe.column==="archived","aria-label":`Select ${Qe.id}`})}),N.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:Qe.id}),t.jsxs("div",{className:"list-title-row",children:[Qe.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(Qn,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),t.jsx("span",{className:"list-title-text",children:Qe.title||Qe.description})]})]})}),N.has("status")&&t.jsx("td",{className:"list-cell",children:St&&Qe.pausedByAgentId?t.jsx("span",{className:"list-status-badge paused",children:"paused by agent"}):Ht?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):Qe.status?t.jsx("span",{className:`list-status-badge list-status-badge--${Qe.column}${It?" failed":""}${jt?" pulsing":""}`,children:xp(Qe.status??"")}):t.jsx("span",{className:"list-status-badge",children:"-"})}),N.has("column")&&t.jsx("td",{className:"list-cell",children:t.jsx("span",{className:"list-column-badge",style:{background:`${Xo[Qe.column]}20`,color:Xo[Qe.column]},children:ns[Qe.column]})}),N.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:Qe.dependencies&&Qe.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:Qe.dependencies.join(", "),children:[t.jsx(cr,{size:12})," ",Qe.dependencies.length]}):"-"}),N.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const De=Sp(Qe);return De.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:`${De.percent}%`,backgroundColor:Xo[Qe.column]}})}),t.jsx("span",{className:"list-progress-label",children:De.label})]}):"-"})()})]},Qe.id)})})]},xe)})})]})]}),!I&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"list-split-resize-handle","data-testid":"list-split-resize-handle",onMouseDown:fn,onKeyDown:Jt,role:"separator",tabIndex:0,"aria-orientation":"vertical","aria-label":"Resize task list sidebar","aria-valuemin":Ll,"aria-valuemax":Math.round(Qd(Me.current?.clientWidth??be/Yd+Zo)),"aria-valuenow":Math.round(be)}),t.jsx("div",{className:"list-split-detail","data-testid":"list-split-detail",children:Ne?t.jsx("div",{className:"list-split-detail-content","data-testid":"list-split-detail-content",children:t.jsx(jx,{task:Ne,projectId:k,tasks:e,embedded:!0,onOpenDetail:Kt,onMoveTask:n,onDeleteTask:a,onMergeTask:r,onRetryTask:s,onResetTask:o,onDuplicateTask:l,onTaskUpdated:xe=>{H(Fe=>!Fe||Fe.id!==xe.id?Fe:{...Fe,...xe})},addToast:d,prAuthAvailable:U})}):t.jsx("div",{className:"list-split-detail-empty",children:t.jsx("p",{children:"Select a task to view details"})})})]})]})})]})}const DI={active:{label:"Active",color:"var(--color-success)",icon:Yn},paused:{label:"Paused",color:"var(--color-warning)",icon:pi},errored:{label:"Error",color:"var(--color-error)",icon:Ps},initializing:{label:"Initializing",color:"var(--color-warning)",icon:xt}};function LI(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 Cp(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 OI(e,n){if(e.project.id!==n.project.id||e.project.status!==n.project.status||e.project.name!==n.project.name||e.project.path!==n.project.path||e.project.lastActivityAt!==n.project.lastActivityAt||e.isLoading!==n.isLoading)return!1;const s=e.health,a=n.health;if(!s&&!a)return!0;if(!s||!a||s.activeTaskCount!==a.activeTaskCount||s.inFlightAgentCount!==a.inFlightAgentCount||s.totalTasksCompleted!==a.totalTasksCompleted||s.totalTasksFailed!==a.totalTasksFailed||s.status!==a.status)return!1;const r=e.availabilityMappings??[],o=n.availabilityMappings??[];return r.length!==o.length?!1:r.every((l,c)=>{const d=o[c];return!!d&&l.nodeId===d.nodeId&&l.path===d.path&&l.displayName===d.displayName&&l.available===d.available})}function zI({project:e,health:n,onSelect:s,onPause:a,onResume:r,onRemove:o,availabilityMappings:l=[],isLoading:c=!1}){const[d,u]=i.useState(!1),m=DI[e.status],h=m.icon,f=i.useCallback(()=>{s(e)},[s,e]),p=i.useCallback(S=>{S.stopPropagation(),a(e)},[a,e]),g=i.useCallback(S=>{S.stopPropagation(),r(e)},[r,e]),x=i.useCallback(S=>{if(S.stopPropagation(),!d){u(!0);return}o(e),u(!1)},[d,o,e]),w=e.status==="paused",b=e.status==="errored",y=e.status==="initializing";return t.jsxs("div",{className:`project-card ${c?"project-card-loading":""} ${b?"project-card-errored":""}`,onClick:f,"data-project-id":e.id,role:"button",tabIndex:0,onKeyDown:S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),f())},children:[t.jsxs("div",{className:"project-card-header",children:[t.jsx("div",{className:"project-card-icon",children:t.jsx(bs,{size:20})}),t.jsxs("div",{className:"project-card-title-section",children:[t.jsx("h3",{className:"project-card-name",title:e.name,children:e.name}),l.length>0&&t.jsxs("div",{className:"project-card-availability","aria-label":"Project node availability",children:[l.slice(0,3).map(S=>t.jsxs("div",{className:"project-card-availability__row",title:`${S.displayName} → ${S.path}`,children:[t.jsx("span",{className:"project-card-availability__node",children:S.displayName}),t.jsx("span",{className:"project-card-availability__arrow",children:"→"}),t.jsx("code",{className:"project-card-availability__path",children:Cp(S.path,28)})]},`${S.nodeId}-${S.path}`)),l.length>3&&t.jsxs("span",{className:"project-card-availability__more",children:["+",l.length-3," more"]})]}),t.jsx("span",{className:"project-card-path",title:e.path,children:Cp(e.path)})]}),t.jsxs("div",{className:"project-card-status-badge",style:{color:m.color,borderColor:m.color},children:[t.jsx(h,{size:12,className:y?"animate-spin":""}),t.jsx("span",{children:m.label})]})]}),t.jsxs("div",{className:"project-card-health",children:[n&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.activeTaskCount}),t.jsx("span",{className:"project-card-metric-label",children:"Active Tasks"})]}),t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.inFlightAgentCount}),t.jsx("span",{className:"project-card-metric-label",children:"Agents"})]}),t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.totalTasksCompleted}),t.jsx("span",{className:"project-card-metric-label",children:"Completed"})]})]}),!n&&t.jsx("div",{className:"project-card-metric project-card-metric-empty",children:t.jsx("span",{className:"project-card-metric-label",children:"No health data available"})})]}),t.jsxs("div",{className:"project-card-footer",children:[t.jsxs("div",{className:"project-card-activity",children:[t.jsx("span",{className:"project-card-activity-label",children:"Last activity:"}),t.jsx("span",{className:"project-card-activity-time",children:LI(e.lastActivityAt||n?.lastActivityAt)})]}),t.jsxs("div",{className:"project-card-actions",children:[w?t.jsxs("button",{className:"project-card-action project-card-action-resume",onClick:g,disabled:c,title:"Resume project","aria-label":"Resume project",children:[t.jsx(Yn,{size:14}),t.jsx("span",{children:"Resume"})]}):t.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:p,disabled:c||y,title:y?"Cannot pause while initializing":"Pause project","aria-label":"Pause project",children:[t.jsx(pi,{size:14}),t.jsx("span",{children:"Pause"})]}),t.jsxs("button",{className:"project-card-action project-card-action-open",onClick:f,disabled:c,title:"Open project","aria-label":"Open project",children:[t.jsx(yo,{size:14}),t.jsx("span",{children:"Open"})]}),t.jsxs("button",{className:`project-card-action project-card-action-remove ${d?"is-armed":""}`,onClick:x,disabled:c,title:d?"Confirm remove":"Remove project","aria-label":d?"Confirm remove project":"Remove project",children:[t.jsx(vn,{size:14}),t.jsx("span",{children:d?"Confirm":""})]})]})]})]})}const FI=i.memo(zI,OI);function Ep(e){return typeof e=="string"&&e.trim().length>0}function Qr(e){return(e.nodeMappings??[]).filter(s=>Ep(s.nodeId)&&Ep(s.path)).map(s=>({nodeId:s.nodeId,nodeName:s.nodeName,path:s.path,available:s.available!==!1}))}function UI(e,n){return Qr(e).filter(s=>s.nodeId===n.id&&s.available)}function BI(e,n){return UI(e,n).length>0}function HI(e,n){return e.filter(s=>BI(s,n))}function K6(e,n){return HI(e,n).length}function _p(e,n,s,a){const r=s.find(o=>o.id===e);return r?.name?r.name:n?.nodeName?n.nodeName:a._sourceNodeName?a._sourceNodeName:e}function qI(){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(bs,{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(Ks,{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($n,{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(Ps,{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 VI=1e4,Mp=5;function WI(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+=Mp){const x=e.slice(g,g+Mp),w=await Promise.allSettled(x.map(async b=>{try{return await vm(b)}catch{return null}}));if(x.forEach((b,y)=>{const S=w[y];p[b]=S.status==="fulfilled"?S.value:null}),d.current?.signal.aborted)return}s(p),u.current=!0}catch(p){if(p instanceof Error&&p.name==="AbortError")return;l(p instanceof Error?p.message:"Failed to fetch health data"),u.current=!0}finally{r(!1)}},[e]),h=i.useCallback(async f=>{try{const p=await vm(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()},VI),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[m,e.length]),{healthMap:n,loading:a,error:o,refresh:m,refreshProject:h}}function KI({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 F=localStorage.getItem("kb-dashboard-recent-projects");if(F)try{const M=JSON.parse(F);b(M)}catch{}},[]);const[w,b]=i.useState([]),y=i.useMemo(()=>e.map(F=>F.id),[e]),{healthMap:S,loading:k}=WI(y),C=i.useMemo(()=>e.map(F=>({project:F,health:S[F.id]||null})),[e,S]),v=i.useMemo(()=>{let F=[...C];return d!=="all"&&(F=F.filter(({project:M})=>M.status===d)),m!==null&&(F=F.filter(({project:M})=>Qr(M).some(O=>O.available&&O.nodeId===m))),F},[C,d,m]),j=i.useMemo(()=>{const F=[...v];return F.sort((M,O)=>{let q=0;switch(f){case"name":q=M.project.name.localeCompare(O.project.name);break;case"activity":{const te=M.project.lastActivityAt||M.health?.lastActivityAt||M.project.updatedAt,Z=O.project.lastActivityAt||O.health?.lastActivityAt||O.project.updatedAt;q=new Date(Z).getTime()-new Date(te).getTime();break}case"status":{const te={errored:0,initializing:1,paused:2,active:3};q=te[M.project.status]-te[O.project.status];break}}return g==="asc"?q:-q}),F},[v,f,g]),P=i.useMemo(()=>{const F=e.length,M=e.filter(I=>I.status==="active").length,O=e.filter(I=>I.status==="errored").length,q=new Set;e.forEach(I=>{Qr(I).forEach($=>{$.available&&q.add($.nodeId)})});const te=q.size;let Z=0,K=0,A=0;return Object.values(S).forEach(I=>{I&&(Z+=I.activeTaskCount,K+=I.totalTasksCompleted,A+=I.inFlightAgentCount)}),{totalProjects:F,activeProjects:M,erroredProjects:O,totalNodes:te,totalActiveTasks:Z,totalCompletedTasks:K,totalInFlightAgents:A}},[e,S]),U=i.useMemo(()=>({all:e.length,active:e.filter(F=>F.status==="active").length,paused:e.filter(F=>F.status==="paused").length,errored:e.filter(F=>F.status==="errored").length}),[e]),E=i.useMemo(()=>{const F=new Map;return e.forEach(M=>{Qr(M).filter(O=>O.available).forEach(O=>{const q=O.nodeId,te=F.get(q),Z=_p(q,O,c,M);te?te.count+=1:F.set(q,{name:Z,count:1})})}),Array.from(F.entries()).map(([M,{name:O,count:q}])=>({nodeId:M,name:O,count:q}))},[e,c]),R=i.useCallback(F=>{const M=[F.id,...w.filter(O=>O!==F.id)].slice(0,3);b(M),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify(M)),s(F)},[s,w]);return n||k&&e.length>0&&Object.keys(S).length===0?t.jsx(qI,{}):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(ya,{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(bn,{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(aa,{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(bs,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:P.totalProjects}),t.jsx("span",{className:"project-stat__label",children:"Total"})]})]}),t.jsxs("div",{className:"project-stat project-stat--active",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Ks,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:P.totalActiveTasks}),t.jsx("span",{className:"project-stat__label",children:"Active Tasks"})]})]}),t.jsxs("div",{className:"project-stat project-stat--completed",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx($n,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:P.totalCompletedTasks}),t.jsx("span",{className:"project-stat__label",children:"Completed"})]})]}),P.erroredProjects>0&&t.jsxs("div",{className:"project-stat project-stat--error",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Ps,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:P.erroredProjects}),t.jsx("span",{className:"project-stat__label",children:"Errored"})]})]}),P.totalNodes>1&&t.jsxs("div",{className:"project-stat project-stat--nodes",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(co,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:P.totalNodes}),t.jsx("span",{className:"project-stat__label",children:"Nodes"})]})]})]}),t.jsxs("button",{className:"btn btn-primary project-overview__add-btn",onClick:a,children:[t.jsx(bn,{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:U.all})]}),t.jsxs("button",{className:`project-filter-tab ${d==="active"?"active":""}`,onClick:()=>u("active"),children:["Active",t.jsx("span",{className:"project-filter-count",children:U.active})]}),t.jsxs("button",{className:`project-filter-tab ${d==="paused"?"active":""}`,onClick:()=>u("paused"),children:["Paused",t.jsx("span",{className:"project-filter-count",children:U.paused})]}),t.jsxs("button",{className:`project-filter-tab ${d==="errored"?"active":""} ${U.errored>0?"has-errors":""}`,onClick:()=>u("errored"),children:["Errored",t.jsx("span",{className:"project-filter-count",children:U.errored})]})]}),E.length>1&&t.jsxs("div",{className:"project-node-filter",children:[t.jsx(co,{size:14}),t.jsxs("select",{value:m??"",onChange:F=>{h(F.target.value||null)},className:"project-node-filter-select","aria-label":"Filter by node",children:[t.jsx("option",{value:"",children:"All Nodes"}),E.map(({nodeId:F,name:M,count:O})=>t.jsxs("option",{value:F??"",children:[M," (",O,")"]},F??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(jl,{size:14}),t.jsxs("select",{value:`${f}-${g}`,onChange:F=>{const[M,O]=F.target.value.split("-");p(M),x(O)},className:"project-sort-select","aria-label":"Sort projects",children:[t.jsx("option",{value:"activity-desc",children:"Last Activity (Newest)"}),t.jsx("option",{value:"activity-asc",children:"Last Activity (Oldest)"}),t.jsx("option",{value:"name-asc",children:"Name (A-Z)"}),t.jsx("option",{value:"name-desc",children:"Name (Z-A)"}),t.jsx("option",{value:"status-asc",children:"Status (Error → Active)"}),t.jsx("option",{value:"status-desc",children:"Status (Active → Error)"})]}),t.jsx(rg,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:j.map(({project:F,health:M})=>{const O=Qr(F).filter(q=>q.available).map(q=>({...q,displayName:_p(q.nodeId,q,c,F)}));return t.jsx(FI,{project:F,health:M,availabilityMappings:O,onSelect:R,onPause:r,onResume:o,onRemove:l},F.id)})}),j.length===0&&t.jsxs("div",{className:"project-overview__no-results",children:[t.jsx(jl,{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 Uu="kb-planning-last-description",Bu="kb-subtask-last-description",Hu="kb-mission-last-goal";function GI(e,n){os(Uu,e,n)}function JI(e){return Dn(Uu,e)||""}function Xa(e){pr(Uu,e)}function YI(e,n){os(Bu,e,n)}function QI(e){return Dn(Bu,e)||""}function ed(e){pr(Bu,e)}function XI(e,n){os(Hu,e,n)}function ZI(e){return Dn(Hu,e)||""}function Qi(e){pr(Hu,e)}function eT(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 tT(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 nT(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 si({entries:e,defaultShowThinking:n=!1}){const[s,a]=i.useState({}),r=nT(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?eT(o):void 0,h=o.question&&m!==void 0?tT(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 Ap="fusion-tab-id";function sT(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Ia(){if(typeof window>"u")return"server-tab";const e=window.sessionStorage.getItem(Ap);if(e)return e;const n=sT();return window.sessionStorage.setItem(Ap,n),n}function lc(e){const n=i.useMemo(()=>Ia(),[]),[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(v1(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=y1(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=Mi(`/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:ii("/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(w1(e,n)),a(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:d,isLoading:l}}const iT="fusion:ai-session-sync",Pp="fusion:ai-session-sync",aT=3e4,rT=6e4;function ki(){return Date.now()}function oT(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Rp(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 lT{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=oT(),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:ki()})}broadcastUpdate(n){const s=n.timestamp??ki();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??ki();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=ki();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=ki();this.releaseTabOwnership(n,s,a),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:a})}broadcastHeartbeat(n){const s=ki();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(iT),this.channel.onmessage=s=>{const a=Rp(s.data);a&&this.handleIncomingMessage(a)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==Pp||!s.newValue))try{const a=JSON.parse(s.newValue),r=Rp(a.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=ki();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},aT)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,a]of this.ownedSessions.entries()){const r=ki();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(Pp,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:ki()});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=ki(),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>rT;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 ji=new lT;function _r(){const e=i.useSyncExternalStore(c=>ji.subscribe(c),()=>ji.getSnapshot(),()=>ji.getSnapshot());i.useEffect(()=>{ji.requestSync()},[]);const n=i.useCallback(c=>{ji.broadcastUpdate(c)},[]),s=i.useCallback(c=>{ji.broadcastCompleted(c)},[]),a=i.useCallback((c,d)=>{ji.broadcastLock(c,d)},[]),r=i.useCallback((c,d)=>{ji.broadcastUnlock(c,d)},[]),o=i.useCallback(c=>{ji.broadcastHeartbeat(c)},[]),l=i.useCallback(()=>{ji.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:a,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function cT(e,n){return e&&n?`${e}/${n}`:""}function dT(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 uT=["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 mT({isOpen:e,onClose:n,onMissionCreated:s,projectId:a,initialGoal:r,resumeSessionId:o}){vi(e);const[l,c]=i.useState(""),[d,u]=i.useState({type:"initial"}),[m,h]=i.useState(null),[f,p]=i.useState([]),[g,x]=i.useState([]),[w,b]=i.useState(null),[y,S]=i.useState(!1),k=i.useRef(!1),[C,v]=i.useState(""),[j,P]=i.useState(!0),[U,E]=i.useState(!1),[R,L]=i.useState(!1),[F,M]=i.useState(!1),O=i.useRef(null),q=i.useRef(null),te=i.useRef(null),Z=i.useRef(null),[K,A]=i.useState(o??null),I=i.useMemo(()=>Ia(),[]),{isLockedByOther:$,takeControl:N,isLoading:G}=lc(e?K:null),{activeTabMap:ge,broadcastUpdate:je,broadcastCompleted:ke,broadcastLock:ne,broadcastUnlock:qe,broadcastHeartbeat:ee}=_r(),{confirm:le}=ai(),[se,re]=i.useState(void 0),[J,B]=i.useState(void 0),[ve,Ne]=i.useState([]),[H,be]=i.useState(!0),[ce,Me]=i.useState(null),[Le,He]=i.useState([]),[gt,Ue]=i.useState([]),pe=cT(se,J);i.useEffect(()=>{(async()=>{try{be(!0);const Ae=await Os();Ne(Ae.models),He(Ae.favoriteProviders),Ue(Ae.favoriteModels)}catch(Ae){Me(Re(Ae)||"Failed to load models")}finally{be(!1)}})()},[]);const Oe=i.useCallback(we=>{He(Ae=>{const he=Ae,me=he.includes(we)?he.filter(nt=>nt!==we):[we,...he];return kn({favoriteProviders:me,favoriteModels:gt}).catch(()=>{He(he)}),me})},[gt]),ze=i.useCallback(we=>{Ue(Ae=>{const he=Ae,me=he.includes(we)?he.filter(nt=>nt!==we):[we,...he];return kn({favoriteProviders:Le,favoriteModels:me}).catch(()=>{Ue(he)}),me})},[Le]),lt=i.useCallback((we,Ae)=>{if(!we||!Ae)return"Using default";const he=ve.find(We=>We.provider===we&&We.id===Ae);return he?`${he.provider}/${he.id}`:`${we}/${Ae}`},[ve]),Be=i.useCallback(we=>{q.current?.close();const Ae=a1(we,a,{onThinking:he=>{v(We=>We+he),je({sessionId:we,status:"generating",needsInput:!1,owningTabId:I,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onQuestion:he=>{E(!1),L(!1),Qi(a),u({type:"question",sessionId:we,question:he}),v(""),S(!0),je({sessionId:we,status:"awaiting_input",needsInput:!0,owningTabId:I,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onSummary:he=>{E(!1),L(!1),Qi(a),u({type:"summary",sessionId:we,summary:he}),b(he),v(""),S(!0),je({sessionId:we,status:"complete",needsInput:!1,owningTabId:I,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onError:he=>{const We=he||"Session failed while contacting the AI.";E(!1),L(!1),h(null),u({type:"error",sessionId:we,errorMessage:We}),v(""),S(!0),te.current=we,je({sessionId:we,status:"error",needsInput:!1,owningTabId:I,type:"mission_interview",title:l.trim()||void 0,projectId:a??null}),ke({sessionId:we,status:"error"})},onComplete:()=>{E(!1),L(!1),te.current=null,ke({sessionId:we,status:"complete"})},onConnectionStateChange:he=>{E(he==="reconnecting")}});q.current=Ae},[ke,je,l,a,I]),ye=i.useCallback(async we=>{const Ae=we??l;if(Ae.trim()){h(null),v(""),p([]),x([]),E(!1),u({type:"loading"});try{const{sessionId:he}=await t1(Ae.trim(),a,se&&J?{modelProvider:se,modelId:J}:void 0);te.current=he,A(he),Qi(a),Be(he),p([])}catch(he){E(!1),h(Re(he)||"Failed to start interview session"),u({type:"initial"}),te.current=null,A(null)}}},[Be,l,se,J,a]);i.useEffect(()=>{e&&d.type==="initial"&&O.current?.focus()},[e,d.type]),i.useEffect(()=>{if(e&&!r&&!o&&!k.current&&d.type==="initial"){const we=ZI(a);we&&c(we)}},[e]),i.useEffect(()=>{if(e&&r&&!k.current&&d.type==="initial"){c(r);const we=setTimeout(()=>{k.current=!0,ye(r)},0);return()=>clearTimeout(we)}},[e,r,d.type,ye]),i.useEffect(()=>{e||(k.current=!1,E(!1),L(!1),A(null))},[e]),i.useEffect(()=>{if(!e||!o||d.type!=="initial")return;let we=!1;return Ci(o).then(Ae=>{if(we||!Ae)return;const he=hr(Ae.conversationHistory);if(x(he),A(Ae.id),p(he.map(We=>We.response).filter(We=>!!(We&&typeof We=="object"&&!Array.isArray(We)))),Ae.status==="awaiting_input"&&Ae.currentQuestion)try{Qi(a);const We=JSON.parse(Ae.currentQuestion);te.current=Ae.id,S(!0),u({type:"question",sessionId:Ae.id,question:We})}catch{h("Failed to restore session question.")}else if(Ae.status==="complete"&&Ae.result)try{Qi(a);const We=JSON.parse(Ae.result);te.current=Ae.id,S(!0),b(We),u({type:"summary",sessionId:Ae.id,summary:We})}catch{h("Failed to restore session result.")}else Ae.status==="generating"?(te.current=Ae.id,S(!0),Ae.thinkingOutput&&v(Ae.thinkingOutput),u({type:"loading"}),Be(Ae.id)):Ae.status==="error"&&(te.current=Ae.id,S(!0),h(null),u({type:"error",sessionId:Ae.id,errorMessage:Ae.error??"The session encountered an error."}))}).catch(()=>{we||h("Failed to resume session.")}),()=>{we=!0}},[Be,e,o,d.type,a]),i.useEffect(()=>{if(!e){Z.current&&(qe(Z.current,I),Z.current=null);return}if(K&&Z.current!==K){Z.current&&qe(Z.current,I),ne(K,I),Z.current=K;return}!K&&Z.current&&(qe(Z.current,I),Z.current=null)},[ne,qe,e,K,I]),i.useEffect(()=>{if(!e||!K||Z.current!==K)return;ee(I);const we=setInterval(()=>{ee(I)},3e4);return()=>{clearInterval(we)}},[ee,e,K,I]),i.useEffect(()=>()=>{q.current?.close(),q.current=null,Z.current&&(qe(Z.current,I),Z.current=null)},[qe,I]),i.useEffect(()=>{if(!e)return;const we=Ae=>{(d.type==="question"||d.type==="summary")&&(Ae.preventDefault(),Ae.returnValue=""),q.current?.close()};return window.addEventListener("beforeunload",we),()=>window.removeEventListener("beforeunload",we)},[e,d]);const Y=i.useCallback(()=>{q.current?.close(),q.current=null,n()},[n]),_e=i.useCallback(async()=>{if(l&&XI(l,a),!(y&&!await le({title:"Close Interview",message:"Are you sure you want to close? Your interview progress will be lost.",danger:!0}))){if(q.current?.close(),q.current=null,d.type==="question"||d.type==="summary"||d.type==="error")try{await Ig(d.sessionId,a,I)}catch{}c(""),u({type:"initial"}),h(null),p([]),x([]),b(null),v(""),E(!1),L(!1),S(!1),M(!1),re(void 0),B(void 0),te.current=null,A(null),n()}},[l,y,d,n,a,I,le]);i.useEffect(()=>{if(!e)return;const we=Ae=>{Ae.key==="Escape"&&_e()};return document.addEventListener("keydown",we),()=>document.removeEventListener("keydown",we)},[e,_e]);const ct=i.useCallback(async we=>{if(d.type!=="question")return;const{sessionId:Ae}=d;h(null),p(he=>[...he,we]),x(he=>[...he,{question:d.question,response:we}]),u({type:"loading"}),v("");try{Be(Ae),await n1(Ae,we,a,I),S(!0)}catch(he){q.current?.close(),q.current=null,h(Re(he)||"Failed to submit response"),u({type:"question",sessionId:Ae,question:d.question})}},[d,a,I,Be]),pt=i.useCallback(async()=>{if(d.type!=="error")return;const we=d.sessionId;h(null),L(!0),v(""),u({type:"loading"}),Be(we);try{te.current=we,A(we),await s1(we,a,I)}catch(Ae){let he=Ae;if((Re(Ae)||"").includes("not in an error state"))try{const me=await Ci(we);if(!me)throw new Error("Failed to refresh interview session.");const nt=hr(me.conversationHistory);if(x(nt),p(nt.map(Ct=>Ct.response).filter(Ct=>!!(Ct&&typeof Ct=="object"&&!Array.isArray(Ct)))),te.current=me.id,A(me.id),S(!0),me.status==="generating")v(me.thinkingOutput??""),u({type:"loading"}),q.current?.isConnected()||Be(me.id);else if(me.status==="awaiting_input"){if(!me.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");Qi(a);const Ct=JSON.parse(me.currentQuestion);u({type:"question",sessionId:me.id,question:Ct}),q.current?.isConnected()||Be(me.id)}else if(me.status==="complete"){if(!me.result)throw new Error("Interview session is complete but has no result.");Qi(a);const Ct=JSON.parse(me.result);b(Ct),u({type:"summary",sessionId:me.id,summary:Ct})}else me.status==="error"&&u({type:"error",sessionId:me.id,errorMessage:me.error??"Retry failed. Please try again."});E(!1);return}catch(me){he=me}q.current?.close(),q.current=null,u({type:"error",sessionId:we,errorMessage:Re(he)||"Retry failed. Please try again."}),E(!1)}finally{L(!1)}},[Be,a,I,d]),de=i.useCallback(async()=>{if(d.type==="summary"){h(null),M(!0);try{const we=await i1(d.sessionId,w||void 0,a);s(we),Qi(a),q.current?.close(),q.current=null,c(""),u({type:"initial"}),h(null),p([]),x([]),b(null),v(""),E(!1),L(!1),S(!1),M(!1),te.current=null,A(null),n()}catch(we){h(Re(we)||"Failed to create mission"),M(!1)}}},[d,w,s,n,a]),Ve=()=>d.type==="question"?Math.min(f.length+1,6):6,Ee=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",$e=K?ge.get(K):null,ut=$e&&$e.tabId!==I,ht=!!(ut&&!$e.stale),Se=$&&(!ut||$e.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:we=>we.target===we.currentTarget&&_e(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(vs,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Plan Mission with AI"})]}),t.jsxs("div",{className:"modal-header-actions",children:[Ee&&t.jsx("button",{className:"modal-send-to-background",onClick:Y,title:"Send to background","aria-label":"Send to background",children:t.jsx(jo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:_e,"aria-label":"Close",children:t.jsx(nn,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[m&&t.jsx("div",{className:"form-error planning-error",children:m}),U&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),ht&&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(ps,{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:O,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:we=>c(we.target.value),onKeyDown:we=>{we.key==="Enter"&&!we.shiftKey&&l.trim()&&(we.preventDefault(),ye())}})]}),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:uT.map((we,Ae)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c(we),children:we.length>45?we.slice(0,45)+"...":we},Ae))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",H&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(ys,{id:"mission-interview-modal-model",label:"Planning Model",value:pe,onChange:we=>{const{provider:Ae,modelId:he}=dT(we);re(Ae),B(he)},models:ve,disabled:H,favoriteProviders:Le,onToggleFavorite:Oe,favoriteModels:gt,onToggleModelFavorite:ze}),ce&&t.jsxs("div",{className:"form-hint form-hint-error",children:[ce," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{be(!0);const we=await Os();Ne(we.models),He(we.favoriteProviders),Ue(we.favoriteModels),Me(null)}catch(we){Me(Re(we)||"Failed to load models")}finally{be(!1)}})()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${se&&J?"model-badge-custom":"model-badge-default"}`,children:lt(se,J)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>ye(),disabled:!l.trim(),children:[t.jsx(vs,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),d.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(xt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:C?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>P(!j),type:"button",children:j?"Hide thinking":"Show thinking"}),j&&C&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:C})})]})]}),d.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[g.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(si,{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 pt(),disabled:R,children:[R?t.jsx(xt,{size:14,className:"spin"}):t.jsx(rs,{size:14}),t.jsx("span",{className:"icon-ml-6",children:R?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:_e,disabled:R,children:"Cancel"})]})]})]})}),d.type==="question"&&t.jsx(hT,{question:d.question,progress:Ve(),historyEntries:g,onSubmit:ct}),d.type==="summary"&&w&&t.jsx(pT,{summary:w,historyEntries:g,onSummaryChange:b,onApprove:de,onStartOver:()=>{u({type:"initial"}),S(!1),b(null),p([]),x([]),A(null),q.current?.close(),q.current=null},isCreating:F}),$&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Yl,{size:16}),t.jsx("span",{children:Se?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Se&&t.jsx("button",{type:"button",onClick:()=>{N()},disabled:G,className:"btn btn-primary session-lock-take-control",children:G?"Taking control...":"Take Control"})]})})]})]})}):null}function hT({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(si,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(f=>t.jsx("div",{className:`planning-progress-step ${f<=n?"active":""}`},f))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:l,onChange:f=>c(f.target.value),onKeyDown:f=>{f.key==="Enter"&&!f.shiftKey&&l.trim()&&(f.preventDefault(),m())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(f=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:f.id,checked:r[e.id]===f.id,onChange:()=>o({[e.id]:f.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(f=>{const p=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:f.id,checked:p.includes(f.id),onChange:g=>{const x=g.target.checked?[...p,f.id]:p.filter(w=>w!==f.id);o({[e.id]:x})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx($n,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(nn,{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(yo,{size:16,className:"icon-ml-4"})]})})]})}function pT({summary:e,historyEntries:n,onSummaryChange:s,onApprove:a,onStartOver:r,isCreating:o}){const[l,c]=i.useState(()=>new Set(e.milestones.map((k,C)=>C))),[d,u]=i.useState(()=>{const k=new Set;return e.milestones.forEach((C,v)=>{C.slices.forEach((j,P)=>k.add(`${v}-${P}`))}),k}),m=k=>{c(C=>{const v=new Set(C);return v.has(k)?v.delete(k):v.add(k),v})},h=k=>{u(C=>{const v=new Set(C);return v.has(k)?v.delete(k):v.add(k),v})},f=(k,C)=>{const v=[...e.milestones];v[k]={...v[k],...C},s({...e,milestones:v})},p=(k,C,v)=>{const j=[...e.milestones],P=[...j[k].slices];P[C]={...P[C],...v},j[k]={...j[k],slices:P},s({...e,milestones:j})},g=(k,C,v,j)=>{const P=[...e.milestones],U=[...P[k].slices],E=[...U[C].features];E[v]={...E[v],...j},U[C]={...U[C],features:E},P[k]={...P[k],slices:U},s({...e,milestones:P})},x=k=>{const C=e.milestones.filter((v,j)=>j!==k);s({...e,milestones:C})},w=(k,C)=>{const v=[...e.milestones];v[k]={...v[k],slices:v[k].slices.filter((j,P)=>P!==C)},s({...e,milestones:v})},b=(k,C,v)=>{const j=[...e.milestones],P=[...j[k].slices];P[C]={...P[C],features:P[C].features.filter((U,E)=>E!==v)},j[k]={...j[k],slices:P},s({...e,milestones:j})},y=(k,C)=>{const v=[...e.milestones],j=[...v[k].slices];j[C]={...j[C],features:[...j[C].features,{title:"New feature",description:""}]},v[k]={...v[k],slices:j},s({...e,milestones:v})},S=e.milestones.reduce((k,C)=>k+C.slices.reduce((v,j)=>v+j.features.length,0),0);return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(si,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx($n,{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:k=>s({...e,missionTitle:k.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Description"}),t.jsx("textarea",{className:"planning-textarea",rows:3,value:e.missionDescription||"",onChange:k=>s({...e,missionDescription:k.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Roadmap"}),t.jsx("div",{className:"roadmap-list",children:e.milestones.map((k,C)=>t.jsxs("div",{className:"roadmap-card",children:[t.jsxs("div",{className:"roadmap-card-header",onClick:()=>m(C),children:[l.has(C)?t.jsx(rn,{size:16,className:"icon-text-secondary"}):t.jsx(Mn,{size:16,className:"icon-text-secondary"}),t.jsx(ja,{size:16,className:"icon-milestone"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:k.title,onChange:v=>f(C,{title:v.target.value}),onClick:v=>v.stopPropagation()}),e.milestones.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:v=>{v.stopPropagation(),x(C)},title:"Remove milestone",children:t.jsx(vn,{size:14,className:"icon-text-secondary"})})]}),l.has(C)&&t.jsxs("div",{className:"roadmap-card-body",children:[t.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:k.description||"",onChange:v=>f(C,{description:v.target.value})}),t.jsxs("div",{className:"roadmap-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Verification Criteria"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-sm",rows:2,placeholder:"How to confirm this milestone is complete...",value:k.verification||"",onChange:v=>f(C,{verification:v.target.value})})]}),k.slices.map((v,j)=>{const P=`${C}-${j}`;return t.jsxs("div",{className:"roadmap-slice-card",children:[t.jsxs("div",{className:"roadmap-slice-header",onClick:()=>h(P),children:[d.has(P)?t.jsx(rn,{size:14,className:"icon-text-secondary"}):t.jsx(Mn,{size:14,className:"icon-text-secondary"}),t.jsx(_d,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:v.title,onChange:U=>p(C,j,{title:U.target.value}),onClick:U=>U.stopPropagation()}),k.slices.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:U=>{U.stopPropagation(),w(C,j)},title:"Remove slice",children:t.jsx(vn,{size:12,className:"icon-text-secondary"})})]}),d.has(P)&&t.jsxs("div",{className:"roadmap-slice-body",children:[t.jsxs("div",{className:"roadmap-slice-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Slice Verification"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-xs",rows:1,placeholder:"How to confirm this slice is done...",value:v.verification||"",onChange:U=>p(C,j,{verification:U.target.value})})]}),v.features.map((U,E)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(kd,{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:U.title,onChange:R=>g(C,j,E,{title:R.target.value})}),U.description&&t.jsx("p",{className:"roadmap-feature-text",children:U.description}),U.acceptanceCriteria&&t.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",U.acceptanceCriteria]})]}),t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>b(C,j,E),title:"Remove feature",children:t.jsx(vn,{size:12,className:"icon-text-secondary"})})]},E)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>y(C,j),children:[t.jsx(bn,{size:12}),"Add Feature"]})]})]},j)})]})]},C))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:o,children:[t.jsx(Aa,{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(xt,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):t.jsxs(t.Fragment,{children:[t.jsx($n,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}const fT=30,gT=16,bT=16;function xT(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let yl=null;function Sx(){return yl===null&&(yl=window.visualViewport?.height??window.innerHeight),yl}function vT(e){const n=Sx();e>n&&(yl=e)}function yT(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 Ip(){if(typeof window>"u"||!window.visualViewport)return{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0};const e=window.visualViewport,n=yT(document.activeElement),s=e.offsetTop;n||vT(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=Sx(),o=Math.max(0,r-e.offsetTop-e.height);if(o>=fT&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};if(o>=gT&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};const l=Math.max(0,r-e.height);return n&&l>=bT?{overlap:0,open:!0,vvHeight:e.height,vvOffsetTop:s}:{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0}}function Wi({enabled:e=!0}={}){const[n,s]=i.useState(0),[a,r]=i.useState(null),[o,l]=i.useState(0),[c,d]=i.useState(!1);return i.useEffect(()=>{if(!e||!xT()){s(0),r(null),l(0),d(!1);return}const u=window.visualViewport;if(!u){s(0),r(null),l(0),d(!1);return}const m=()=>{const v=Ip();s(v.overlap),r(v.vvHeight),l(v.vvOffsetTop),d(v.open)},h=()=>{const v=Ip();s(v.overlap),r(v.vvHeight),d(v.open)},f=[],p=v=>{if(typeof window>"u")return;const j=window.setTimeout(()=>{typeof window>"u"||m()},v);f.push(j)};let g=null,x=0,w=-1,b=0;const y=()=>{g!==null&&typeof window<"u"&&(window.cancelAnimationFrame(g),g=null)},S=()=>{if(typeof window>"u")return;m();const v=window.visualViewport?.offsetTop??0;if(v===w?b+=1:(b=0,w=v),b>=2||performance.now()>x){g=null;return}g=window.requestAnimationFrame(S)},k=()=>{typeof window>"u"||(y(),x=performance.now()+1500,w=-1,b=0,g=window.requestAnimationFrame(S))},C=()=>{m(),p(50),p(200),p(500),p(1e3),p(1500),k()};return C(),u.addEventListener("resize",m),u.addEventListener("scroll",h),document.addEventListener("focusin",C),document.addEventListener("focusout",m),document.addEventListener("visibilitychange",C),window.addEventListener("pageshow",C),()=>{u.removeEventListener("resize",m),u.removeEventListener("scroll",h),document.removeEventListener("focusin",C),document.removeEventListener("focusout",m),document.removeEventListener("visibilitychange",C),window.removeEventListener("pageshow",C);for(const v of f)clearTimeout(v);y(),s(0),r(null),l(0),d(!1)}},[e]),{keyboardOverlap:n,viewportHeight:a,viewportOffsetTop:o,keyboardOpen:c}}function wT({isOpen:e,onClose:n,onApplied:s,targetType:a,targetId:r,targetTitle:o,missionContext:l,projectId:c,resumeSessionId:d}){const u=Ys();vi(e);const{keyboardOverlap:m,viewportHeight:h,viewportOffsetTop:f,keyboardOpen:p}=Wi({enabled:u==="mobile"}),g=p?{"--keyboard-overlap":`${m}px`,"--vv-offset-top":`${f}px`,...h!==null?{"--vv-height":`${h}px`}:{}}:{},[x,w]=i.useState({type:"initial"}),[b,y]=i.useState(null),[S,k]=i.useState([]),[C,v]=i.useState([]),[j,P]=i.useState(null),[U,E]=i.useState(""),[R,L]=i.useState(!0),[F,M]=i.useState(!1),[O,q]=i.useState(!1),te=i.useRef(null),Z=i.useRef(null),K=i.useRef(null),A=i.useRef(null),[I,$]=i.useState(null),N=i.useMemo(()=>Ia(),[]);lc(e?I:null);const{activeTabMap:G,broadcastUpdate:ge,broadcastCompleted:je,broadcastLock:ke,broadcastUnlock:ne,broadcastHeartbeat:qe}=_r(),ee=a==="milestone"?r1:u1,le=a==="milestone"?o1:m1,se=a==="milestone"?l1:h1,re=a==="milestone"?c1:p1,J=a==="milestone"?d1:f1,B=a==="milestone"?"Milestone":"Slice",ve=a==="milestone"?"milestone_interview":"slice_interview",Ne=i.useCallback(Be=>{Z.current?.close();const ye=se(Be,c,{onThinking:Y=>{E(_e=>_e+Y),ge({sessionId:Be,status:"generating",needsInput:!1,owningTabId:N,type:ve,title:o,projectId:c??null})},onQuestion:Y=>{M(!1),H(),w({type:"question",sessionId:Be,question:Y}),E(""),ge({sessionId:Be,status:"awaiting_input",needsInput:!0,owningTabId:N,type:ve,title:o,projectId:c??null})},onSummary:Y=>{M(!1),H(),w({type:"summary",sessionId:Be,summary:Y}),P(Y),E(""),ge({sessionId:Be,status:"complete",needsInput:!1,owningTabId:N,type:ve,title:o,projectId:c??null})},onError:Y=>{const _e=Y||"Session failed while contacting the AI.";M(!1),y(null),w({type:"error",sessionId:Be,errorMessage:_e}),E(""),K.current=Be,ge({sessionId:Be,status:"error",needsInput:!1,owningTabId:N,type:ve,title:o,projectId:c??null}),je({sessionId:Be,status:"error"})},onComplete:()=>{M(!1),K.current=null,je({sessionId:Be,status:"complete"})},onConnectionStateChange:Y=>{M(Y==="reconnecting")}});Z.current=ye},[je,ge,se,ve,c,N,o]),H=()=>{P(null),k([]),v([]),E("")},be=i.useCallback(async()=>{y(null),H(),M(!1),w({type:"loading"});try{const{sessionId:Be}=await ee(r,c);K.current=Be,$(Be),Ne(Be)}catch(Be){M(!1),y(Re(Be)||`Failed to start ${B.toLowerCase()} interview`),w({type:"initial"}),K.current=null,$(null)}},[Ne,c,ee,r,B]),ce=i.useCallback(async()=>{y(null),q(!0);try{await J(r,c),s(),w({type:"applied"})}catch(Be){y(Re(Be)||`Failed to skip ${B.toLowerCase()} interview`),q(!1)}},[s,c,J,r,B]);i.useEffect(()=>{e&&x.type==="initial"&&te.current?.focus()},[e,x.type]),i.useEffect(()=>{if(!e||!d||x.type!=="initial")return;let Be=!1;return Ci(d).then(ye=>{if(Be||!ye)return;const Y=hr(ye.conversationHistory);if(v(Y),$(ye.id),k(Y.map(_e=>_e.response).filter(_e=>!!(_e&&typeof _e=="object"&&!Array.isArray(_e)))),ye.status==="awaiting_input"&&ye.currentQuestion)try{const _e=JSON.parse(ye.currentQuestion);K.current=ye.id,w({type:"question",sessionId:ye.id,question:_e})}catch{y("Failed to restore session question.")}else if(ye.status==="complete"&&ye.result)try{const _e=JSON.parse(ye.result);K.current=ye.id,P(_e),w({type:"summary",sessionId:ye.id,summary:_e})}catch{y("Failed to restore session result.")}else ye.status==="generating"?(K.current=ye.id,ye.thinkingOutput&&E(ye.thinkingOutput),w({type:"loading"}),Ne(ye.id)):ye.status==="error"&&(K.current=ye.id,y(null),w({type:"error",sessionId:ye.id,errorMessage:ye.error??"The session encountered an error."}))}).catch(()=>{Be||y("Failed to resume session.")}),()=>{Be=!0}},[Ne,e,d,x.type]),i.useEffect(()=>{e||(M(!1),$(null))},[e]),i.useEffect(()=>{if(!(!e||!I)){if(A.current!==I){A.current&&ne(A.current,N),ke(I,N),A.current=I;return}!I&&A.current&&(ne(A.current,N),A.current=null)}},[ke,ne,e,I,N]),i.useEffect(()=>{if(!e||!I||A.current!==I)return;qe(N);const Be=setInterval(()=>{qe(N)},3e4);return()=>{clearInterval(Be)}},[qe,e,I,N]),i.useEffect(()=>()=>{Z.current?.close(),Z.current=null,A.current&&(ne(A.current,N),A.current=null)},[ne,N]);const Me=i.useCallback(()=>{Z.current?.close(),Z.current=null,n()},[n]),Le=i.useCallback(async()=>{Z.current?.close(),Z.current=null,H(),w({type:"initial"}),y(null),K.current=null,$(null),n()},[n]),He=i.useCallback(async Be=>{if(x.type!=="question")return;const{sessionId:ye}=x;y(null),k(Y=>[...Y,Be]),v(Y=>[...Y,{question:x.question,response:Be}]),w({type:"loading"}),E("");try{Ne(ye),await le(ye,Be,c,N)}catch(Y){Z.current?.close(),Z.current=null,y(Re(Y)||"Failed to submit response"),w({type:"question",sessionId:ye,question:x.question})}},[Ne,c,le,N,x]),gt=i.useCallback(async()=>{if(x.type==="summary"){y(null),q(!0);try{await re(x.sessionId,j||void 0,c),s(),w({type:"applied"})}catch(Be){y(Re(Be)||"Failed to apply interview results"),q(!1)}}},[re,j,s,c,x]),Ue=()=>x.type==="question"?Math.min(S.length+1,6):6,pe=x.type==="loading"||x.type==="question"||x.type==="summary"||x.type==="error",Oe=I?G.get(I):null,lt=!!(Oe&&Oe.tabId!==N&&!Oe.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Be=>Be.target===Be.currentTarget&&Le(),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(ps,{size:20,className:"icon-triage"}),t.jsxs("h3",{children:["Plan ",B,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[pe&&t.jsx("button",{className:"modal-send-to-background",onClick:Me,title:"Send to background","aria-label":"Send to background",children:t.jsx(jo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:Le,"aria-label":"Close",children:t.jsx(nn,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[b&&t.jsx("div",{className:"form-error planning-error",children:b}),F&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),lt&&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(ps,{size:32,className:"icon-triage-lg"}),t.jsxs("h4",{children:["Refine ",B," 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 be(),children:[t.jsx(ps,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void ce(),disabled:O,children:[O?t.jsx(xt,{size:16,className:"spin"}):null,"Use Mission Context"]}),t.jsx("button",{className:"btn",onClick:Le,children:"Cancel"})]})]}),x.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(xt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:U?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>L(!R),type:"button",children:R?"Hide thinking":"Show thinking"}),R&&U&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:U})})]})]}),x.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[C.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(si,{entries:C}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:x.errorMessage}),t.jsx("div",{className:"ai-error-actions",children:t.jsx("button",{className:"btn",onClick:Le,children:"Cancel"})})]})]})}),x.type==="question"&&t.jsx(kT,{question:x.question,progress:Ue(),historyEntries:C,onSubmit:He}),x.type==="summary"&&j&&t.jsx(jT,{summary:j,historyEntries:C,onSummaryChange:P,onApply:gt,onCancel:Le,isApplying:O}),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($n,{size:48,className:"icon-success"}),t.jsxs("h4",{children:[B," 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 kT({question:e,progress:n,historyEntries:s,onSubmit:a}){const[r,o]=i.useState({}),[l,c]=i.useState(""),[d,u]=i.useState(""),m=i.useCallback(()=>{let f;e.type==="text"?f={[e.id]:l}:e.type==="confirm"?f={[e.id]:r[e.id]===!0}:f=r;const p=d.trim();p.length>0&&(f={...f,_comment:p}),a(f)},[d,e,r,l,a]);i.useEffect(()=>{o({}),c(""),u("")},[e.id]);const h=()=>{switch(e.type){case"text":return l.trim().length>0;case"single_select":return r[e.id]!==void 0;case"multi_select":return Array.isArray(r[e.id])&&r[e.id].length>0;case"confirm":return r[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(si,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(f=>t.jsx("div",{className:`planning-progress-step ${f<=n?"active":""}`},f))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:l,onChange:f=>c(f.target.value),onKeyDown:f=>{f.key==="Enter"&&!f.shiftKey&&l.trim()&&(f.preventDefault(),m())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(f=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:f.id,checked:r[e.id]===f.id,onChange:()=>o({[e.id]:f.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(f=>{const p=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:f.id,checked:p.includes(f.id),onChange:g=>{const x=g.target.checked?[...p,f.id]:p.filter(w=>w!==f.id);o({[e.id]:x})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx($n,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(nn,{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(yo,{size:16,className:"icon-ml-4"})]})})]})}function jT({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(si,{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(rn,{size:16}):t.jsx(Mn,{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(xt,{size:16,className:"spin"}):null,"Apply"]}),t.jsx("button",{className:"btn",onClick:r,disabled:o,children:"Cancel"})]})]})}const Tp=300,tl=220,nl=560,$p="fusion:mission-sidebar-width",Fr={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)"}},Dp={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)"}},Lp={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)"}},sl={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)"}},il={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)"}},al={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)"}},Op={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)"}},NT=3;function ST(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function zp({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 Fp(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const Up={title:"",description:"",status:"planning",autopilotEnabled:!1},td={title:"",description:"",status:"planning",dependencies:[]},nd={title:"",description:"",status:"pending"},sd={title:"",description:"",acceptanceCriteria:"",status:"defined"},CT=3600*1e3;function Ol(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 ET(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=CT,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 _T(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 MT(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 id(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 Cx=["feature_triaged","feature_completed"],Ex=["slice_activated","slice_completed","milestone_completed"],_x=["mission_started","mission_paused","mission_resumed","mission_completed"],Mx=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function Bp(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return _x.includes(e);case"tasks":return Cx.includes(e);case"slices":return Ex.includes(e);case"autopilot":return Mx.includes(e);default:return!0}}function AT(e){return e==="error"||e==="warning"?"mission-event__type--error":_x.includes(e)?"mission-event__type--state":Cx.includes(e)?"mission-event__type--task":Ex.includes(e)?"mission-event__type--slice":Mx.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function PT(e){return e.replace(/_/g," ")}function RT(e,n){return n?e==="watching"?`Watching since ${Ol(n)}`:`Last activation ${Ol(n)}`:null}function IT({isOpen:e,isInline:n=!1,onClose:s,addToast:a,projectId:r,onSelectTask:o,availableTasks:l=[],resumeSessionId:c,targetMissionId:d,milestoneSliceResumeSessionId:u,onMilestoneSliceResumeFetchError:m}){const h=n||e,[f,p]=i.useState([]),[g,x]=i.useState(null),[w,b]=i.useState(!0),[y,S]=i.useState(!1),k=Ys()==="mobile",[C,v]=i.useState(()=>{if(typeof window>"u")return Tp;const V=window.localStorage.getItem($p),Ie=V?Number(V):NaN;return Number.isFinite(Ie)?Math.max(tl,Math.min(nl,Ie)):Tp}),j=i.useCallback(V=>{try{window.localStorage.setItem($p,String(V))}catch{}},[]),P=i.useCallback(V=>{if(k)return;V.preventDefault(),V.stopPropagation();const Ie=V.currentTarget;typeof Ie.setPointerCapture=="function"&&Ie.setPointerCapture(V.pointerId);const z=V.clientX,ue=C;let Xe=ue;document.body.style.userSelect="none";const ft=Ze=>{const st=Ze.clientX-z,Ot=Math.max(tl,Math.min(nl,ue+st));Xe=Ot,v(Ot)},qt=Ze=>{typeof Ie.releasePointerCapture=="function"&&Ie.releasePointerCapture(Ze.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",ft),document.removeEventListener("pointerup",qt),j(Xe)};document.addEventListener("pointermove",ft),document.addEventListener("pointerup",qt)},[k,j,C]),U=i.useCallback(V=>{if(k||V.key!=="ArrowLeft"&&V.key!=="ArrowRight")return;V.preventDefault();const Ie=V.shiftKey?50:10,z=V.key==="ArrowLeft"?-Ie:Ie,ue=Math.max(tl,Math.min(nl,C+z));v(ue),j(ue)},[k,j,C]),[E,R]=i.useState(!1),[L,F]=i.useState(null),[M,O]=i.useState(Up),[q,te]=i.useState(!1),[Z,K]=i.useState(new Set),[A,I]=i.useState(new Set),[$,N]=i.useState(null),[G,ge]=i.useState(td),[je,ke]=i.useState(!1),[ne,qe]=i.useState(null),[ee,le]=i.useState(nd),[se,re]=i.useState(!1),[J,B]=i.useState(null),[ve,Ne]=i.useState(null),[H,be]=i.useState(sd),[ce,Me]=i.useState(!1),[Le,He]=i.useState(null),[gt,Ue]=i.useState(null),[pe,Oe]=i.useState(""),[ze,lt]=i.useState(!1),[Be,ye]=i.useState([]),[Y,_e]=i.useState(void 0),ct=Y??c,[pt,de]=i.useState(null),[Ve,Ee]=i.useState(null),[$e,ut]=i.useState(null);i.useEffect(()=>{h&&ct&<(!0)},[h,ct]),i.useEffect(()=>{if(!h||ct)return;let V=!1;return hu(r).then(Ie=>{if(V)return;const z=Ie.filter(ue=>ue.type==="mission_interview"&&(ue.status==="awaiting_input"||ue.status==="error"));ye(z)}).catch(Ie=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",Ie)}),()=>{V=!0}},[h,r,ct]),i.useEffect(()=>{if(!h||!u)return;let V=!1;return Ci(u).then(Ie=>{if(!(V||!Ie))try{const z=JSON.parse(Ie.inputPayload||"{}");z.targetId&&z.targetType&&de({type:z.targetType,id:z.targetId,title:z.targetTitle||Ie.title,resumeSessionId:u})}catch{de({type:"milestone",id:"",title:Ie.title,resumeSessionId:u})}}).catch(Ie=>{V||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",Ie),m?.())}),()=>{V=!0}},[h,u,m]);const[ht,Se]=i.useState(null),[we,Ae]=i.useState(new Map),[he,We]=i.useState(null),[me,nt]=i.useState({title:"",assertion:"",status:"pending"}),[Ct,wt]=i.useState(!1),[$t,Vt]=i.useState(null),[Mt,Dt]=i.useState(new Map),[Qt,Kt]=i.useState(new Set),[Bt,on]=i.useState(new Set),[fn,Jt]=i.useState(null),[an,zt]=i.useState(new Map),[en,Zt]=i.useState(null),[dn,xe]=i.useState(null),[Fe,Ke]=i.useState(!0),[et,Qe]=i.useState(new Set),[It,St]=i.useState(new Map),[Ht,jt]=i.useState(null),[ae,De]=i.useState(new Map),[At,Lt]=i.useState(null),[Ft,Pe]=i.useState(new Map),[dt,bt]=i.useState(new Map),[_t,Yt]=i.useState("structure"),[Xt,Te]=i.useState([]),Ye=i.useRef([]),Nt=i.useRef([]),Ut=i.useRef(null),tn=i.useRef(null),Xn=i.useRef("structure"),fe=i.useRef("all"),[at,ot]=i.useState(!1),[rt,mt]=i.useState(0),[vt,ie]=i.useState("all"),[it,Gt]=i.useState(new Set),Cn=i.useRef(null),fs=i.useRef(null);Nt.current=f,Ut.current=g,tn.current=en,Xn.current=_t,fe.current=vt;const On=i.useCallback((V="auto")=>{const Ie=fs.current;if(Ie&&typeof Ie.scrollIntoView=="function"){Ie.scrollIntoView({block:"end",behavior:V});return}const z=Cn.current;z&&(z.scrollTop=z.scrollHeight)},[]),jn=i.useCallback(()=>{const V=Cn.current;return V?V.scrollHeight-V.scrollTop-V.clientHeight<=100:!0},[]),zn=i.useCallback(async V=>{if(V.length===0){bt(new Map);return}const Ie=await _S(r);bt(z=>{const ue=new Map(z);for(const[Xe,ft]of Object.entries(Ie))_T(ft)&&ue.set(Xe,ft);return ue})},[r]),hn=i.useCallback(async()=>{try{b(!0);const V=await jS(r);p(V),zn(V)}catch(V){a(Re(V)||"Failed to load missions","error")}finally{b(!1)}},[a,r,zn]),Et=i.useCallback(async V=>{try{S(!0);const Ie=await Rg(V,r);if(!Ie||!Array.isArray(Ie.milestones)){S(!1);return}if(x(Ie),Ie.milestones.length>0){const z=Ie.milestones[0].id;Zt(z),Ke(!0),K(new Set([z])),pc(z,r).then(ue=>{Ae(Xe=>{const ft=new Map(Xe);return ft.set(z,ue),ft})}).catch(()=>{}),fc(z,r).then(ue=>{zt(Xe=>{const ft=new Map(Xe);return ft.set(z,ue),ft})}).catch(()=>{}),Ie.milestones[0].slices.length>0&&I(new Set([Ie.milestones[0].slices[0].id]))}else Zt(null),xe(null)}catch(Ie){a(Re(Ie)||"Failed to load mission details","error")}finally{S(!1)}},[a,r]);i.useEffect(()=>{if(!h||!en){xe(null);return}let V=!1;return xe(null),wm(en,r).then(Ie=>{if(!V){if(!id(Ie)){xe(null);return}xe(Ie),zt(z=>{const ue=new Map(z);return ue.set(en,Ie.rollup),ue})}}).catch(()=>{V||xe(null)}),()=>{V=!0}},[h,en,r]),i.useEffect(()=>{Ke(!0)},[en]);const En=i.useCallback(V=>{!V||V!==tn.current||wm(V,r).then(Ie=>{tn.current!==V||!id(Ie)||(xe(Ie),zt(z=>{const ue=new Map(z);return ue.set(V,Ie.rollup),ue}))}).catch(()=>{})},[r]),yn=i.useCallback(async(V,Ie)=>{const z=Ie?.append??!1,ue=z?Ye.current.length:0;z||(ot(!0),Gt(new Set));try{const Xe=await ES(V,{limit:50,offset:ue,eventType:void 0},r),ft=Xe.events.filter(qt=>Bp(qt.eventType,vt));Te(qt=>{if(!z)return Ye.current=ft,ft;const Ze=new Set(qt.map(Ot=>Ot.id)),st=[...qt];for(const Ot of ft)Ze.has(Ot.id)||st.push(Ot);return Ye.current=st,st}),mt(Xe.total),z||requestAnimationFrame(()=>{On("auto")})}catch(Xe){a(Re(Xe)||"Failed to load mission activity","error")}finally{z||ot(!1)}},[a,vt,r,On]);i.useEffect(()=>{Ye.current=Xt},[Xt]),i.useEffect(()=>{h&&(hn(),x(null),Zt(null),xe(null),Te([]),mt(0),Yt("structure"),ie("all"),Gt(new Set))},[h,hn]);const ls=i.useRef(null);i.useEffect(()=>{h&&d&&ls.current!==d&&f.length>0&&(ls.current=d,Et(d))},[h,d,f,Et]),i.useEffect(()=>{h||(ls.current=null)},[h]);const cs=i.useRef(!1);i.useEffect(()=>{!h||!n||k||w||cs.current||g||d||f.length!==0&&(cs.current=!0,Et(f[0].id))},[h,n,k,w,f,g,d,Et]),i.useEffect(()=>{h||(cs.current=!1)},[h]),i.useEffect(()=>{!h||!g||_t!=="activity"||yn(g.id)},[_t,h,yn,g,vt]),i.useEffect(()=>{if(!h||typeof EventSource>"u")return;const V=new URLSearchParams;r&&V.set("projectId",r);const Ie=`/api/events${V.size>0?`?${V.toString()}`:""}`,z=()=>{zn(Nt.current)},ue=as=>{z();const Jn=as;if(Jn.data)try{const un=JSON.parse(Jn.data);un?.id&&p(Di=>Di.map(Es=>Es.id===un.id?{...Es,...un}:Es))}catch{}Ut.current&&Et(Ut.current.id)},Xe=as=>{z(),Ut.current&&Et(Ut.current.id)},ft=()=>{z(),Ut.current&&Et(Ut.current.id)},qt=as=>{z(),Ut.current&&Et(Ut.current.id)},Ze=as=>{const Jn=as;if(Jn.data)try{const un=JSON.parse(Jn.data);un&&un.featureId&&(Qs(un.featureId),oi(un.featureId),un.milestoneId&&En(un.milestoneId))}catch{}},st=as=>{const Jn=as;if(Jn.data)try{const un=JSON.parse(Jn.data);un&&un.featureId&&(Qs(un.featureId),oi(un.featureId),un.milestoneId&&En(un.milestoneId),Ut.current&&Et(Ut.current.id))}catch{}},Ot=as=>{const Jn=as;if(Jn.data)try{const un=JSON.parse(Jn.data);un&&un.milestoneId&&(Kn(un.milestoneId),En(un.milestoneId))}catch{}},xn=as=>{const Jn=as;if(Jn.data)try{const un=JSON.parse(Jn.data);un&&un.milestoneId&&(Wn(un.milestoneId),Kn(un.milestoneId),En(un.milestoneId))}catch{}};return ii(Ie,{events:{"mission:updated":ue,"slice:updated":Xe,"feature:updated":ft,"milestone:updated":qt,"mission:event":as=>{z();const Jn=Ut.current;if(!Jn||Xn.current!=="activity")return;const un=jn(),Di=as;if(Di.data)try{const Es=JSON.parse(Di.data);if(!MT(Es)||Es.missionId!==Jn.id||!Bp(Es.eventType,fe.current))return;Te(qs=>{const Ji=qs.filter(fa=>fa.id!==Es.id);return[Es,...Ji].slice(0,100)}),mt(qs=>qs+1),un&&requestAnimationFrame(()=>{const qs=Cn.current;qs&&(qs.scrollTop=0)})}catch{}},"validator-run:started":Ze,"validator-run:completed":st,"milestone:validation:updated":Ot,"assertion:created":xn,"assertion:updated":xn,"assertion:deleted":xn,"assertion:linked":xn,"assertion:unlinked":xn,"fix-feature:created":as=>{const Jn=as;if(Jn.data)try{const un=JSON.parse(Jn.data);if(un&&un.sourceFeatureId){Qs(un.sourceFeatureId);const Di=un?.feature?.sliceId,Es=Ut.current;if(Di&&Es){const qs=Es.milestones.find(Ji=>Ji.slices.some(fa=>fa.id===Di));qs&&En(qs.id)}Ut.current&&Et(Ut.current.id)}}catch{}}}})},[h,jn,Et,zn,r,En]);const Hn=i.useCallback(V=>{F(V.id),R(!1),O({title:V.title,description:V.description||"",status:V.status,autopilotEnabled:V.autopilotEnabled??!1})},[]),qn=i.useCallback(()=>{F(null),R(!1),O(Up)},[]),wn=i.useCallback(async()=>{if(!M.title.trim()){a("Mission title is required","error");return}try{if(te(!0),E)await NS({title:M.title.trim(),description:M.description.trim()||void 0,autopilotEnabled:M.autopilotEnabled},r),a("Mission created","success");else if(L){const V={title:M.title.trim(),description:M.description.trim()||void 0,status:M.status,autopilotEnabled:M.autopilotEnabled};M.autopilotEnabled&&(V.autoAdvance=!0),await SS(L,V,r),a("Mission updated","success"),g?.id===L&&await Et(L)}await hn(),qn()}catch(V){a(Re(V)||"Failed to save mission","error")}finally{te(!1)}},[M,E,L,a,hn,Et,g,qn,r]),Zn=i.useCallback(async V=>{try{await CS(V,r),a("Mission deleted","success"),g?.id===V&&x(null),await hn(),Se(null)}catch(Ie){a(Re(Ie)||"Failed to delete mission","error")}},[a,hn,g,r]),_n=i.useCallback(()=>{ke(!0),N(null),ge(td)},[]),ss=i.useCallback(V=>{N(V.id),ke(!1),ge({title:V.title,description:V.description||"",status:V.status,dependencies:V.dependencies})},[]),Ns=i.useCallback(()=>{N(null),ke(!1),ge(td)},[]),es=i.useCallback(async()=>{if(!G.title.trim()){a("Milestone title is required","error");return}try{te(!0),je&&g?(await MS(g.id,{title:G.title.trim(),description:G.description.trim()||void 0,dependencies:G.dependencies},r),a("Milestone created","success")):$&&(await AS($,{title:G.title.trim(),description:G.description.trim()||void 0,status:G.status,dependencies:G.dependencies},r),a("Milestone updated","success")),await Et(g.id),Ns()}catch(V){a(Re(V)||"Failed to save milestone","error")}finally{te(!1)}},[G,je,$,g,a,Et,Ns,M.title,r]),ks=i.useCallback(async V=>{try{await PS(V,r),a("Milestone deleted","success"),await Et(g.id),Se(null)}catch(Ie){a(Re(Ie)||"Failed to delete milestone","error")}},[a,Et,g,r]),Is=i.useCallback(V=>{Zt(V),Ke(!0),K(Ie=>{const z=new Set(Ie);return!z.has(V)?(z.add(V),pc(V,r).then(Xe=>{Ae(ft=>{const qt=new Map(ft);return qt.set(V,Xe),qt})}).catch(()=>{}),fc(V,r).then(Xe=>{zt(ft=>{const qt=new Map(ft);return qt.set(V,Xe),qt})}).catch(()=>{})):z.delete(V),z})},[r]),Ss=i.useCallback(V=>{B(V),re(!0),qe(null),le(nd)},[]),X=i.useCallback(V=>{qe(V.id),re(!1),le({title:V.title,description:V.description||"",status:V.status})},[]),_=i.useCallback(()=>{qe(null),re(!1),B(null),le(nd)},[]),oe=i.useCallback(async()=>{if(!ee.title.trim()){a("Slice title is required","error");return}try{te(!0),se&&J?(await RS(J,{title:ee.title.trim(),description:ee.description.trim()||void 0},r),a("Slice created","success")):ne&&(await IS(ne,{title:ee.title.trim(),description:ee.description.trim()||void 0,status:ee.status},r),a("Slice updated","success")),await Et(g.id),_()}catch(V){a(Re(V)||"Failed to save slice","error")}finally{te(!1)}},[ee,se,ne,J,g,a,Et,_,r]),D=i.useCallback(async V=>{try{await TS(V,r),a("Slice deleted","success"),await Et(g.id),Se(null)}catch(Ie){a(Re(Ie)||"Failed to delete slice","error")}},[a,Et,g,r]),Q=i.useCallback(async V=>{try{await $S(V,r),a("Slice activated","success"),await Et(g.id)}catch(Ie){a(Re(Ie)||"Failed to activate slice","error")}},[a,Et,g,r]),Ce=i.useCallback(V=>{I(Ie=>{const z=new Set(Ie);return z.has(V)?z.delete(V):z.add(V),z})},[]),Je=i.useCallback(V=>{He(V),Me(!0),Ne(null),be(sd)},[]),kt=i.useCallback(V=>{Ne(V.id),Me(!1),be({title:V.title,description:V.description||"",acceptanceCriteria:V.acceptanceCriteria||"",status:V.status})},[]),Tt=i.useCallback(()=>{Ne(null),Me(!1),He(null),be(sd)},[]),Pt=i.useCallback(async()=>{if(!H.title.trim()){a("Feature title is required","error");return}try{te(!0),ce&&Le?(await DS(Le,{title:H.title.trim(),description:H.description.trim()||void 0,acceptanceCriteria:H.acceptanceCriteria.trim()||void 0},r),a("Feature created","success")):ve&&(await LS(ve,{title:H.title.trim(),description:H.description.trim()||void 0,acceptanceCriteria:H.acceptanceCriteria.trim()||void 0,status:H.status},r),a("Feature updated","success")),await Et(g.id),Tt()}catch(V){a(Re(V)||"Failed to save feature","error")}finally{te(!1)}},[H,ce,ve,Le,g,a,Et,Tt,r]),ln=i.useCallback(async V=>{try{await OS(V,r),a("Feature deleted","success"),await Et(g.id),Se(null)}catch(Ie){a(Re(Ie)||"Failed to delete feature","error")}},[a,Et,g,r]),ts=i.useCallback(async()=>{if(!gt||!pe.trim()){a("Task ID is required","error");return}try{await zS(gt,pe.trim(),r),a("Feature linked to task","success"),await Et(g.id),Ue(null),Oe("")}catch(V){a(Re(V)||"Failed to link feature to task","error")}},[gt,pe,a,Et,g,r]),Pn=i.useCallback(async V=>{try{await FS(V,r),a("Feature unlinked from task","success"),await Et(g.id)}catch(Ie){a(Re(Ie)||"Failed to unlink feature","error")}},[a,Et,g,r]),Fn=i.useCallback(async V=>{try{te(!0),await US(V,void 0,void 0,r),a("Feature triaged — task created","success"),await Et(g.id)}catch(Ie){a(Re(Ie)||"Failed to triage feature","error")}finally{te(!1)}},[a,Et,g,r]),Un=i.useCallback(async V=>{ut(V);try{const Ie=await g1(V,r);Ee({featureId:V,enrichedDescription:Ie.description})}catch{await Fn(V)}finally{ut(null)}},[Fn,r]),gs=i.useCallback(async()=>{Ve&&(Ee(null),await Fn(Ve.featureId))},[Fn,Ve]),Ln=i.useCallback(()=>{Ee(null)},[]),Vn=i.useCallback(async V=>{try{te(!0);const Ie=await BS(V,r);a(`Triaged ${Ie.count} feature${Ie.count!==1?"s":""}`,"success"),await Et(g.id)}catch(Ie){a(Re(Ie)||"Failed to triage slice features","error")}finally{te(!1)}},[a,Et,g,r]),Wn=i.useCallback(async V=>{try{const Ie=await pc(V,r);Ae(z=>{const ue=new Map(z);return ue.set(V,Ie),ue})}catch{}},[r]),Kn=i.useCallback(async V=>{try{const Ie=await fc(V,r);zt(z=>{const ue=new Map(z);return ue.set(V,Ie),ue})}catch{}},[r]),Bn=i.useCallback(async V=>{if(!me.title.trim()||!me.assertion.trim()){a("Title and assertion text are required","error");return}try{te(!0),await HS(V,{title:me.title.trim(),assertion:me.assertion.trim(),status:me.status},r),a("Assertion created","success"),await Wn(V),await Kn(V),wt(!1),nt({title:"",assertion:"",status:"pending"})}catch(Ie){a(Re(Ie)||"Failed to create assertion","error")}finally{te(!1)}},[me,a,Wn,Kn,r]),Nn=i.useCallback(V=>{We(V.id),nt({title:V.title,assertion:V.assertion,status:V.status})},[]),Gn=i.useCallback(()=>{We(null),wt(!1),nt({title:"",assertion:"",status:"pending"})},[]),ds=i.useCallback(async(V,Ie)=>{if(!me.title.trim()||!me.assertion.trim()){a("Title and assertion text are required","error");return}try{te(!0),await qS(V,{title:me.title.trim(),assertion:me.assertion.trim(),status:me.status},r),a("Assertion updated","success"),await Wn(Ie),await Kn(Ie),Gn()}catch(z){a(Re(z)||"Failed to update assertion","error")}finally{te(!1)}},[me,a,Wn,Kn,Gn,r]),Ts=i.useCallback(async V=>{try{const Ie=await KS(V,r);Dt(z=>{const ue=new Map(z);return ue.set(V,Ie),ue})}catch{}},[r]),Ri=i.useCallback(async V=>{const Ie=$t!==V;Vt(z=>z===V?null:V),Ie&&await Ts(V)},[$t,Ts]),ca=i.useCallback(V=>{Vt(V),Ts(V),requestAnimationFrame(()=>{const Ie=document.querySelector(`[data-mission-assertion-id="${V}"]`);Ie instanceof HTMLElement&&typeof Ie.scrollIntoView=="function"&&Ie.scrollIntoView({behavior:"smooth",block:"center"})})},[Ts]),ri=i.useCallback(async(V,Ie)=>{try{Kt(z=>new Set(z).add(Ie)),await VS(V,Ie,r),a("Feature linked to assertion","success"),await Ts(Ie),Jt(null)}catch(z){a(Re(z)||"Failed to link feature","error")}finally{Kt(z=>{const ue=new Set(z);return ue.delete(Ie),ue})}},[a,Ts,r]),Ta=i.useCallback(async(V,Ie)=>{const z=`${V}-${Ie}`;try{on(ue=>new Set(ue).add(z)),await WS(V,Ie,r),a("Feature unlinked from assertion","success"),await Ts(Ie)}catch(ue){a(Re(ue)||"Failed to unlink feature","error")}finally{on(ue=>{const Xe=new Set(ue);return Xe.delete(z),Xe})}},[a,Ts,r]),$a=i.useCallback(async V=>{try{Qe(z=>new Set(z).add(V)),await GS(V,r),a("Validation triggered","success");const Ie=await km(V,r);St(z=>{const ue=new Map(z);return ue.set(V,Ie),ue})}catch(Ie){a(Re(Ie)||"Failed to trigger validation","error")}finally{Qe(Ie=>{const z=new Set(Ie);return z.delete(V),z})}},[a,r]),Qs=i.useCallback(async V=>{try{const Ie=await km(V,r);St(z=>{const ue=new Map(z);return ue.set(V,Ie),ue})}catch{}},[r]),oi=i.useCallback(async V=>{try{const Ie=await JS(V,{limit:10},r);De(z=>{const ue=new Map(z);return ue.set(V,Ie),ue})}catch{}},[r]),Ii=i.useCallback(V=>{const Ie=Ut.current;if(Ie){for(const z of Ie.milestones)for(const ue of z.slices)if(ue.features.find(ft=>ft.id===V)){K(ft=>{const qt=new Set(ft);return qt.add(z.id),qt}),I(ft=>{const qt=new Set(ft);return qt.add(ue.id),qt}),jt(V),Zt(z.id),Qs(V),oi(V),requestAnimationFrame(()=>{const ft=document.querySelector(`[data-mission-feature-id="${V}"]`);ft instanceof HTMLElement&&typeof ft.scrollIntoView=="function"&&ft.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[Qs,oi]),da=i.useCallback(async V=>{try{const Ie=await YS(V,r);Pe(z=>{const ue=new Map(z);return ue.set(V,Ie),ue})}catch{}},[r]),Da=i.useCallback(async V=>{Ht===V?jt(null):(jt(V),await Qs(V),await oi(V))},[Ht,Qs,oi]),La=i.useCallback(async V=>{At===V?Lt(null):(Lt(V),await da(V))},[At,da]),ua=i.useCallback(async V=>{try{await QS(V,r),a("Mission resumed","success"),await Et(V),hn()}catch(Ie){a(Re(Ie)||"Failed to resume mission","error")}},[a,Et,hn,r]),ma=i.useCallback(async V=>{try{const z=(await XS(V,r)).pausedTaskIds?.length??0;a(`Mission stopped (${z} task${z!==1?"s":""} paused)`,"success"),await Et(V),hn()}catch(Ie){a(Re(Ie)||"Failed to stop mission","error")}},[a,Et,hn,r]),Ti=i.useCallback(async V=>{try{await ZS(V,r),a("Mission started — first slice activated","success"),await Et(V),hn()}catch(Ie){a(Re(Ie)||"Failed to start mission","error")}},[a,Et,hn,r]),Oa=i.useCallback(async(V,Ie)=>{try{await e1(V,{enabled:Ie},r),a(Ie?"Autopilot enabled":"Autopilot disabled","success"),await Et(V),hn()}catch(z){a(Re(z)||"Failed to update autopilot","error")}},[a,Et,hn,r]),ha=i.useCallback(V=>{Yt("structure"),Zt(null),xe(null),Te([]),mt(0),ie("all"),Gt(new Set),Et(V.id)},[Et]),Mr=i.useCallback(()=>{x(null),Zt(null),xe(null),Yt("structure"),Te([]),mt(0),ie("all"),Gt(new Set),hn()},[hn]),li=Xt.length<rt,Hs=g?.autopilotState??"inactive",za=Hs==="watching"||Hs==="activating",Fa=RT(Hs,g?.lastAutopilotActivityAt),$i=i.useMemo(()=>!dn||!en||!id(dn)?null:dn.rollup.milestoneId===en?dn:null,[en,dn]),Ua=i.useMemo(()=>{const V=new Map;for(const Ie of $i?.validationTelemetry.validationRounds??[]){const z=V.get(Ie.featureId);(!z||Ie.startedAt>z.startedAt)&&V.set(Ie.featureId,Ie)}return V},[$i]),Ba=i.useCallback(()=>{!g||at||!li||yn(g.id,{append:!0})},[at,li,yn,g]),Ha=i.useCallback(V=>{Gt(Ie=>{const z=new Set(Ie);return z.has(V)?z.delete(V):z.add(V),z})},[]),yi=i.useCallback(V=>{V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),wn())},[wn]),pa=i.useCallback(V=>{V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),es())},[es]),us=i.useCallback(V=>{V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),oe())},[oe]),Ki=i.useCallback(V=>{V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),Pt())},[Pt]),Cs=i.useRef(null);if(i.useEffect(()=>{if(!h)return;const V=Ie=>{Ie.key==="Escape"&&s()};return document.addEventListener("keydown",V),()=>document.removeEventListener("keydown",V)},[h,s]),!h)return null;const Gi=()=>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:[za&&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:(Fr[g.status]||Fr.planning).bg,color:(Fr[g.status]||Fr.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:V=>Oa(g.id,V.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(Qn,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),t.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(il[Hs]||il.inactive).bg,color:(il[Hs]||il.inactive).text},"data-testid":"autopilot-state-badge",children:[za&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),Hs]})]}),Fa&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:Fa})]}),t.jsxs("div",{className:"mission-detail__actions",children:[g.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ma(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:()=>ua(g.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(Yn,{size:14})}),g.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Ti(g.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(Yn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Hn(g),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(Ds,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Se({type:"mission",id:g.id}),title:"Delete mission","aria-label":"Delete mission",children:t.jsx(vn,{size:14})})]})]}),L===g.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:M.title,onChange:V=>O({...M,title:V.target.value}),onKeyDown:yi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:M.description,onChange:V=>O({...M,description:V.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:M.status,onChange:V=>O({...M,status:V.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:M.autopilotEnabled,onChange:V=>O({...M,autopilotEnabled:V.target.checked})}),t.jsx(Qn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:wn,disabled:q,children:[q?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(hs,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:qn,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[t.jsx("button",{className:`mission-btn ${_t==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Yt("structure"),role:"tab","aria-selected":_t==="structure","data-testid":"mission-tab-structure",children:"Structure"}),t.jsxs("button",{className:`mission-btn ${_t==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Yt("activity"),role:"tab","aria-selected":_t==="activity","data-testid":"mission-tab-activity",children:["Activity (",rt,")"]})]}),_t==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[g.milestones.map(V=>{const Ie=$i?.rollup.milestoneId===V.id?$i:null,z=Ie?.rollup??an.get(V.id),ue=Ie?.validationTelemetry.validationRounds??[],Xe=Ie?.fixFeatures??[],ft=Op[z?.state??"not_started"]??Op.not_started,qt=z&&(z.state==="blocked"||z.state==="failed")?Ie?.validationTelemetry.validationRounds.find(Ze=>Ze.blockedReason)?.blockedReason:void 0;return t.jsxs("div",{className:"mission-milestone",children:[t.jsxs("div",{className:"mission-milestone__header",onClick:()=>Is(V.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:Z.has(V.id)?t.jsx(rn,{size:16}):t.jsx(Mn,{size:16})}),t.jsx(ja,{size:16,className:"mission-milestone__icon"}),t.jsx("span",{className:"mission-milestone__title",children:V.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Dp[V.status].bg,color:Dp[V.status].text},children:V.status}),t.jsxs("span",{className:"mission-milestone__count",children:[V.slices.length," slices"]}),t.jsx(zp,{state:ST(V.interviewState)}),z&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:ft.bg,color:ft.text},title:"Validation state",children:Fp(z.state)}),z.totalAssertions>0&&t.jsx("div",{className:"mission-milestone__coverage-bar",title:`${z.passedAssertions??0} of ${z.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${(z.passedAssertions??0)/z.totalAssertions*100}%`,backgroundColor:(z.passedAssertions??0)===z.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),V.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>de({type:"milestone",id:V.id,title:V.title}),title:"Plan milestone","aria-label":"Plan milestone",children:t.jsx(ia,{size:14})}),t.jsxs("div",{className:"mission-milestone__actions",onClick:Ze=>Ze.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ss(V.id),title:"Add slice",children:t.jsx(bn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ss(V),title:"Edit milestone",children:t.jsx(Ds,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Se({type:"milestone",id:V.id}),title:"Delete milestone",children:t.jsx(vn,{size:14})})]})]}),Z.has(V.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(je||$===V.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:G.title,onChange:Ze=>ge({...G,title:Ze.target.value}),onKeyDown:pa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:G.description,onChange:Ze=>ge({...G,description:Ze.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:es,disabled:q,children:[q?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(hs,{size:14}),$?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ns,children:"Cancel"})]})]}),Ie&&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:[Ie.validationTelemetry.totalRuns," rounds",Ie.validationTelemetry.lastValidatorStatus?` · Last ${Ie.validationTelemetry.lastValidatorStatus}`:""]})]}),qt&&t.jsxs("div",{className:"mission-blocked-reason",children:[t.jsx("strong",{children:"Blocked reason:"})," ",qt]}),ue.length>0&&t.jsxs("div",{className:"mission-validation-rounds",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm mission-validation-rounds__toggle",onClick:()=>Ke(Ze=>!Ze),title:Fe?"Hide validation rounds":"Show validation rounds",children:[Fe?t.jsx(rn,{size:12}):t.jsx(Mn,{size:12}),"Validation rounds (",ue.length,")"]}),Fe&&t.jsx("div",{className:"mission-validation-rounds__list",children:ue.map(Ze=>t.jsxs("div",{className:"mission-validation-round",children:[t.jsxs("div",{className:"mission-validation-round__header",children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-validation-round__status mission-validation-round__status--${Ze.validatorStatus}`,children:Ze.validatorStatus}),t.jsx("span",{className:"mission-validation-round__feature",children:Ze.featureTitle}),t.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",Ze.implementationAttempt," · reviewer #",Ze.validatorAttempt]})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),Ze.failedAssertionIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Ze.failedAssertionIds.map(st=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ca(st),title:`Jump to assertion ${st}`,children:st},`${Ze.roundId}-${st}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Generated fix features:"}),Ze.generatedFixFeatureIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Ze.generatedFixFeatureIds.map(st=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Ii(st),title:`Jump to fix feature ${st}`,children:st},`${Ze.roundId}-${st}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),Ze.blockedReason&&t.jsx("div",{className:"mission-validation-round__blocked-reason",children:Ze.blockedReason})]},Ze.roundId))})]}),Xe.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:Xe.map(Ze=>t.jsxs("div",{className:"mission-fix-feature",children:[t.jsxs("div",{className:"mission-fix-feature__header",children:[t.jsx("button",{className:"mission-fix-feature__title",onClick:()=>Ii(Ze.id),title:`Jump to feature ${Ze.id}`,children:Ze.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:sl[Ze.status].bg,color:sl[Ze.status].text},children:Ze.status}),Ze.loopState&&t.jsx("span",{className:`mission-loop-state mission-loop-state--${Ze.loopState}`,children:Ze.loopState})]}),t.jsxs("div",{className:"mission-fix-feature__meta",children:[t.jsx("span",{children:"Source:"}),t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Ii(Ze.sourceFeatureId),title:`Jump to source feature ${Ze.sourceFeatureId}`,children:Ze.sourceFeatureId}),t.jsx("span",{children:"Run:"}),t.jsx("span",{className:"mission-fix-feature__run",children:Ze.runId})]}),Ze.failedAssertionIds.length>0&&t.jsxs("div",{className:"mission-fix-feature__assertions",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),t.jsx("div",{className:"mission-validation-round__chip-list",children:Ze.failedAssertionIds.map(st=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ca(st),title:`Jump to assertion ${st}`,children:st},`${Ze.id}-${st}`))})]})]},Ze.id))})]})]}),t.jsxs("div",{className:"mission-slices",children:[V.slices.map(Ze=>t.jsxs("div",{className:"mission-slice",children:[t.jsxs("div",{className:"mission-slice__header",onClick:()=>Ce(Ze.id),children:[t.jsx("button",{className:"mission-slice__expand",children:A.has(Ze.id)?t.jsx(rn,{size:16}):t.jsx(Mn,{size:16})}),t.jsx(_d,{size:16,className:"mission-slice__icon"}),t.jsx("span",{className:"mission-slice__title",children:Ze.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Lp[Ze.status].bg,color:Lp[Ze.status].text},children:Ze.status}),t.jsxs("span",{className:"mission-slice__count",children:[Ze.features?.length||0," features"]}),t.jsx(zp,{state:Ze.planState??"not_started"}),Ze.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>de({type:"slice",id:Ze.id,title:Ze.title}),title:"Plan slice","aria-label":"Plan slice",children:t.jsx(ia,{size:14})}),t.jsxs("div",{className:"mission-slice__actions",onClick:st=>st.stopPropagation(),children:[Ze.status==="pending"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Q(Ze.id),title:"Activate slice",children:t.jsx(Yn,{size:14})}),Ze.status==="active"&&Ze.features?.some(st=>st.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Vn(Ze.id),title:"Triage all features",disabled:q,children:q?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(Qn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Je(Ze.id),title:"Add feature",children:t.jsx(bn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>X(Ze),title:"Edit slice",children:t.jsx(Ds,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Se({type:"slice",id:Ze.id}),title:"Delete slice",children:t.jsx(vn,{size:14})})]})]}),A.has(Ze.id)&&t.jsxs("div",{className:"mission-slice__body",children:[se&&J===V.id&&!ne&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:ee.title,onChange:st=>le({...ee,title:st.target.value}),onKeyDown:us,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:ee.description,onChange:st=>le({...ee,description:st.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:oe,disabled:q,children:[q?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(hs,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:_,children:"Cancel"})]})]}),ne===Ze.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:ee.title,onChange:st=>le({...ee,title:st.target.value}),onKeyDown:us,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:ee.description,onChange:st=>le({...ee,description:st.target.value}),rows:2}),t.jsxs("select",{value:ee.status,onChange:st=>le({...ee,status:st.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:oe,disabled:q,children:[q?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(hs,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:_,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-features",children:[Ze.features?.map(st=>t.jsxs("div",{className:"mission-feature","data-mission-feature-id":st.id,children:[t.jsxs("div",{className:"mission-feature__header",children:[t.jsx("button",{className:"mission-feature__expand",onClick:()=>Da(st.id),title:Ht===st.id?"Collapse details":"Expand to show run history",children:Ht===st.id?t.jsx(rn,{size:14}):t.jsx(Mn,{size:14})}),t.jsx(kd,{size:14,className:"mission-feature__icon"}),t.jsx("span",{className:"mission-feature__title",children:st.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:sl[st.status].bg,color:sl[st.status].text},children:st.status}),st.loopState&&st.loopState!=="idle"&&t.jsxs("span",{className:`mission-loop-state mission-loop-state--${st.loopState}`,title:`Loop state: ${st.loopState}`,children:[st.loopState==="implementing"&&"⏳",st.loopState==="validating"&&"🔄",st.loopState==="needs_fix"&&"🔧",st.loopState==="passed"&&"✅",st.loopState==="blocked"&&"🚫"]}),st.generatedFromFeatureId&&t.jsx("button",{className:"mission-feature__lineage",onClick:()=>Ii(st.generatedFromFeatureId),title:`Generated from feature: ${st.generatedFromFeatureId}`,children:"🔗 Fix"}),(st.loopState==="validating"||st.loopState==="needs_fix")&&(()=>{const Ot=It.get(st.id),xn=Ua.get(st.id),Xs=Ot?.implementationAttemptCount??xn?.implementationAttempt??st.implementationAttemptCount??0,ci=Ot?.retryBudgetRemaining??Math.max(0,NT-Xs);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",Xs," · ",ci," ",ci===1?"retry":"retries"," left"]})})(),st.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>$a(st.id),title:"Validate feature",disabled:et.has(st.id),children:et.has(st.id)?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(ps,{size:14})}),st.taskId&&t.jsx("span",{className:"mission-feature__task-link",onClick:()=>o?.(st.taskId),title:"Click to view task",children:st.taskId}),t.jsxs("div",{className:"mission-feature__actions",children:[st.status==="defined"&&!st.taskId&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Un(st.id),title:"Triage — create task",disabled:q||$e===st.id,children:$e===st.id?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(Qn,{size:14})}),st.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>Pn(st.id),title:"Unlink task",children:t.jsx(Yu,{size:14})}):st.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ue(st.id),title:"Link to task",children:t.jsx(cr,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>kt(st),title:"Edit feature",children:t.jsx(Ds,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Se({type:"feature",id:st.id}),title:"Delete feature",children:t.jsx(vn,{size:14})})]})]}),st.description&&t.jsx("p",{className:"mission-feature__description",children:st.description}),st.acceptanceCriteria&&t.jsxs("p",{className:"mission-feature__criteria",children:[t.jsx("strong",{children:"Acceptance:"})," ",st.acceptanceCriteria]}),Ve?.featureId===st.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:Ve.enrichedDescription}),t.jsxs("div",{className:"mission-triage-preview__actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:gs,disabled:q,children:[q?t.jsx(xt,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:Ln,disabled:q,children:"Cancel"})]})]}),ve===st.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:H.title,onChange:Ot=>be({...H,title:Ot.target.value}),onKeyDown:Ki,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:H.description,onChange:Ot=>be({...H,description:Ot.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:H.acceptanceCriteria,onChange:Ot=>be({...H,acceptanceCriteria:Ot.target.value}),rows:2}),t.jsxs("select",{value:H.status,onChange:Ot=>be({...H,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:Pt,disabled:q,children:[q?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(hs,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Tt,children:"Cancel"})]})]}),Ht===st.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"})}),(ae.get(st.id)??[]).map(Ot=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>La(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:At===Ot.id?"Hide details":"Show details",children:At===Ot.id?t.jsx(rn,{size:12}):t.jsx(Mn,{size:12})})]}),At===Ot.id&&Ft.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]}),Ft.get(Ot.id)?.failures&&Ft.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:"}),Ft.get(Ot.id).failures.map(xn=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:xn.message}),xn.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",xn.expected]}),xn.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",xn.actual]})]},xn.id))]}),(!Ft.get(Ot.id)?.failures||Ft.get(Ot.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},Ot.id)),(!ae.get(st.id)||ae.get(st.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},st.id)),ce&&Le===Ze.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:H.title,onChange:st=>be({...H,title:st.target.value}),onKeyDown:Ki,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:H.description,onChange:st=>be({...H,description:st.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:H.acceptanceCriteria,onChange:st=>be({...H,acceptanceCriteria:st.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Pt,disabled:q,children:[q?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(hs,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Tt,children:"Cancel"})]})]}),!ce&&(!Ze.features||Ze.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(kd,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},Ze.id)),V.slices.length===0&&!se&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(_d,{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"}),z&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:ft.bg,color:ft.text},children:Fp(z.state)}),z&&z.totalAssertions>0&&t.jsx("div",{className:"mission-assertions__coverage-bar",title:`${z.passedAssertions??0} of ${z.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${(z.passedAssertions??0)/z.totalAssertions*100}%`,backgroundColor:(z.passedAssertions??0)===z.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>{wt(!0),We(null),nt({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx(bn,{size:14})})]}),Ct&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:me.title,onChange:Ze=>nt({...me,title:Ze.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:me.assertion,onChange:Ze=>nt({...me,assertion:Ze.target.value}),rows:2}),t.jsxs("select",{value:me.status,onChange:Ze=>nt({...me,status:Ze.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"passed",children:"Passed"}),t.jsx("option",{value:"failed",children:"Failed"}),t.jsx("option",{value:"blocked",children:"Blocked"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:()=>Bn(V.id),disabled:q,children:[q?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(hs,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Gn,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(we.get(V.id))?we.get(V.id):[]).map(Ze=>t.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":Ze.id,children:[t.jsx("div",{className:"mission-assertion__header",children:he===Ze.id?t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:me.title,onChange:st=>nt({...me,title:st.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:me.assertion,onChange:st=>nt({...me,assertion:st.target.value}),rows:2}),t.jsxs("select",{value:me.status,onChange:st=>nt({...me,status:st.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"passed",children:"Passed"}),t.jsx("option",{value:"failed",children:"Failed"}),t.jsx("option",{value:"blocked",children:"Blocked"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:()=>ds(Ze.id,V.id),disabled:q,children:[q?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(hs,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Gn,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(al[Ze.status]??al.pending).bg,color:(al[Ze.status]??al.pending).text},children:Ze.status}),t.jsx("span",{className:"mission-assertion__title",children:Ze.title}),(()=>{const Ot=Mt.get(Ze.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:()=>Ri(Ze.id),title:"Toggle details",children:$t===Ze.id?t.jsx(rn,{size:14}):t.jsx(Mn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Nn(Ze),title:"Edit assertion",children:t.jsx(Ds,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Se({type:"assertion",id:Ze.id}),title:"Delete assertion",children:t.jsx(vn,{size:14})})]})}),$t===Ze.id&&t.jsxs("div",{className:"mission-assertion__body",children:[t.jsx("p",{className:"mission-assertion__text",children:Ze.assertion}),t.jsxs("div",{className:"mission-assertion__linked-features",children:[t.jsxs("div",{className:"mission-assertion__linked-features-header",children:[t.jsx("span",{className:"mission-assertion__linked-features-label",children:"Linked Features"}),t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:async()=>{$t!==Ze.id&&await Ri(Ze.id),Jt(fn===Ze.id?null:Ze.id)},title:"Link a feature",children:[t.jsx(cr,{size:12}),"Link Feature"]})]}),fn===Ze.id&&t.jsx("div",{className:"mission-assertion__feature-picker",children:t.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const st=new Set((Mt.get(Ze.id)??[]).map(xn=>xn.id)),Ot=[];return g?.milestones.forEach(xn=>xn.slices.forEach(Xs=>Ot.push(...Xs.features.filter(ci=>!st.has(ci.id))))),Ot.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):Ot.map(xn=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>ri(xn.id,Ze.id),disabled:Qt.has(Ze.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:xn.title}),Qt.has(Ze.id)&&t.jsx(xt,{size:12,className:"spinner"})]},xn.id))})()})}),(()=>{const st=Mt.get(Ze.id)??[];return st.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):st.map(Ot=>{const xn=`${Ot.id}-${Ze.id}`,Xs=Bt.has(xn);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:()=>Ta(Ot.id,Ze.id),disabled:Xs,title:"Unlink feature",children:Xs?t.jsx(xt,{size:12,className:"spinner"}):t.jsx(Yu,{size:12})})]},Ot.id)})})()]})]})]},Ze.id)),(!we.get(V.id)||we.get(V.id)?.length===0)&&!Ct&&t.jsx("div",{className:"mission-manager__empty mission-assertions__empty",children:t.jsx("span",{children:"No assertions defined. Add one to define completion criteria."})})]})]})]})]})]},V.id)}),g&&!je&&$===null&&t.jsxs("button",{className:"mission-add-btn",onClick:_n,children:[t.jsx(bn,{size:16}),"Add Milestone"]}),je&&$===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:G.title,onChange:V=>ge({...G,title:V.target.value}),onKeyDown:pa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:G.description,onChange:V=>ge({...G,description:V.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:es,disabled:q,children:[q?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(hs,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ns,children:"Cancel"})]})]}),g.milestones.length===0&&!je&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(ja,{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:V=>ie(V.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:[Xt.length," of ",rt]})]}),!at&&li&&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:Ba,"data-testid":"mission-activity-load-more",children:"Load more"})}),at?t.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[t.jsx(xt,{size:18,className:"spinner"}),t.jsx("span",{children:"Loading mission activity..."})]}):Xt.length===0?t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Ks,{size:18}),t.jsx("span",{children:"No events yet."})]}):t.jsxs("div",{ref:Cn,className:"mission-events","data-testid":"mission-activity-events",children:[Xt.map(V=>{const Ie=!!(V.metadata&&Object.keys(V.metadata).length>0),z=it.has(V.id);return t.jsxs("div",{className:"mission-event",children:[t.jsxs("div",{className:"mission-event__header",children:[t.jsx("span",{className:`mission-event__type ${AT(V.eventType)}`,children:PT(V.eventType)}),t.jsx("span",{className:"mission-event__time",children:Ol(V.timestamp)})]}),t.jsx("p",{className:"mission-event__description",children:V.description}),t.jsx("span",{className:"mission-event__timestamp",children:new Date(V.timestamp).toLocaleString()}),Ie&&t.jsxs("div",{className:"mission-event__metadata",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>Ha(V.id),"data-testid":`mission-event-metadata-${V.id}`,children:[z?"Hide":"Show"," metadata"]}),z&&t.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(V.metadata,null,2)})]})]},V.id)}),t.jsx("div",{ref:fs})]})]})]}):null,qa=()=>f.map(V=>{const Ie=V,z=g?.id===Ie.id,ue=Fr[Ie.status]||{bg:"",text:""},Xe=Ie.summary,ft=dt.get(Ie.id),qt=ET(ft),Ze=!!(Xe&&(Xe.totalMilestones>0||Xe.totalFeatures>0)),st=ft?.totalTasks??0,Ot=ft?.tasksCompleted??0,xn=ft?.tasksFailed??0,Xs=ft?.estimatedCompletionPercent??Xe?.progressPercent??0,ci=Ze||st>0||xn>0||!!ft?.lastActivityAt;return t.jsxs("div",{className:`mission-list__item ${z?"mission-list__item--selected":""}`,onClick:()=>ha(V),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(vs,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:Ie.title})]}),t.jsxs("div",{className:"mission-list__item-tags",children:[V.autopilotEnabled&&t.jsx("span",{title:"Autopilot enabled",children:t.jsx(Qn,{size:12,className:"mission-list__item-autopilot-icon"})}),t.jsx("span",{className:`mission-health-badge mission-health-badge--${qt}`,"data-testid":`mission-health-badge-${Ie.id}`,"aria-label":`Mission health: ${qt}`}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:ue.bg,color:ue.text},children:Ie.status})]}),Ie.description&&t.jsx("p",{className:"mission-list__item-description",children:Ie.description}),ci&&t.jsxs("div",{className:"mission-list__item-summary",children:[Ze&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[Xe.completedMilestones,"/",Xe.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[Xe.completedFeatures,"/",Xe.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${Ie.id}`,children:[Ot,"/",st," tasks"]}),xn>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:as=>{as.stopPropagation(),ha(V)},"data-testid":`mission-failed-${Ie.id}`,title:"View mission failures",children:[xn," failed"]}),t.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${qt}`,children:t.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${Xs}%`}})})]}),ci&&t.jsx("div",{className:"mission-list__item-activity",children:t.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${Ie.id}`,children:["Activity ",Ol(ft?.lastActivityAt)]})})]}),t.jsxs("div",{className:"mission-list__item-actions",onClick:as=>as.stopPropagation(),children:[Ie.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ma(Ie.id),title:"Stop mission",children:t.jsx(Si,{size:14})}),Ie.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>ua(Ie.id),title:"Resume mission",children:t.jsx(Yn,{size:14})}),Ie.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Ti(Ie.id),title:"Start mission",children:t.jsx(Yn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Hn(V),title:"Edit mission",children:t.jsx(Ds,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Se({type:"mission",id:Ie.id}),title:"Delete mission",children:t.jsx(vn,{size:14})})]})]},Ie.id)}),Ge=({hideBottomButtons:V=!1}={})=>{const Ie=k&&f.length>0&&!E,z=!V&&!Ie;return t.jsxs("div",{className:"mission-list",children:[E&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:M.title,onChange:ue=>O({...M,title:ue.target.value}),onKeyDown:yi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:M.description,onChange:ue=>O({...M,description:ue.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:wn,disabled:q,children:[q?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(hs,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:qn,children:"Cancel"})]})]}),Ie&&t.jsx("div",{className:"mission-list__top-action",children:t.jsxs("button",{className:"btn btn-sm btn-task-create mission-list__primary-cta",onClick:()=>lt(!0),children:[t.jsx(ps,{size:14}),"Plan New Mission"]})}),qa(),L&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:M.title,onChange:ue=>O({...M,title:ue.target.value}),onKeyDown:yi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:M.description,onChange:ue=>O({...M,description:ue.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:M.status,onChange:ue=>O({...M,status:ue.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:M.autopilotEnabled,onChange:ue=>O({...M,autopilotEnabled:ue.target.checked})}),t.jsx(Qn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:wn,disabled:q,children:[q?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(hs,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:qn,children:"Cancel"})]})]}),f.length===0&&!E&&t.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large mission-manager__empty--mission",children:[t.jsx(vs,{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:()=>lt(!0),children:[t.jsx(ps,{size:14}),"Plan New Mission"]})]}),!E&&t.jsxs("div",{className:"mission-list__footer",children:[Be.length>0&&t.jsxs("div",{className:"mission-resume-prompt",children:[t.jsx(Ps,{size:16}),t.jsx("span",{children:Be.length===1?`Resume "${Be[0].title}"?`:`${Be.length} interview sessions pending`}),t.jsx("div",{className:"mission-list__resume-actions",children:Be.map(ue=>t.jsxs("button",{className:"mission-add-btn",onClick:()=>{_e(ue.id),lt(!0),ye([])},children:[ue.status==="error"?t.jsx(rs,{size:14}):t.jsx(ps,{size:14}),ue.status==="error"?"Retry":"Resume"]},ue.id))})]}),z&&t.jsx("div",{className:"mission-list__footer-actions",children:t.jsxs("button",{className:"mission-add-btn",onClick:()=>lt(!0),children:[t.jsx(ps,{size:16}),"Plan New Mission"]})})]})]})},Rt=()=>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 ",ht?.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()=>{ht&&(ht.type==="mission"?await Zn(ht.id):ht.type==="milestone"?await ks(ht.id):ht.type==="slice"?await D(ht.id):ht.type==="feature"&&await ln(ht.id))},children:"Delete"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>Se(null),children:"Cancel"})]})]})}),cn=()=>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:pe,onChange:V=>Oe(V.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(V=>t.jsxs("button",{className:"mission-task-suggestions__item",onClick:()=>Oe(V.id),children:[V.id,": ",V.title||"Untitled"]},V.id))})]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--primary",onClick:ts,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{Ue(null),Oe("")},children:"Cancel"})]})]})}),is=t.jsxs("div",{ref:Cs,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:Mr,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(ql,{size:18})}),t.jsx(vs,{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(nn,{size:18})})]}),k?t.jsxs("div",{className:"mission-manager__body mission-manager__body--stacked",children:[w?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(xt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(xt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?Gi():Ge(),ht&&Rt(),gt&&cn()]}):t.jsxs("div",{className:"mission-manager__split",children:[t.jsxs("aside",{className:"mission-manager__sidebar","data-testid":"mission-sidebar","aria-label":"Mission list",style:k?void 0:{width:`${C}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:()=>lt(!0),title:"Plan New Mission","aria-label":"Plan New Mission",children:[t.jsx(ps,{size:14}),"Plan New Mission"]})}),t.jsx("div",{className:"mission-manager__sidebar-list",children:w?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(xt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):Ge({hideBottomButtons:!0})})]}),!k&&t.jsx("div",{className:"mission-manager__sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":tl,"aria-valuemax":nl,"aria-valuenow":C,"aria-label":"Resize mission sidebar",tabIndex:0,onPointerDown:P,onKeyDown:U}),t.jsxs("div",{className:"mission-manager__detail-pane",children:[y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(xt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?Gi():t.jsxs("div",{className:"mission-manager__detail-pane-empty","data-testid":"mission-empty-detail",children:[t.jsx(vs,{size:32}),t.jsx("span",{children:"Select a mission to view details"})]}),ht&&Rt(),gt&&cn()]})]})]}),Rn=t.jsx(mT,{isOpen:ze,onClose:()=>lt(!1),onMissionCreated:()=>{hn(),a("Mission created from AI interview","success")},projectId:r,resumeSessionId:ct}),$s=pt?t.jsx(wT,{isOpen:!0,onClose:()=>de(null),onApplied:()=>{de(null),g&&Et(g.id)},targetType:pt.type,targetId:pt.id,targetTitle:pt.title,missionContext:g?.title,projectId:r,resumeSessionId:pt.resumeSessionId}):null;return n?t.jsxs(t.Fragment,{children:[is,Rn,$s]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mission-manager-overlay open",onClick:V=>V.target===V.currentTarget&&s(),"data-testid":"mission-manager-overlay",role:"dialog","aria-modal":"true",children:is}),Rn,$s]})}const TT={pre:({children:e,...n})=>t.jsx("pre",{...n,className:"mailbox-markdown-pre",children:e}),table:({children:e,...n})=>t.jsx("table",{...n,className:"mailbox-markdown-table",children:e}),a:({children:e,...n})=>t.jsx("a",{...n,target:"_blank",rel:"noopener noreferrer",children:e})},Hp=i.memo(function({content:n,className:s,testId:a}){const r=s?`mailbox-markdown ${s}`:"mailbox-markdown";return t.jsx("div",{className:r,"data-testid":a,children:t.jsx(bi,{remarkPlugins:[xi],components:TT,children:n})})}),rl=2e3;function qp({recipient:e,replyContext:n,agents:s=[],projectId:a,onSend:r,onCancel:o,addToast:l,isLoadingAgents:c=!1}){const[d,u]=i.useState(e?.id??""),[m,h]=i.useState(e?.type??"agent"),[f,p]=i.useState(""),[g,x]=i.useState(!1),[w,b]=i.useState(!1),[y,S]=i.useState(null),k=i.useRef(null),C=i.useMemo(()=>s.find(F=>F.id===d),[s,d]),v=i.useMemo(()=>e?s.find(F=>F.id===e.id):void 0,[s,e]),j=m==="agent",P=j&&C?.runtimeConfig?.messageResponseMode==="immediate",U=j&&(g||P),E=d.trim()!==""&&f.trim().length>0&&f.length<=rl,R=i.useCallback(async()=>{if(!(!E||w)){b(!0),S(null);try{const F=m==="agent"?"user-to-agent":"system",M=n?{replyTo:{messageId:n.messageId}}:void 0,O=U;await E1({toId:d.trim(),toType:m,content:f.trim(),type:F,...M?{metadata:M}:{},...O?{wakeImmediately:!0}:{}},a),r()}catch(F){const M=Re(F)||"Failed to send message";S(M),l?.(M,"error")}finally{b(!1)}}},[E,w,d,m,f,U,n,a,r,l]),L=i.useCallback(F=>{u(F),h("agent")},[]);return i.useEffect(()=>{n&&k.current?.focus()},[n]),i.useEffect(()=>{if(!n||typeof window>"u"||window.visualViewport==null)return;const F=()=>{k.current?.scrollIntoView({block:"center",behavior:"auto"})};return window.visualViewport.addEventListener("resize",F),()=>{window.visualViewport?.removeEventListener("resize",F)}},[n]),t.jsxs("div",{className:"message-composer","data-testid":"message-composer",children:[t.jsxs("div",{className:"message-composer-header",children:[t.jsx("span",{children:n?"Reply":"New Message"}),t.jsx("button",{className:"btn-icon",onClick:o,"aria-label":"Cancel","data-testid":"message-composer-cancel",children:t.jsx(nn,{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:F=>L(F.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(F=>t.jsx("option",{value:F.id,children:F.name||F.id},F.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(Tn,{size:14}),v?.name||e.id]})]}),n&&t.jsxs("div",{className:"message-composer-field","data-testid":"message-composer-reply-context",children:[t.jsx("span",{className:"message-composer-label",children:"Replying to:"}),t.jsx("span",{className:"message-composer-recipient-fixed",children:n.preview?.trim()?n.preview:`Message ${n.messageId}`})]}),t.jsxs("div",{className:"message-composer-field message-composer-field--content",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-content",children:"Message:"}),t.jsx("textarea",{id:"message-content",ref:k,className:"message-composer-textarea",placeholder:"Type your message…",value:f,onChange:F=>p(F.target.value),maxLength:rl,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>rl?"over-limit":"",children:[f.length,"/",rl]})})]}),j&&t.jsx("div",{className:"message-composer-field message-composer-field--wake",children:t.jsxs("label",{className:"message-composer-wake-label",children:[t.jsx("input",{type:"checkbox",checked:U,disabled:P,onChange:F=>x(F.target.checked),"data-testid":"message-composer-wake"}),t.jsxs("span",{children:["Wake agent immediately",t.jsx("span",{className:"message-composer-wake-hint","data-testid":"message-composer-wake-hint",children:P?"(agent is already set to immediate response mode)":"(one-off override for this message only)"})]})]})}),y&&t.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[t.jsx(Ps,{size:14}),t.jsx("span",{children:y})]})]}),t.jsxs("div",{className:"message-composer-footer",children:[t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:o,"data-testid":"message-composer-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:R,disabled:!E||w,"data-testid":"message-composer-send",children:w?t.jsxs(t.Fragment,{children:[t.jsx(xt,{size:14,className:"spin"}),t.jsx("span",{children:"Sending…"})]}):t.jsxs(t.Fragment,{children:[t.jsx(wa,{size:14}),t.jsx("span",{children:"Send"})]})})]})]})}function Xi(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 $T(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 DT(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 Vp(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function Wp(){if(typeof window>"u")return null;const n=new URLSearchParams(window.location.search).get("mailbox-message");return n||(/^#message-(.+)$/.exec(window.location.hash)?.[1]??null)}function ol(e){return`mailbox-list-message-${e}`}function ad(e){return`mailbox-detail-message-${e}`}function LT(e,n){const s=[...e];s.some(o=>o.id===n.id)||s.push(n);const a=new Set([n.id]);let r=!0;for(;r;){r=!1;for(const o of s){const l=o.metadata?.replyTo?.messageId;a.has(o.id)&&l&&!a.has(l)&&(a.add(l),r=!0),l&&a.has(l)&&!a.has(o.id)&&(a.add(o.id),r=!0)}}return s.filter(o=>a.has(o.id)).sort((o,l)=>new Date(o.createdAt).getTime()-new Date(l.createdAt).getTime())}function OT({projectId:e,addToast:n,onUnreadCountChange:s}){const[a,r]=i.useState("inbox"),[o,l]=i.useState(null),[c,d]=i.useState(null),[u,m]=i.useState(0),[h,f]=i.useState(!1),[p,g]=i.useState(null),[x,w]=i.useState([]),[b,y]=i.useState(!1),[S,k]=i.useState(null),[C,v]=i.useState(null),[j,P]=i.useState(null),[U,E]=i.useState("inbox"),[R,L]=i.useState(null),[F,M]=i.useState([]),[O,q]=i.useState("pending"),[te,Z]=i.useState([]),[K,A]=i.useState(0),[I,$]=i.useState(null),[N,G]=i.useState(""),[ge,je]=i.useState(!1),ke=i.useMemo(()=>new Map(F.map(de=>[de.id,de.name??""])),[F]),ne=i.useCallback((de,Ve)=>$T(de,Ve,ke),[ke]),ee=Ys()==="mobile",le=!ee,{keyboardOverlap:se,viewportHeight:re,viewportOffsetTop:J,keyboardOpen:B}=Wi({enabled:ee}),ve=i.useMemo(()=>{if(B)return{"--keyboard-overlap":`${se}px`,"--vv-offset-top":`${J}px`,...re!=null?{"--vv-height":`${re}px`}:{}}},[B,se,re,J]),Ne=i.useCallback(async()=>{f(!0);try{const de=await S1({limit:50},e);l(de),m(de.unreadCount),s?.(de.unreadCount)}catch{}finally{f(!1)}},[e,s]),H=i.useCallback(async()=>{f(!0);try{const de=await C1({limit:50},e);d(de)}catch{}finally{f(!1)}},[e]),be=i.useCallback(async de=>{f(!0);try{const Ve=await R1(de,e);L(Ve)}catch{}finally{f(!1)}},[e]),ce=i.useCallback(async()=>{try{const de=await Nr(void 0,e);M(de)}catch{}},[e]),Me=i.useCallback(async()=>{try{const de=await $g(e);m(de.unreadCount),s?.(de.unreadCount)}catch{}},[e,s]),Le=i.useCallback(async de=>{f(!0);try{const Ve=await Fo({status:de==="pending"?"pending":void 0,limit:100},e);if(de==="pending")Z(Ve.requests);else{const[Ee,$e,ut]=await Promise.all([Fo({status:"approved",limit:100},e),Fo({status:"denied",limit:100},e),Fo({status:"completed",limit:100},e)]);Z([...Ee.requests,...$e.requests,...ut.requests].sort((ht,Se)=>Se.updatedAt.localeCompare(ht.updatedAt)))}A(Ve.pendingCount)}catch{}finally{f(!1)}},[e]);i.useEffect(()=>{a==="inbox"?Ne():a==="outbox"?H():a==="agents"?ce():a==="approvals"&&Le(O)},[a,Ne,H,ce,Le,O]),i.useEffect(()=>{j&&be(j)},[j,be]),i.useEffect(()=>{Me()},[Me]),i.useEffect(()=>{ce()},[ce]),i.useEffect(()=>{if(typeof EventSource>"u")return;const de=e?`?projectId=${encodeURIComponent(e)}`:"",Ve=()=>{Me(),a==="inbox"?Ne():a==="outbox"?H():a==="approvals"&&Le(O),j&&be(j)};return ii(`/api/events${de}`,{events:{"message:sent":Ve,"message:received":Ve,"message:read":Ve,"message:deleted":Ve,"approval:requested":Ve,"approval:updated":Ve,"approval:decided":Ve}})},[e,a,j,Me,Ne,H,be,Le,O]);const He=i.useCallback(async de=>{if(g(de),!de.read&&a==="inbox")try{const Ve=await _1(de.id,e);Ve&&l($e=>$e&&{...$e,messages:$e.messages.map(ut=>ut.id===Ve.id?Ve:ut),unreadCount:Math.max(0,$e.unreadCount-1)});const Ee=Math.max(0,u-1);m(Ee),s?.(Ee)}catch{}try{const Ve=await P1(de.fromId,de.fromType,e);w(Ve)}catch{w([de])}},[e,u,s,a]);i.useEffect(()=>{const de=Wp();if(!de)return;const Ve=[...o?.messages??[],...c?.messages??[],...R?.inbox??[],...R?.outbox??[],...x].find(Ee=>Ee.id===de);Ve&&He(Ve)},[o,c,R,x,He]),i.useEffect(()=>{const de=Wp();if(!de)return;const Ve=document.getElementById(ad(de));if(!Ve)return;Ve.scrollIntoView({behavior:"smooth",block:"center"}),Ve.classList.add("mailbox-message-highlight");const Ee=window.setTimeout(()=>{Ve.classList.remove("mailbox-message-highlight")},2e3);return()=>{window.clearTimeout(Ee)}},[p,x]);const gt=i.useCallback(()=>{g(null),w([])},[]),Ue=i.useCallback(async()=>{try{const de=await M1(e);m(0),s?.(0),l(Ve=>Ve&&{...Ve,messages:Ve.messages.map(Ee=>({...Ee,read:!0})),unreadCount:0}),n?.(`Marked ${de.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[e,n,s]),pe=i.useCallback(async de=>{try{await A1(de,e),g(null),w([]),a==="inbox"?Ne():a==="outbox"?H():j&&be(j),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,a,j,Ne,H,be,n]),Oe=i.useCallback(de=>{k({id:de.fromId,type:de.fromType}),v({messageId:de.id,preview:Vp(de.content,120)}),y(!0)},[]),ze=i.useCallback(()=>{y(!1),k(null),v(null),n?.("Message sent","success"),a==="outbox"?H():a==="agents"&&j&&be(j),Me()},[a,H,j,be,n,Me]),lt=i.useCallback(()=>{k(a==="agents"&&j?{id:j,type:"agent"}:null),v(null),y(!0)},[a,j]),Be=i.useCallback(()=>{y(!1),k(null),v(null)},[]),ye=i.useCallback(async de=>{try{const Ve=await jm(de.id,e);$(Ve),G("")}catch{n?.("Failed to load approval request","error")}},[e,n]),Y=i.useCallback(async de=>{if(!(!I||ge)){je(de);try{await I1(I.id,{decision:de,comment:N||void 0},e),await Le(O);const Ve=await jm(I.id,e);$(Ve),G(""),n?.(`Request ${de==="approve"?"approved":"denied"}`,"success")}catch{n?.("Failed to submit decision","error")}finally{je(!1)}}},[I,ge,N,e,Le,O,n]),_e=()=>{if(!p||b)return null;const de=LT(x,p);return t.jsxs("div",{className:"mailbox-message-detail","data-testid":"mailbox-message-detail",id:ad(p.id),children:[t.jsxs("div",{className:"mailbox-message-detail-header",children:[ee&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:gt,"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:DT(p.type)}),t.jsx("span",{className:"mailbox-message-time",children:Xi(p.createdAt)})]}),t.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>Oe(p),"data-testid":"mailbox-reply",children:[t.jsx(Ui,{size:14}),t.jsx("span",{children:"Reply"})]}),t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>pe(p.id),"data-testid":"mailbox-delete",children:[t.jsx(vn,{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(Tn,{size:14}):t.jsx(Ka,{size:14}),ne(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(Tn,{size:14}):t.jsx(Ka,{size:14}),ne(p.toId,p.toType)]})]})]}),de.length>1&&t.jsxs("div",{className:"mailbox-conversation","data-testid":"mailbox-conversation",children:[t.jsx("div",{className:"mailbox-conversation-label",children:"Conversation"}),de.map(Ve=>{const Ee=Ve.metadata?.replyTo?.messageId,$e=Ee?de.find(ut=>ut.id===Ee):void 0;return t.jsxs("div",{id:ad(Ve.id),className:`mailbox-conversation-msg ${Ve.id===p.id?"current":""}`,children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:ne(Ve.fromId,Ve.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:Xi(Ve.createdAt)})]}),Ee&&t.jsxs("div",{className:"mailbox-reply-context-static","data-testid":`mailbox-reply-context-${Ve.id}`,children:["↪ Replying to ",$e?Vp($e.content,60):`message ${Ee}`]}),t.jsx(Hp,{content:Ve.content,className:"mailbox-conversation-msg-body"})]},Ve.id)})]}),de.length<=1&&t.jsxs(t.Fragment,{children:[p.metadata?.replyTo?.messageId&&t.jsxs("div",{className:"mailbox-reply-context-static","data-testid":"mailbox-selected-reply-context",children:["↪ Replying to message ",p.metadata.replyTo.messageId]}),t.jsx(Hp,{content:p.content,className:"mailbox-message-body",testId:"mailbox-message-body"})]})]})},ct=()=>t.jsxs(t.Fragment,{children:[a==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!o&&t.jsx(rd,{}),o&&o.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[t.jsx(ya,{size:32}),t.jsx("p",{children:"No messages in your inbox"})]}),o?.messages.map(de=>t.jsxs("div",{id:ol(de.id),className:`mailbox-item ${de.read?"":"unread"}`,onClick:()=>He(de),"data-testid":`mailbox-item-${de.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:de.fromType==="agent"?t.jsx(Tn,{size:16}):t.jsx(Ka,{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:ne(de.fromId,de.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:Xi(de.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[de.content.slice(0,80),de.content.length>80?"…":""]})]}),!de.read&&t.jsx("div",{className:"mailbox-item-unread-dot","data-testid":`mailbox-unread-dot-${de.id}`})]},de.id))]}),a==="outbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!c&&t.jsx(rd,{}),c&&c.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[t.jsx(wa,{size:32}),t.jsx("p",{children:"No sent messages"})]}),c?.messages.map(de=>t.jsxs("div",{id:ol(de.id),className:"mailbox-item",onClick:()=>He(de),"data-testid":`mailbox-item-${de.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:de.toType==="agent"?t.jsx(Tn,{size:16}):t.jsx(Ka,{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: ",ne(de.toId,de.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:Xi(de.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[de.content.slice(0,80),de.content.length>80?"…":""]})]})]},de.id))]}),a==="approvals"&&t.jsxs("div",{className:"mailbox-approvals","data-testid":"mailbox-approvals",children:[t.jsxs("div",{className:"mailbox-approval-filters","data-testid":"mailbox-approval-filters",children:[t.jsx("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${O==="pending"?"active":""}`,onClick:()=>{q("pending"),$(null)},"data-testid":"mailbox-approval-filter-pending",children:"Pending"}),t.jsx("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${O==="history"?"active":""}`,onClick:()=>{q("history"),$(null)},"data-testid":"mailbox-approval-filter-history",children:"History"})]}),t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-approval-list",children:[te.length===0&&!h&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-approval-empty",children:[t.jsx(ya,{size:32}),t.jsx("p",{children:O==="pending"?"No pending approvals":"No historical approvals"})]}),te.map(de=>t.jsxs("div",{className:"mailbox-item mailbox-approval-item",onClick:()=>void ye(de),"data-testid":`mailbox-approval-item-${de.id}`,children:[t.jsx("div",{className:`status-dot mailbox-approval-status-dot mailbox-approval-status-dot--${de.status}`}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsxs("span",{className:"mailbox-item-from",children:[de.agentId," · ",de.actionCategory]}),t.jsx("span",{className:"mailbox-item-time",children:Xi(de.createdAt)})]}),t.jsx("div",{className:"mailbox-item-preview",children:de.actionSummary})]}),t.jsx("span",{className:`mailbox-approval-status mailbox-approval-status--${de.status}`,children:de.status})]},de.id))]})]}),a==="agents"&&t.jsx("div",{className:"mailbox-agents","data-testid":"mailbox-agents",children:F.length===0?t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Tn,{size:32}),t.jsx("p",{children:"No agents found"})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"mailbox-agents-header",children:[t.jsx("div",{className:"mailbox-agents-dropdown",children:t.jsxs("select",{className:"message-composer-select mailbox-agent-select",value:j??"",onChange:de=>{P(de.target.value||null),E("inbox")},"data-testid":"mailbox-agent-select",children:[t.jsx("option",{value:"",children:"Select an agent…"}),F.map(de=>t.jsx("option",{value:de.id,children:de.name||de.id},de.id))]})}),t.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:lt,"data-testid":"mailbox-compose-btn",children:[t.jsx(Ui,{size:14}),t.jsx("span",{children:"Compose"})]})]}),j&&t.jsxs("div",{className:"mailbox-agent-subtabs","data-testid":"mailbox-agent-subtabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${U==="inbox"?"active":""}`,onClick:()=>E("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[t.jsx(ya,{size:12}),t.jsx("span",{children:"Inbox"}),R&&R.unreadCount>0&&t.jsx("span",{className:"mailbox-tab-badge",children:R.unreadCount})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${U==="outbox"?"active":""}`,onClick:()=>E("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[t.jsx(wa,{size:12}),t.jsx("span",{children:"Outbox"})]})]}),t.jsxs("div",{className:"mailbox-agents-content",children:[!j&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Tn,{size:32}),t.jsx("p",{children:"Select an agent to view their mailbox"})]}),j&&h&&!R&&t.jsx(rd,{}),j&&R&&U==="inbox"&&R.inbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(ya,{size:32}),t.jsx("p",{children:"No received messages for this agent"})]}),j&&R&&U==="outbox"&&R.outbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(wa,{size:32}),t.jsx("p",{children:"No sent messages for this agent"})]}),j&&R&&U==="inbox"&&R.inbox.map(de=>t.jsxs("div",{id:ol(de.id),className:`mailbox-item ${de.read?"":"unread"}`,onClick:()=>He(de),"data-testid":`mailbox-item-${de.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:de.fromType==="agent"?t.jsx(Tn,{size:16}):t.jsx(Ka,{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:ne(de.fromId,de.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:Xi(de.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[de.content.slice(0,80),de.content.length>80?"…":""]})]})]},de.id)),j&&R&&U==="outbox"&&R.outbox.map(de=>t.jsxs("div",{id:ol(de.id),className:"mailbox-item",onClick:()=>He(de),"data-testid":`mailbox-item-${de.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:de.toType==="agent"?t.jsx(Tn,{size:16}):t.jsx(Ka,{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: ",ne(de.toId,de.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:Xi(de.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[de.content.slice(0,80),de.content.length>80?"…":""]})]})]},de.id))]})]})})]}),pt=()=>b?t.jsx(qp,{recipient:S,replyContext:C,agents:F,projectId:e,onSend:ze,onCancel:Be,addToast:n}):p?_e():a==="approvals"&&I?t.jsxs("div",{className:"mailbox-message-detail mailbox-approval-detail","data-testid":"mailbox-approval-detail",children:[ee&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:()=>$(null),"data-testid":"mailbox-approval-back-to-list",children:"← Back"}),t.jsx("div",{className:"mailbox-message-detail-header",children:t.jsxs("div",{className:"mailbox-message-detail-meta",children:[t.jsx("span",{className:"mailbox-message-type",children:I.actionCategory}),t.jsx("span",{className:"mailbox-message-time",children:I.status})]})}),t.jsxs("div",{className:"mailbox-message-body",children:[t.jsx("strong",{children:I.actionSummary}),t.jsxs("p",{children:["Requester: ",I.requester.actorName," (",I.agentId,")"]}),I.taskId&&t.jsxs("p",{children:["Task: ",I.taskId]}),t.jsxs("p",{children:["Requested: ",Xi(I.createdAt)]})]}),t.jsx("div",{className:"mailbox-conversation","data-testid":"mailbox-approval-history",children:I.history.map(de=>t.jsxs("div",{className:"mailbox-conversation-msg",children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:de.eventType}),t.jsx("span",{children:de.actor.actorName})]}),de.note&&t.jsx("div",{className:"mailbox-item-preview",children:de.note})]},de.id))}),I.status==="pending"&&t.jsxs("div",{className:"mailbox-approval-decision","data-testid":"mailbox-approval-decision",children:[t.jsx("textarea",{className:"message-composer-textarea mailbox-approval-comment",value:N,onChange:de=>G(de.target.value),placeholder:"Optional comment","data-testid":"mailbox-approval-comment"}),t.jsxs("div",{className:"mailbox-header-actions",children:[t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:()=>void Y("deny"),disabled:ge!==!1,"data-testid":"mailbox-approval-deny",children:"Deny"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>void Y("approve"),disabled:ge!==!1,"data-testid":"mailbox-approval-approve",children:"Approve"})]})]})]}):t.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[t.jsx(Na,{size:24}),t.jsx("p",{children:"Select a message to read"})]});return t.jsxs("div",{className:"mailbox-view",style:ve,"data-testid":"mailbox-view",children:[t.jsxs("div",{className:"mailbox-header",children:[t.jsxs("div",{className:"mailbox-title",children:[t.jsx(Na,{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:lt,title:"Compose message","data-testid":"mailbox-header-compose",children:[t.jsx(Ui,{size:14}),t.jsx("span",{children:"Compose"})]}),a==="inbox"&&u>0&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:Ue,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[t.jsx(Wu,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{a==="inbox"?Ne():a==="outbox"?H():a==="approvals"?Le(O):j&&be(j)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?t.jsx(xt,{size:14,className:"spin"}):t.jsx(rs,{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(ya,{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(wa,{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),$(null)},"data-testid":"mailbox-tab-agents",children:[t.jsx(Tn,{size:14}),t.jsx("span",{children:"Agents"})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${a==="approvals"?"active":""}`,onClick:()=>{r("approvals"),g(null),$(null)},"data-testid":"mailbox-tab-approvals",children:[t.jsx(Wu,{size:14}),t.jsx("span",{children:"Approvals"}),K>0&&t.jsx("span",{className:"mailbox-tab-badge","data-testid":"mailbox-approvals-pending-badge",children:K})]})]}),t.jsx("div",{className:"mailbox-content","data-testid":"mailbox-content",children:le?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:ct()}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:pt()})]}):t.jsxs(t.Fragment,{children:[_e(),a==="approvals"&&I&&pt(),b&&t.jsx(qp,{recipient:S,replyContext:C,agents:F,projectId:e,onSend:ze,onCancel:Be,addToast:n}),!p&&!I&&!b&&ct()]})})]})}function rd(){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 zT=640;function FT({isOpen:e,onClose:n,onImport:s,tasks:a,projectId:r}){vi(e);const[o,l]=i.useState(""),[c,d]=i.useState(""),[u,m]=i.useState(""),[h,f]=i.useState(!1),[p,g]=i.useState("issues"),[x,w]=i.useState([]),[b,y]=i.useState(null),[S,k]=i.useState([]),[C,v]=i.useState(null),[j,P]=i.useState(null),[U,E]=i.useState(!1),[R,L]=i.useState([]),[F,M]=i.useState(!1),[O,q]=i.useState(""),te=i.useRef(!1),Z=i.useRef(null);Ai(Z,e,"fusion:github-modal-size");const K=qi(n),[A,I]=i.useState(!1),[$,N]=i.useState("list"),G=i.useRef(null),ge=new Set;for(const ye of a){const Y=ye.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);Y&&ge.add(Y[1]);const _e=ye.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);_e&&ge.add(_e[1])}i.useEffect(()=>{if(e)return l(""),d(""),m(""),w([]),y(null),k([]),v(null),g("issues"),P(null),E(!1),L([]),M(!0),q(""),G.current=null,te.current=!0,Pj().then(ye=>{if(te.current)if(L(ye),M(!1),ye.length===1){const Y=ye[0];l(Y.owner),d(Y.repo),q(Y.name)}else ye.length>1&&(l(""),d(""),q(""))}).catch(()=>{te.current&&M(!1)}),()=>{te.current=!1}},[e]);const je=i.useCallback(ye=>{if(q(ye),ye==="")l(""),d("");else{const Y=R.find(_e=>_e.name===ye);Y&&(l(Y.owner),d(Y.repo))}},[R]),ke=i.useCallback(async()=>{if(!o.trim()||!c.trim()){P("Repository must be selected");return}f(!0),P(null),w([]),y(null);try{const ye=u.split(",").map(_e=>_e.trim()).filter(Boolean),Y=await Ej(o.trim(),c.trim(),30,ye.length>0?ye:void 0);w(Y),Y.length===0&&P("No open issues found")}catch(ye){P(Re(ye)||"Failed to fetch issues")}finally{f(!1)}},[o,c,u]),ne=i.useCallback(async()=>{if(!o.trim()||!c.trim()){P("Repository must be selected");return}f(!0),P(null),k([]),v(null);try{const ye=await Mj(o.trim(),c.trim(),30);k(ye),ye.length===0&&P("No open pull requests found")}catch(ye){P(Re(ye)||"Failed to fetch pull requests")}finally{f(!1)}},[o,c]);i.useEffect(()=>{if(!e||!o.trim()||!c.trim()||h||U)return;const ye={owner:o.trim(),repo:c.trim(),labels:u.trim(),tab:p};G.current?.owner===ye.owner&&G.current?.repo===ye.repo&&G.current?.labels===ye.labels&&G.current?.tab===ye.tab||(G.current=ye,p==="issues"?ke():ne())},[o,c,u,p,e,h,U,ke,ne]),i.useEffect(()=>{if(!e)return;const ye=Y=>{Y.key==="Escape"&&n()};return document.addEventListener("keydown",ye),()=>document.removeEventListener("keydown",ye)},[e,n]),i.useEffect(()=>{if(!e)return;const ye=()=>{I(window.innerWidth<=zT)};return ye(),window.addEventListener("resize",ye),()=>window.removeEventListener("resize",ye)},[e]);const qe=i.useCallback(ye=>{y(ye),A&&N("preview")},[A]),ee=i.useCallback(ye=>{v(ye),A&&N("preview")},[A]),le=i.useCallback(()=>{N("list")},[]),se=i.useCallback(async()=>{if(p==="issues"){if(b===null)return;E(!0),P(null);try{const ye=await _j(o.trim(),c.trim(),b,r);s(ye),y(null),A&&$==="preview"&&N("list")}catch(ye){const Y=Re(ye);Y?.includes("already imported")?P(Y):P(Y||"Failed to import issue")}finally{E(!1)}}else{if(C===null)return;E(!0),P(null);try{const ye=await Aj(o.trim(),c.trim(),C,r);s(ye),v(null),A&&$==="preview"&&N("list")}catch(ye){const Y=Re(ye);Y?.includes("already imported")?P(Y):P(Y||"Failed to import pull request")}finally{E(!1)}}},[p,b,C,o,c,s,A,$]),re=x.find(ye=>ye.number===b),J=S.find(ye=>ye.number===C);if(!e)return null;const B=R.length>0,ve=R.length===1,Ne=x.filter(ye=>ge.has(ye.html_url)).length,H=S.filter(ye=>ge.has(ye.html_url)).length,be=j==="No open issues found",ce=j==="No open pull requests found",Me=p==="issues"?be:ce,Le=!!j&&!be&&x.length===0&&!h,He=!!j&&!ce&&S.length===0&&!h,gt=p==="issues"?Le:He,Ue=h||x.length>0||be||Le,pe=h||S.length>0||ce||He,Oe=p==="issues"?Ue:pe,ze=!!j&&x.length>0&&!be,lt=!!j&&S.length>0&&!ce,Be=p==="issues"?ze:lt;return t.jsx("div",{className:"modal-overlay open",...K,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg github-import-modal",ref:Z,children:[t.jsxs("div",{className:"modal-header github-import-modal__header",children:[t.jsxs("div",{children:[t.jsx("h3",{children:"Import from GitHub"}),t.jsx("p",{className:"github-import-modal__subtitle",children:"Choose a detected remote, load open issues or pull requests, and import one into the board."})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close import modal",children:"×"})]}),t.jsxs("div",{className:"modal-body github-import-modal__body",children:[t.jsxs("div",{className:"github-import-tabs",role:"tablist","aria-label":"Import type",children:[t.jsxs("button",{role:"tab","aria-selected":p==="issues","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="issues"?"active":""}`,onClick:()=>{g("issues"),v(null)},disabled:h||U,children:[t.jsx(Vl,{size:16}),t.jsx("span",{children:"Issues"})]}),t.jsxs("button",{role:"tab","aria-selected":p==="pulls","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="pulls"?"active":""}`,onClick:()=>{g("pulls"),y(null)},disabled:h||U,children:[t.jsx(Ws,{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:F?t.jsxs("div",{className:"github-import-toolbar__loading",role:"status","aria-live":"polite",children:[t.jsx(xt,{size:16,className:"spin"}),t.jsx("span",{children:"Detecting…"})]}):B?ve?t.jsxs("div",{className:"github-import-remote-pill","data-testid":"github-import-single-remote",children:[t.jsx("span",{className:"github-import-remote-pill__name",children:R[0].name}),t.jsxs("span",{className:"github-import-remote-pill__repo",children:[R[0].owner,"/",R[0].repo]})]}):t.jsxs("div",{className:"github-import-remote-select",children:[t.jsx("label",{htmlFor:"gh-remote",className:"visually-hidden",children:"Repository"}),t.jsxs("select",{id:"gh-remote",value:O,onChange:ye=>je(ye.target.value),disabled:h||U,"aria-label":"Select Git remote",children:[t.jsx("option",{value:"",children:"Select remote…"}),R.map(ye=>t.jsxs("option",{value:ye.name,children:[ye.name," (",ye.owner,"/",ye.repo,")"]},ye.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:ye=>m(ye.target.value),onKeyDown:ye=>ye.key==="Enter"&&ke(),disabled:h||U||!B,"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"?ke:ne,disabled:h||U||!o.trim()||!c.trim(),"aria-label":h?`Loading ${p}`:`Load ${p} from repository`,title:h?"Loading…":`Load ${p}`,children:[h?t.jsx(xt,{size:14,className:"spin"}):t.jsx(rs,{size:14}),t.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!F&&!B&&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"})]}),Be&&t.jsx("div",{className:"form-error github-import-banner",role:"alert",children:j}),t.jsxs("div",{className:"github-import-workspace",children:[t.jsxs("section",{className:`github-import-list-pane ${A?"mobile":""} ${$==="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:[Ne," 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:[H," imported"]})]})]}),t.jsxs("div",{className:"github-import-pane-content",children:[!Oe&&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(xt,{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."})]})]}),gt&&t.jsx("div",{className:"github-import-state github-import-state--error",role:"alert",children:t.jsxs("div",{children:[t.jsxs("strong",{children:["Could not load ",p==="issues"?"issues":"pull requests"]}),t.jsx("span",{children:j})]})}),Me&&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(ye=>{const Y=ge.has(ye.html_url);return t.jsxs("div",{className:`issue-item ${b===ye.number?"selected":""} ${Y?"imported":""}`,onClick:()=>!Y&&qe(ye.number),children:[t.jsx("input",{type:"radio",name:"issue",checked:b===ye.number,onChange:()=>qe(ye.number),disabled:Y,"aria-label":`Select issue #${ye.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",ye.number]}),t.jsx("span",{className:"issue-title",children:ye.title})]}),ye.labels.length>0&&t.jsx("span",{className:"issue-labels",children:ye.labels.map(_e=>t.jsx("span",{className:"label-chip",children:_e.name},_e.name))})]}),Y&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},ye.number)})}),p==="pulls"&&S.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:S.map(ye=>{const Y=ge.has(ye.html_url);return t.jsxs("div",{className:`issue-item ${C===ye.number?"selected":""} ${Y?"imported":""}`,onClick:()=>!Y&&ee(ye.number),children:[t.jsx("input",{type:"radio",name:"pull",checked:C===ye.number,onChange:()=>ee(ye.number),disabled:Y,"aria-label":`Select pull request #${ye.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",ye.number]}),t.jsx("span",{className:"issue-title",children:ye.title})]}),t.jsxs("span",{className:"pull-branch-info",children:[ye.headBranch," → ",ye.baseBranch]})]}),Y&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},ye.number)})})]})]}),t.jsxs("section",{className:`github-import-preview-pane ${A?"mobile":""} ${$==="preview"?"active":""}`,"data-testid":"github-import-preview-pane","aria-labelledby":"github-import-preview-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[A&&t.jsxs("button",{className:"github-import-back-button",onClick:le,"data-testid":"github-import-back-button","aria-label":`Back to ${p==="issues"?"issues":"pull requests"} list`,children:[t.jsx(Aa,{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"&&re?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Issue #",re.number]}),t.jsx("div",{className:"preview-title",children:re.title}),t.jsx("div",{className:"preview-body",children:re.body?re.body.slice(0,200)+(re.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"&&J?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Pull Request #",J.number]}),t.jsx("div",{className:"preview-title",children:J.title}),t.jsxs("div",{className:"preview-branch",children:[t.jsx("strong",{children:"Branch:"})," ",J.headBranch," → ",J.baseBranch]}),t.jsx("div",{className:"preview-body",children:J.body?J.body.slice(0,200)+(J.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:U,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:se,disabled:(p==="issues"?b===null:C===null)||U,children:U?t.jsx(xt,{size:14,className:"spin"}):"Import"})]})]})})}function ti({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(Mn,{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 UT=["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 go(e){return e&&oa.includes(e)?e:js}function od(e){return{...e,priority:go(e.priority)}}function BT(e,n){return e&&n?`${e}/${n}`:""}function HT(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 qT({isOpen:e,onClose:n,onTaskCreated:s,onTasksCreated:a,tasks:r,initialPlan:o,projectId:l,resumeSessionId:c}){const[d,u]=i.useState(""),[m,h]=i.useState({type:"initial"}),[f,p]=i.useState(null),[g,x]=i.useState([]),[w,b]=i.useState([]),[y,S]=i.useState(null),k=i.useRef(!1),C=i.useRef(!1),[v,j]=i.useState(""),[P,U]=i.useState(!0),[E,R]=i.useState(!1),[L,F]=i.useState(!1),[M,O]=i.useState(null),[q,te]=i.useState(0),Z=i.useRef(null),K=i.useRef(null),A=i.useRef(null),I=i.useRef(null),$=i.useRef(null),N=i.useRef(null),G=i.useRef(null),[ge,je]=i.useState(c??null),ke=i.useMemo(()=>Ia(),[]),{isLockedByOther:ne,takeControl:qe,isLoading:ee}=lc(e?ge:null),{activeTabMap:le,broadcastUpdate:se,broadcastCompleted:re,broadcastLock:J,broadcastUnlock:B,broadcastHeartbeat:ve}=_r(),[Ne,H]=i.useState(void 0),[be,ce]=i.useState(void 0),[Me,Le]=i.useState("medium"),[He,gt]=i.useState(""),[Ue,pe]=i.useState([]),[Oe,ze]=i.useState(!1),[lt,Be]=i.useState(null),[ye,Y]=i.useState([]),[_e,ct]=i.useState([]),[pt,de]=i.useState({}),Ve=i.useRef(null),[Ee,$e]=i.useState([]),[ut,ht]=i.useState(!1),[Se,we]=i.useState(c??null),[Ae,he]=i.useState(!!c),[We,me]=i.useState(null),[nt,Ct]=i.useState(!1),wt=i.useRef(!1),$t=i.useRef(null),Vt=i.useRef(""),Mt=i.useRef(null),Dt=i.useRef(null);Ai(K,e,"fusion:planning-modal-size");const Qt=Ys(),{keyboardOverlap:Kt,viewportHeight:Bt,viewportOffsetTop:on,keyboardOpen:fn}=Wi({enabled:Qt==="mobile"});vi(Qt==="mobile"&&e),i.useEffect(()=>{const fe=K.current;fe&&(fn?(fe.style.setProperty("--keyboard-overlap",`${Kt}px`),fe.style.setProperty("--vv-offset-top",`${on}px`),Bt!==null?fe.style.setProperty("--vv-height",`${Bt}px`):fe.style.removeProperty("--vv-height")):(fe.style.removeProperty("--keyboard-overlap"),fe.style.removeProperty("--vv-offset-top"),fe.style.removeProperty("--vv-height")))},[fn,Kt,on,Bt]),i.useEffect(()=>{Vt.current=v},[v]),i.useEffect(()=>{const fe=$t.current;if(!fe)return;fe.scrollHeight-fe.scrollTop-fe.clientHeight<32&&(fe.scrollTop=fe.scrollHeight)},[v]),i.useEffect(()=>{if(m.type!=="loading"){O(null),te(0);return}const fe=Date.now();O(fe),te(0);const at=setInterval(()=>{te(Math.max(0,Math.floor((Date.now()-fe)/1e3)))},1e3);return()=>clearInterval(at)},[m.type]),i.useEffect(()=>{if(m.type!=="loading")return;const fe=I.current;if(!fe)return;let at=!1;const rt=setInterval(async()=>{try{const mt=await Ci(fe);if(at||!mt||I.current!==fe)return;if(mt.status==="awaiting_input"&&mt.currentQuestion){const vt=JSON.parse(mt.currentQuestion);h({type:"question",session:{sessionId:fe,currentQuestion:vt,summary:null}}),j("")}else if(mt.status==="complete"&&mt.result){const vt=od(JSON.parse(mt.result));h({type:"summary",session:{sessionId:fe,currentQuestion:null,summary:vt},summary:vt}),S(vt),j("")}}catch{}},8e3);return()=>{at=!0,clearInterval(rt)}},[m.type]);const Jt=i.useCallback(()=>{u(""),h({type:"initial"}),p(null),x([]),b([]),S(null),j(""),R(!1),F(!1),H(void 0),ce(void 0),Le("medium"),gt(""),I.current=null,je(null)},[]),an=BT(Ne,be),zt=i.useCallback((fe,at)=>{if(!fe||!at)return pt.provider&&pt.modelId?`${pt.provider}/${pt.modelId}`:"Using default";const ot=Ue.find(rt=>rt.provider===fe&&rt.id===at);return ot?`${ot.provider}/${ot.id}`:`${fe}/${at}`},[Ue,pt.modelId,pt.provider]),en=i.useCallback(async()=>{ze(!0),Be(null);try{const fe=await Os();pe(fe.models),Y(fe.favoriteProviders),ct(fe.favoriteModels),de({provider:fe.resolvedPlanningProvider,modelId:fe.resolvedPlanningModelId})}catch(fe){Be(Re(fe)||"Failed to load models")}finally{ze(!1)}},[]),Zt=i.useCallback(fe=>{Y(at=>{const ot=at,mt=ot.includes(fe)?ot.filter(vt=>vt!==fe):[fe,...ot];return kn({favoriteProviders:mt,favoriteModels:_e}).catch(()=>{Y(ot)}),mt})},[_e]),dn=i.useCallback(fe=>{ct(at=>{const ot=at,mt=ot.includes(fe)?ot.filter(vt=>vt!==fe):[fe,...ot];return kn({favoriteProviders:ye,favoriteModels:mt}).catch(()=>{ct(ot)}),mt})},[ye]),xe=i.useCallback(fe=>{A.current?.close();const at=()=>I.current!==fe,ot=IN(fe,l,{onThinking:rt=>{at()||(j(mt=>mt+rt),se({sessionId:fe,status:"generating",needsInput:!1,owningTabId:ke,type:"planning",title:d.trim()||void 0,projectId:l??null}))},onQuestion:rt=>{if(at())return;R(!1),F(!1),Xa(l);const mt=Vt.current.trim();mt&&b(vt=>vt[vt.length-1]?.thinkingOutput===mt?vt:[...vt,{thinkingOutput:mt}]),h({type:"question",session:{sessionId:fe,currentQuestion:rt,summary:null}}),j(""),se({sessionId:fe,status:"awaiting_input",needsInput:!0,owningTabId:ke,type:"planning",title:d.trim()||void 0,projectId:l??null})},onSummary:rt=>{if(at())return;R(!1),F(!1),Xa(l);const mt=Vt.current.trim();mt&&b(vt=>vt[vt.length-1]?.thinkingOutput===mt?vt:[...vt,{thinkingOutput:mt}]),h({type:"summary",session:{sessionId:fe,currentQuestion:null,summary:rt},summary:rt}),S(rt),j(""),se({sessionId:fe,status:"complete",needsInput:!1,owningTabId:ke,type:"planning",title:d.trim()||void 0,projectId:l??null})},onError:rt=>{const mt=rt||"Session failed while contacting the AI.";R(!0),(async()=>{try{const vt=await Ci(fe);if(vt&&(vt.status==="generating"||vt.status==="awaiting_input")){xe(fe);return}}catch{}R(!1),F(!1),p(null),h(vt=>vt.type==="question"||vt.type==="summary"||vt.type==="error"?{type:"error",session:vt.session,errorMessage:mt}:{type:"error",session:{sessionId:fe,currentQuestion:null,summary:null},errorMessage:mt}),j(""),I.current=fe,se({sessionId:fe,status:"error",needsInput:!1,owningTabId:ke,type:"planning",title:d.trim()||void 0,projectId:l??null}),re({sessionId:fe,status:"error"})})()},onComplete:()=>{R(!1),F(!1),I.current=null,re({sessionId:fe,status:"complete"})},onConnectionStateChange:rt=>{R(rt==="reconnecting")}});A.current=ot},[re,se,d,l,ke]),Fe=i.useCallback(async fe=>{const at=fe??d;if(at.trim()){p(null),j(""),b([]),x([]),R(!1),h({type:"loading"});try{const ot=Ne&&be?{planningModelProvider:Ne,planningModelId:be}:void 0,rt=He.trim()?Number.parseInt(He,10):void 0,mt=$.current,{sessionId:vt}=await fN(at.trim(),l,ot,{planningDepth:Me,customQuestionCount:Number.isInteger(rt)?rt:void 0},mt??void 0);$.current=null,I.current=vt,je(vt),we(vt),xe(vt),x([])}catch(ot){R(!1),p(Re(ot)||"Failed to start planning session"),h({type:"initial"}),I.current=null,je(null)}}},[xe,He,d,Me,be,Ne,l]);i.useEffect(()=>{e&&m.type==="initial"&&Z.current?.focus()},[e,m.type]),i.useEffect(()=>{e&&en()},[e,en]),i.useEffect(()=>{if(e&&o&&!k.current&&m.type==="initial"){u(o);const fe=setTimeout(()=>{k.current=!0,Fe(o)},0);return()=>clearTimeout(fe)}else if(e&&!o&&!k.current&&!C.current&&m.type==="initial"){C.current=!0;const fe=JI(l);fe&&u(fe)}},[e,o,m.type,Fe,l]);const Ke=i.useCallback(async fe=>{A.current?.close(),A.current=null,p(null),j(""),x([]),b([]),S(null),F(!1),h({type:"loading"});try{const at=await Ci(fe);if(!at){we(null),he(!1),h({type:"initial"});return}I.current=fe,je(fe);const ot=hr(at.conversationHistory);if(b(ot),x(ot.map(rt=>rt.response).filter(rt=>!!(rt&&typeof rt=="object"&&!Array.isArray(rt)))),at.status==="draft"){let rt="",mt,vt;try{const ie=at.inputPayload?JSON.parse(at.inputPayload):null;ie&&typeof ie.initialPlan=="string"&&(rt=ie.initialPlan),ie&&typeof ie.modelProvider=="string"&&typeof ie.modelId=="string"&&(mt=ie.modelProvider,vt=ie.modelId)}catch{}u(rt),H(mt),ce(vt),$.current=fe,Dt.current=rt?{sessionId:fe,initialPlan:rt.trim(),modelProvider:mt,modelId:vt}:null,h({type:"initial"})}else if(at.status==="awaiting_input"&&at.currentQuestion){Xa(l);const rt=JSON.parse(at.currentQuestion);if(h({type:"question",session:{sessionId:fe,currentQuestion:rt,summary:null}}),at.thinkingOutput){const mt=at.thinkingOutput.trim();mt&&b(vt=>vt[vt.length-1]?.thinkingOutput===mt?vt:[...vt,{thinkingOutput:mt}])}xe(fe)}else if(at.status==="complete"&&at.result){Xa(l);const rt=od(JSON.parse(at.result));h({type:"summary",session:{sessionId:fe,currentQuestion:null,summary:rt},summary:rt}),S(rt)}else at.status==="generating"?(h({type:"loading"}),at.thinkingOutput&&j(at.thinkingOutput),xe(fe)):at.status==="error"&&h({type:"error",session:{sessionId:fe,currentQuestion:null,summary:null},errorMessage:at.error||"Session failed"})}catch{p("Failed to load session"),h({type:"initial"})}},[xe,l]);i.useEffect(()=>{!e||!c||I.current!==c&&G.current!==c&&(we(c),he(!0),Ke(c))},[e,c]),i.useEffect(()=>{e&&Se&&(c&&c===Se||Ke(Se))},[e]);const et=i.useCallback(async()=>{ht(!0);try{const at=(await hu(l,{includeCompleted:!0,includeArchived:nt})).filter(ot=>ot.type==="planning").sort((ot,rt)=>Date.parse(rt.updatedAt)-Date.parse(ot.updatedAt));$e(at)}catch{}finally{ht(!1)}},[l,nt]);i.useEffect(()=>{e&&et()},[e,et]);const Qe=i.useRef(!1);i.useEffect(()=>{const fe=Qe.current&&!ut;Qe.current=ut,fe&&Qt==="mobile"&&(Ae||c||Se||Ee.length>0||he(!0))},[Qt,Ae,c,Se,ut,Ee.length]),i.useEffect(()=>{if(!e)return;const fe=l?`?projectId=${encodeURIComponent(l)}`:"",at=rt=>{try{const mt=JSON.parse(rt.data);if(mt.type!=="planning")return;$e(vt=>{const ie=vt.findIndex(Gt=>Gt.id===mt.id);return(ie>=0?[...vt.slice(0,ie),mt,...vt.slice(ie+1)]:[mt,...vt]).sort((Gt,Cn)=>Date.parse(Cn.updatedAt)-Date.parse(Gt.updatedAt))})}catch{}},ot=rt=>{try{const mt=JSON.parse(rt.data);$e(vt=>vt.filter(ie=>ie.id!==mt))}catch{}};return ii(`/api/events${fe}`,{events:{"ai_session:updated":at,"ai_session:deleted":ot},onReconnect:()=>{et()}})},[e,l,et]);const It=i.useCallback(fe=>{if(Se===fe){he(!0);return}we(fe),he(!0),Ke(fe)},[Ke,Se]),St=i.useCallback(()=>{A.current?.close(),A.current=null,$.current=null,N.current&&(clearTimeout(N.current),N.current=null),c&&(G.current=c),Jt(),we(null),he(!0)},[Jt,c]),Ht=i.useCallback(()=>{he(!1)},[]),jt=i.useCallback(async(fe,at)=>{const ot=at.trim();if(!(!ot||Dt.current?.sessionId===fe&&Dt.current.initialPlan===ot&&Dt.current.modelProvider===Ne&&Dt.current.modelId===be))try{await j1(fe,{initialPlan:ot,modelProvider:Ne&&be?Ne:void 0,modelId:Ne&&be?be:void 0},l),Dt.current={sessionId:fe,initialPlan:ot,modelProvider:Ne,modelId:be}}catch{}},[be,Ne,l]);i.useEffect(()=>{if(Mt.current&&(clearTimeout(Mt.current),Mt.current=null),!(!e||m.type!=="initial"||!Se))return Mt.current=setTimeout(()=>{jt(Se,d)},500),()=>{Mt.current&&(clearTimeout(Mt.current),Mt.current=null)}},[d,e,Se,jt,m.type]),i.useEffect(()=>{Dt.current=null},[Se]),i.useEffect(()=>()=>{Mt.current&&(clearTimeout(Mt.current),Mt.current=null)},[]);const ae=i.useCallback(async fe=>{const at=rt=>rt==="generating"||rt==="awaiting_input",ot=Ee.find(rt=>rt.id===fe);if(ot&&at(ot.status))try{await Sg(fe,l,ke)}catch{}try{await Tg(fe)}catch{}re({sessionId:fe,status:"complete",timestamp:Date.now()}),$e(rt=>rt.filter(mt=>mt.id!==fe)),Se===fe&&(A.current?.close(),A.current=null,Jt(),we(null),he(!1)),me(null)},[re,Ee,l,Jt,Se,ke]),De=i.useCallback(async fe=>{const ot=Ee.find(rt=>rt.id===fe)?.archived===!0;try{ot?await x1(fe):await b1(fe)}catch{return}$e(rt=>!ot&&!nt?rt.filter(mt=>mt.id!==fe):rt.map(mt=>mt.id===fe?{...mt,archived:!ot}:mt)),!ot&&Se===fe&&!nt&&(A.current?.close(),A.current=null,Jt(),we(null),he(!1))},[Ee,Jt,Se,he,nt]);i.useEffect(()=>{e||(k.current=!1,C.current=!1,R(!1),F(!1),je(null))},[e]),i.useEffect(()=>{if(!e){Ve.current&&(B(Ve.current,ke),Ve.current=null);return}if(ge&&Ve.current!==ge){Ve.current&&B(Ve.current,ke),J(ge,ke),Ve.current=ge;return}!ge&&Ve.current&&(B(Ve.current,ke),Ve.current=null)},[J,B,e,ge,ke]),i.useEffect(()=>{if(!e||!ge||Ve.current!==ge)return;ve(ke);const fe=setInterval(()=>{ve(ke)},3e4);return()=>{clearInterval(fe)}},[ve,e,ge,ke]),i.useEffect(()=>()=>{N.current&&(clearTimeout(N.current),N.current=null),A.current?.close(),A.current=null,Ve.current&&(B(Ve.current,ke),Ve.current=null)},[B,ke]),i.useEffect(()=>{if(!e)return;const fe=()=>{A.current?.close(),A.current=null};return window.addEventListener("beforeunload",fe),()=>window.removeEventListener("beforeunload",fe)},[e]);const At=i.useCallback((fe,at)=>{Mt.current&&(clearTimeout(Mt.current),Mt.current=null),(async()=>{try{await jt(fe,at),await N1(fe,l)}catch{}})()},[l,jt]),Lt=i.useCallback(()=>{if(Qt!=="mobile")return;const fe=document.activeElement;fe instanceof HTMLElement&&fe.blur(),window.scrollTo(0,0),requestAnimationFrame(()=>{window.scrollTo(0,0)})},[Qt]),Ft=i.useCallback(()=>{d&&m.type==="initial"&&GI(d,l);const fe=$.current;fe&&d.trim()&&At(fe,d),$.current=null,N.current&&(clearTimeout(N.current),N.current=null),A.current?.close(),A.current=null,R(!1),F(!1),Lt(),n()},[At,d,n,l,Lt,m.type]);i.useEffect(()=>{if(!e)return;const fe=at=>{at.key==="Escape"&&Ft()};return document.addEventListener("keydown",fe),()=>document.removeEventListener("keydown",fe)},[e,Ft]);const Pe=i.useCallback(async fe=>{if(m.type!=="question")return;const{session:at}=m,ot=at.sessionId,rt=at.currentQuestion;if(!rt){p("No active question in session");return}p(null),x(mt=>[...mt,fe]),b(mt=>{const vt=Vt.current.trim();let ie=mt;return vt&&ie[ie.length-1]?.thinkingOutput!==vt&&(ie=[...ie,{thinkingOutput:vt}]),[...ie,{question:rt,response:fe}]}),h({type:"loading"}),j("");try{await cm(ot,fe,l,ke)}catch(mt){p(Re(mt)||"Failed to submit response"),h({type:"question",session:at})}},[l,ke,m]),dt=i.useCallback(async()=>{if(m.type!=="summary")return;const{session:fe,summary:at}=m,ot=fe.sessionId;I.current=ot,je(ot),p(null),F(!1),j(""),h({type:"loading"}),xe(ot);try{await cm(ot,{refine:!0},l,ke)}catch(rt){A.current?.close(),A.current=null,p(Re(rt)||"Failed to refine plan"),h({type:"summary",session:fe,summary:y??at})}},[xe,y,l,ke,m]),bt=i.useCallback(async()=>{const fe=I.current;if(fe){try{await xN(fe,l,ke)}catch{}A.current?.close(),A.current=null,R(!1),F(!1),h({type:"error",session:{sessionId:fe,currentQuestion:null,summary:null},errorMessage:"Generation stopped by user. You can retry or start a new session."}),j("")}},[l,ke]),_t=i.useCallback(async()=>{if(m.type!=="error")return;const fe=m.session;p(null),F(!0),j(""),h({type:"loading"}),xe(fe.sessionId);try{I.current=fe.sessionId,je(fe.sessionId),await bN(fe.sessionId,l,ke)}catch(at){let ot=at;if((Re(at)||"").includes("not in an error state"))try{const mt=await Ci(fe.sessionId);if(!mt)throw new Error("Failed to refresh planning session.");if(I.current=mt.id,je(mt.id),mt.status==="generating")j(mt.thinkingOutput??""),h({type:"loading"});else if(mt.status==="awaiting_input"){if(!mt.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const vt=JSON.parse(mt.currentQuestion);if(Xa(l),h({type:"question",session:{sessionId:mt.id,currentQuestion:vt,summary:null}}),mt.thinkingOutput){const ie=mt.thinkingOutput.trim();ie&&b(it=>it[it.length-1]?.thinkingOutput===ie?it:[...it,{thinkingOutput:ie}])}A.current?.isConnected()||xe(mt.id)}else if(mt.status==="complete"){if(!mt.result)throw new Error("Planning session is complete but has no result.");const vt=od(JSON.parse(mt.result));Xa(l),h({type:"summary",session:{sessionId:mt.id,currentQuestion:null,summary:vt},summary:vt}),S(vt)}else mt.status==="error"&&h({type:"error",session:{sessionId:mt.id,currentQuestion:null,summary:null},errorMessage:mt.error||"Retry failed. Please try again."});R(!1);return}catch(mt){ot=mt}A.current?.close(),A.current=null,h({type:"error",session:fe,errorMessage:Re(ot)||"Retry failed. Please try again."}),R(!1)}finally{F(!1)}},[xe,l,ke,m]),Yt=i.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const fe=m.session.sessionId,at=await vN(fe,y??void 0,l);s(at),we(null),$e(ot=>ot.filter(rt=>rt.id!==fe)),re({sessionId:fe,status:"complete",timestamp:Date.now()}),Ft()}catch(fe){p(Re(fe)||"Failed to create task"),h({type:"summary",session:m.session,summary:m.summary})}}},[re,y,m,l,s,Ft]),Xt=i.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const fe=await yN(m.session.sessionId,y??void 0,l);je(fe.sessionId),h({type:"breakdown",sessionId:fe.sessionId,subtasks:fe.subtasks.map(at=>({...at,priority:go(at.priority)})),dirty:!1})}catch(fe){p(Re(fe)||"Failed to start breakdown"),h({type:"summary",session:m.session,summary:m.summary})}}},[y,m,l]),Te=i.useCallback(async()=>{if(m.type==="breakdown"){p(null),h({type:"creating"});try{const fe=m.sessionId,at=await wN(fe,m.subtasks.map(ot=>({...ot,priority:go(ot.priority)})),l);a(at.tasks),$e(ot=>ot.filter(rt=>rt.id!==fe)),re({sessionId:fe,status:"complete",timestamp:Date.now()}),u(""),h({type:"initial"}),p(null),x([]),b([]),S(null),j(""),H(void 0),ce(void 0),Le("medium"),gt(""),I.current=null,je(null),we(null),Ft()}catch(fe){p(Re(fe)||"Failed to create tasks"),h({type:"breakdown",sessionId:m.sessionId,subtasks:m.subtasks,dirty:m.dirty})}}},[re,Ft,m,a,l]),Ye=i.useCallback(async()=>{if(m.type!=="question"||g.length===0)return;const fe=m.session.sessionId;p(null),h({type:"loading"});try{const at=await gN(fe,l,ke);x(at.history.map(ot=>ot.response&&typeof ot.response=="object"&&!Array.isArray(ot.response)?ot.response:{[ot.question.id]:ot.response})),b(at.history.map(ot=>({question:ot.question,response:ot.response&&typeof ot.response=="object"&&!Array.isArray(ot.response)?ot.response:{[ot.question.id]:ot.response},thinkingOutput:ot.thinkingOutput}))),j(""),h({type:"question",session:{...m.session,currentQuestion:at.currentQuestion,summary:null}})}catch(at){p(Re(at)||"Failed to go back to the previous question"),h({type:"question",session:m.session})}},[l,g.length,ke,m]),Nt=()=>m.type==="question"?Math.min(g.length+1,3):3,Ut=ge?le.get(ge):null,tn=Ut&&Ut.tabId!==ke,Xn=ne&&(!tn||Ut.stale);return e?t.jsx("div",{className:"modal-overlay open",onMouseDown:fe=>{wt.current=fe.target===fe.currentTarget},onClick:fe=>{fe.target===fe.currentTarget&&wt.current&&Ft(),wt.current=!1},role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",ref:K,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[Ae&&t.jsx("button",{className:"modal-back planning-mobile-back",onClick:Ht,"aria-label":"Back to sessions",title:"Back to sessions",children:t.jsx(ql,{size:18})}),t.jsx(_i,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Planning Mode"})]}),t.jsx("div",{className:"modal-header-actions",children:t.jsx("button",{className:"modal-close",onClick:Ft,"aria-label":"Close",children:t.jsx(nn,{size:20})})})]}),t.jsxs("div",{className:`planning-modal-body planning-modal-body--split ${Ae?"planning-modal-body--show-detail":"planning-modal-body--show-list"}`,children:[t.jsx(JT,{sessions:Ee,loading:ut,selectedSessionId:Se,pendingDeleteId:We,showArchived:nt,onToggleShowArchived:()=>Ct(fe=>!fe),onArchive:fe=>void De(fe),onSelectSession:It,onNewSession:St,onRequestDelete:me,onConfirmDelete:fe=>void ae(fe),onCancelDelete:()=>me(null)}),t.jsxs("div",{className:"planning-detail",children:[f&&t.jsx("div",{className:"form-error planning-error",children:f}),E&&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(ps,{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:Z,id:"initial-plan",rows:4,className:"planning-textarea",placeholder:"e.g., Build a user authentication system with login, signup, and password reset...",value:d,onChange:fe=>{const at=fe.target.value;u(at),!($.current||at.trim().length===0)&&(N.current&&clearTimeout(N.current),N.current=setTimeout(()=>{if($.current)return;const ot=at.trim();if(!ot)return;pN(ot,l,Ne&&be?{planningModelProvider:Ne,planningModelId:be}:void 0).then(mt=>{$.current=mt.sessionId,$e(vt=>vt.some(it=>it.id===mt.sessionId)?vt:[{id:mt.sessionId,type:"planning",status:"draft",title:mt.title,preview:ot.length>80?`${ot.slice(0,79).trimEnd()}…`:ot,projectId:l??null,lockedByTab:null,updatedAt:new Date().toISOString(),archived:!1},...vt].sort((it,Gt)=>Date.parse(Gt.updatedAt)-Date.parse(it.updatedAt))),we(mt.sessionId)}).catch(()=>{})},300))},onKeyDown:fe=>{fe.key==="Enter"&&!fe.shiftKey&&d.trim()&&(fe.preventDefault(),Fe())},onBlur:()=>{const fe=$.current;fe&&d.trim()&&At(fe,d)}})]}),t.jsxs("div",{className:"planning-examples",children:[t.jsx("span",{className:"planning-examples-label",children:"Try an example:"}),t.jsx("div",{className:"planning-example-chips",children:UT.map((fe,at)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>u(fe),children:fe.length>40?fe.slice(0,40)+"...":fe},at))})]}),t.jsx(ti,{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",Oe&&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(ys,{id:"planning-modal-model",label:"Planning Model",value:an,onChange:fe=>{const{provider:at,modelId:ot}=HT(fe);H(at),ce(ot)},models:Ue,disabled:Oe,favoriteProviders:ye,onToggleFavorite:Zt,favoriteModels:_e,onToggleModelFavorite:dn}),lt&&t.jsxs("div",{className:"form-hint form-hint-error",children:[lt," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{en()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${Ne&&be?"model-badge-custom":"model-badge-default"}`,children:zt(Ne,be)})})]}),t.jsxs("div",{className:"planning-advanced-section planning-depth-selector",children:[t.jsx("p",{className:"planning-advanced-blurb",children:"Plan size sets default interview depth. Questions lets you override with an exact count."}),t.jsxs("div",{className:"planning-depth-controls-row",children:[t.jsx("div",{className:"planning-depth-chip-group",role:"group","aria-label":"Planning depth",children:[{value:"small",label:"Small"},{value:"medium",label:"Medium"},{value:"large",label:"Large"}].map(fe=>t.jsx("button",{type:"button",className:`planning-depth-chip btn ${Me===fe.value?"btn-primary planning-depth-chip-active":""}`,onClick:()=>Le(fe.value),"aria-pressed":Me===fe.value,children:fe.label},fe.value))}),t.jsxs("label",{className:"planning-depth-question-count",htmlFor:"planning-depth-questions",children:[t.jsx("span",{children:"Questions"}),t.jsx("input",{id:"planning-depth-questions",className:"input planning-depth-question-input",type:"number",min:1,max:20,value:He,onChange:fe=>gt(fe.target.value),placeholder:"Auto"})]})]})]})]})})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>Fe(),disabled:!d.trim(),children:[t.jsx(_i,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),m.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(xt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:v?"AI is thinking...":"Generating next question..."}),M&&t.jsxs("div",{className:"planning-elapsed",children:["Thinking… (",q,"s)"]}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>U(!P),type:"button",children:P?"Hide thinking":"Show thinking"}),t.jsx("div",{className:"planning-loading-actions",children:t.jsxs("button",{className:"btn planning-stop-btn",type:"button",onClick:()=>void bt(),children:[t.jsx(Yv,{size:14}),t.jsx("span",{className:"icon-ml-6",children:"Stop"})]})}),P&&v&&t.jsx("div",{className:"planning-thinking-output",ref:$t,children:t.jsx("pre",{children:v})})]})]}),m.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[w.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(si,{entries:w}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:m.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void _t(),disabled:L,children:[L?t.jsx(xt,{size:14,className:"spin"}):t.jsx(rs,{size:14}),t.jsx("span",{className:"icon-ml-6",children:L?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Ft,disabled:L,children:"Dismiss"})]})]})]})}),m.type==="creating"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(xt,{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(VT,{question:m.session.currentQuestion,progress:Nt(),historyEntries:w,onSubmit:Pe,onBack:g.length>0?Ye:void 0})}),m.type==="summary"&&y&&t.jsx(WT,{summary:y,historyEntries:w,onSummaryChange:S,tasks:r,onCreateTask:Yt,onBreakIntoTasks:Xt,onRefine:()=>{dt()},isLoading:!1}),m.type==="breakdown"&&t.jsx(GT,{subtasks:m.subtasks,dirty:m.dirty,isLoading:!1,onUpdateSubtasks:fe=>h({...m,subtasks:fe,dirty:!0}),onCreateTasks:Te,onBack:()=>{const at={sessionId:m.sessionId,currentQuestion:null,summary:y??null};y&&h({type:"summary",session:at,summary:y})}})]}),ne&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Yl,{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:()=>{qe()},disabled:ee,className:"btn btn-primary session-lock-take-control",children:ee?"Taking control...":"Take Control"})]})})]})]})}):null}function VT({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(si,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3].map(p=>t.jsx("div",{className:`planning-progress-step ${p<=n?"active":""}`},p))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~3"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:c,onChange:p=>d(p.target.value),onKeyDown:p=>{p.key==="Enter"&&!p.shiftKey&&c.trim()&&(p.preventDefault(),h())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(p=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:p.id,checked:o[e.id]===p.id,onChange:()=>l({[e.id]:p.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:p.label}),p.description&&t.jsx("span",{className:"planning-option-desc",children:p.description})]})]},p.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(p=>{const g=o[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:p.id,checked:g.includes(p.id),onChange:x=>{const w=x.target.checked?[...g,p.id]:g.filter(b=>b!==p.id);l({[e.id]:w})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:p.label}),p.description&&t.jsx("span",{className:"planning-option-desc",children:p.description})]})]},p.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!0?"selected":""}`,onClick:()=>l({[e.id]:!0}),children:[t.jsx($n,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!1?"selected":""}`,onClick:()=>l({[e.id]:!1}),children:[t.jsx(nn,{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(Aa,{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(yo,{size:16,className:"icon-ml-4"})]})]})]})}function WT({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=go(e.priority),p=g=>{const x=m.includes(g)?m.filter(w=>w!==g):[...m,g];h(x),s({...e,suggestedDependencies:x})};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(ti,{summary:"Show user Q&A",className:"planning-summary-qa-disclosure",children:[t.jsx(si,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx($n,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Planning Complete!"}),t.jsx("p",{className:"text-muted",children:"Review and refine your task before creating it."})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{children:["Description",t.jsx("button",{type:"button",className:"planning-expand-btn",onClick:()=>u(!d),children:d?"Collapse":"Expand"})]}),t.jsx("textarea",{className:`planning-textarea ${d?"expanded":""}`,rows:d?10:4,value:e.description,onChange:g=>s({...e,description:g.target.value})})]}),t.jsxs("div",{className:"planning-summary-meta-row",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"planning-summary-size",children:"Suggested Size"}),t.jsxs("select",{id:"planning-summary-size",className:"planning-size-select",value:e.suggestedSize,onChange:g=>s({...e,suggestedSize:g.target.value}),disabled:c,children:[t.jsx("option",{value:"S",children:"S (Small)"}),t.jsx("option",{value:"M",children:"M (Medium)"}),t.jsx("option",{value:"L",children:"L (Large)"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"planning-summary-priority",children:"Priority"}),t.jsx("select",{id:"planning-summary-priority",className:"planning-size-select",value:f,onChange:g=>s({...e,priority:g.target.value}),disabled:c,children:oa.map(g=>t.jsx("option",{value:g,children:g[0].toUpperCase()+g.slice(1)},g))})]})]}),a.length>0&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Dependencies"}),t.jsx("div",{className:"planning-deps-list",children:a.map(g=>t.jsxs("label",{className:`planning-dep-chip ${m.includes(g.id)?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:m.includes(g.id),onChange:()=>p(g.id)}),t.jsx("span",{className:"planning-dep-id",children:g.id}),t.jsx("span",{className:"planning-dep-title",children:g.title||g.description.slice(0,30)})]},g.id))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Key Deliverables"}),t.jsx("ul",{className:"planning-deliverables",children:e.keyDeliverables.map((g,x)=>t.jsx("li",{children:g},x))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:l,disabled:c,children:[t.jsx(Aa,{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(xt,{size:16,className:"spin icon-mr-8"}),"Creating..."]}):t.jsxs(t.Fragment,{children:[t.jsx($n,{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(xt,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Jl,{size:16,className:"icon-mr-8"}),"Break into Tasks"]})})]})]})]})}function Kp(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 KT(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",priority:js,dependsOn:[]}}function GT({subtasks:e,dirty:n,isLoading:s,onUpdateSubtasks:a,onCreateTasks:r,onBack:o}){const[l,c]=i.useState(null),[d,u]=i.useState(null),[m,h]=i.useState(null),f=i.useRef([]),p=i.useMemo(()=>e.length===0||e.some(j=>!j.title.trim())?!0:Kp(e),[e]),g=i.useCallback((j,P)=>{a(e.map(U=>U.id===j?{...U,...P}:U))},[e,a]),x=i.useCallback(()=>{a([...e,KT(e.length+1)])},[e,a]),w=i.useCallback(j=>{a(e.filter(P=>P.id!==j).map(P=>({...P,dependsOn:P.dependsOn.filter(U=>U!==j)})))},[e,a]),b=i.useCallback((j,P)=>{if(P<0||P>=e.length)return;const U=[...e],[E]=U.splice(j,1);U.splice(P,0,E),a(U)},[e,a]),y=i.useCallback(j=>P=>{c(j),P.dataTransfer.setData("text/plain",j),P.dataTransfer.effectAllowed="move"},[]),S=i.useCallback(()=>{c(null),u(null),h(null)},[]),k=i.useCallback(j=>P=>{if(P.preventDefault(),j===l)return;const U=P.currentTarget.getBoundingClientRect(),E=U.top+U.height/2,R=P.clientY<E?"before":"after";u(j),h(R)},[l]),C=i.useCallback(j=>P=>{P.preventDefault();const U=P.dataTransfer.getData("text/plain");if(!U||U===j){S();return}const E=e.findIndex(O=>O.id===U),R=e.findIndex(O=>O.id===j);if(E===-1||R===-1){S();return}const L=[...e],[F]=L.splice(E,1);let M=R;m==="after"&&E<R&&M--,m==="after"&&M++,L.splice(M,0,F),a(L),S()},[e,m,a,S]),v=i.useCallback(j=>{const P=j.currentTarget.getBoundingClientRect(),U=j.clientX,E=j.clientY;(U<P.left||U>P.right||E<P.top||E>P.bottom)&&(u(null),h(null))},[]);return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Jl,{size:24,className:"icon-triage"}),t.jsx("h4",{children:"Break into Tasks"}),t.jsx("p",{className:"text-muted",children:"Review and edit the subtasks generated from your plan. Adjust titles, descriptions, sizes, priorities, and dependencies before creating."})]}),t.jsxs("div",{className:"planning-summary-form",children:[e.map((j,P)=>{const U=l===j.id,E=d===j.id,R=["task-detail-section","subtask-item",U?"subtask-item-dragging":"",E?"subtask-item-drop-target":"",E&&m==="before"?"subtask-item-drop-before":"",E&&m==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:R,"data-testid":`subtask-item-${P}`,draggable:!s,onDragStart:y(j.id),onDragEnd:S,onDragOver:k(j.id),onDrop:C(j.id),onDragLeave:v,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(Gl,{size:16}),t.jsx("strong",{children:j.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>b(P,P-1),disabled:s||P===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(ka,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>b(P,P+1),disabled:s||P===e.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(vo,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>w(j.id),disabled:s,children:[t.jsx(vn,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:L=>{f.current[P]=L},value:j.title,onChange:L=>g(j.id,{title:L.target.value}),onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),P<e.length-1&&f.current[P+1]?.focus())},disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:j.description,onChange:L=>g(j.id,{description:L.target.value}),disabled:s})]}),t.jsxs("div",{className:"planning-summary-meta-row",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`${j.id}-size`,children:"Size"}),t.jsxs("select",{id:`${j.id}-size`,className:"planning-size-select",value:j.suggestedSize,onChange:L=>g(j.id,{suggestedSize:L.target.value}),disabled:s,children:[t.jsx("option",{value:"S",children:"S"}),t.jsx("option",{value:"M",children:"M"}),t.jsx("option",{value:"L",children:"L"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`${j.id}-priority`,children:"Priority"}),t.jsx("select",{id:`${j.id}-priority`,className:"planning-size-select",value:go(j.priority),onChange:L=>g(j.id,{priority:L.target.value}),disabled:s,children:oa.map(L=>t.jsx("option",{value:L,children:L[0].toUpperCase()+L.slice(1)},L))})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[e.slice(0,P).filter(L=>L.id!==j.id).map(L=>{const F=j.dependsOn.includes(L.id);return t.jsxs("label",{className:`planning-dep-chip ${F?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:F,onChange:()=>{const M=F?j.dependsOn.filter(O=>O!==L.id):[...j.dependsOn,L.id];g(j.id,{dependsOn:M})},disabled:s}),t.jsx("span",{className:"planning-dep-id",children:L.id}),t.jsx("span",{className:"planning-dep-title",children:L.title||"Untitled"})]},L.id)}),P===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),P>0&&e.slice(0,P).filter(L=>L.id!==j.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},j.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:x,disabled:s,children:[t.jsx(bn,{size:16,className:"icon-mr-6"})," Add subtask"]}),Kp(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(Aa,{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(xt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]})}function JT({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(hw,{size:16}),t.jsx("span",{children:"New session"})]})}),t.jsxs("div",{className:"planning-sidebar-list",children:[e.length===0&&!n&&t.jsx("div",{className:"planning-sidebar-empty text-muted",children:"No saved sessions yet. Start one on the right to see it here."}),e.map(f=>{const p=f.id===s,g=a===f.id,x=f.archived===!0,w=f.status==="complete"||f.status==="error";return t.jsxs("div",{className:`planning-sidebar-item ${p?"selected":""} ${g?"pending-delete":""} ${x?"archived":""}`,children:[t.jsxs("button",{type:"button",className:"planning-sidebar-item-button",onClick:()=>c(f.id),children:[t.jsx(YT,{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(QT,{status:f.status}),t.jsx("span",{"aria-hidden":!0,children:" · "}),t.jsx("span",{children:XT(f.updatedAt)})]})]})]}),g?t.jsxs("div",{className:"planning-sidebar-confirm",children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>m(f.id),children:"Delete"}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,children:"Cancel"})]}):t.jsxs("div",{className:"planning-sidebar-item-actions",children:[w&&t.jsx("button",{type:"button",className:"planning-sidebar-item-archive",onClick:b=>{b.stopPropagation(),l(f.id)},"aria-label":x?"Unarchive session":"Archive session",title:x?"Unarchive session":"Archive session",children:x?t.jsx(Cv,{size:14}):t.jsx(xo,{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(vn,{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 YT({status:e}){switch(e){case"generating":return t.jsx(xt,{size:14,className:"spin planning-sidebar-status-icon planning-sidebar-status-generating"});case"awaiting_input":return t.jsx(jd,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-awaiting"});case"complete":return t.jsx($n,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-complete"});case"error":return t.jsx(Ps,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-error"});default:return t.jsx(Hi,{size:14,className:"planning-sidebar-status-icon"})}}function QT({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 XT(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 ZT(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function Gp(e){const n=new Map(e.map(o=>[o.id,o.dependsOn])),s=new Set,a=new Set,r=o=>{if(s.has(o))return!0;if(a.has(o))return!1;s.add(o);for(const l of n.get(o)??[])if(n.has(l)&&r(l))return!0;return s.delete(o),a.add(o),!1};return e.some(o=>r(o.id))}function e4({isOpen:e,onClose:n,initialDescription:s,onTasksCreated:a,parentTaskId:r,projectId:o,resumeSessionId:l}){const c=Ys();vi(e);const{keyboardOverlap:d,viewportHeight:u,viewportOffsetTop:m,keyboardOpen:h}=Wi({enabled:c==="mobile"}),f=h?{"--keyboard-overlap":`${d}px`,"--vv-offset-top":`${m}px`,...u!==null?{"--vv-height":`${u}px`}:{}}:{},[p,g]=i.useState({type:"initial"}),[x,w]=i.useState([]),[b,y]=i.useState([]),[S,k]=i.useState(""),[C,v]=i.useState(!0),[j,P]=i.useState(!1),[U,E]=i.useState(!1),[R,L]=i.useState(s),[F,M]=i.useState(null),[O,q]=i.useState(!1),[te,Z]=i.useState(null),[K,A]=i.useState(null),[I,$]=i.useState(null),N=i.useRef(null),G=i.useRef([]),ge=i.useRef(!1),je=i.useRef(null),ke=p.type==="generating"||p.type==="editing"||p.type==="creating"||p.type==="error"?p.sessionId:null,ne=i.useMemo(()=>Ia(),[]),{isLockedByOther:qe,takeControl:ee,isLoading:le}=lc(e?ke:null),{activeTabMap:se,broadcastUpdate:re,broadcastCompleted:J,broadcastLock:B,broadcastUnlock:ve,broadcastHeartbeat:Ne}=_r(),H=i.useMemo(()=>x.length===0||x.some(Se=>!Se.title.trim())?!0:Gp(x),[x]),be=p.type==="generating"||p.type==="editing"||p.type==="error",ce=ke?se.get(ke):null,{confirm:Me}=ai(),Le=ce&&ce.tabId!==ne,He=!!(Le&&!ce.stale),gt=qe&&(!Le||ce.stale),Ue=i.useCallback(()=>{R&&YI(R,o),N.current?.close(),N.current=null,g({type:"initial"}),w([]),y([]),k(""),v(!0),P(!1),E(!1),M(null),q(!1),ge.current=!1},[R,o]),pe=i.useCallback(()=>{N.current?.close(),N.current=null,n()},[n]),Oe=i.useCallback(async()=>{if(!((O||p.type==="editing"||p.type==="creating")&&!await Me({title:"Discard Changes",message:"Close subtask breakdown? Unsaved changes will be lost.",danger:!0}))){if(ke)try{await _g(ke,o,ne)}catch{}Ue(),n()}},[O,n,Ue,ke,ne,p.type,o,Me]),ze=i.useCallback(Se=>{N.current?.close(),N.current=YN(Se,o,{onThinking:we=>{k(Ae=>Ae+we),re({sessionId:Se,status:"generating",needsInput:!1,owningTabId:ne,type:"subtask",title:R.trim()||void 0,projectId:o??null})},onSubtasks:we=>{P(!1),E(!1),ed(o),w(we),g({type:"editing",sessionId:Se}),q(!1),re({sessionId:Se,status:"awaiting_input",needsInput:!0,owningTabId:ne,type:"subtask",title:R.trim()||void 0,projectId:o??null})},onError:we=>{const Ae=we||"Session failed while contacting the AI.";P(!1),E(!1),M(null),g({type:"error",sessionId:Se,errorMessage:Ae}),re({sessionId:Se,status:"error",needsInput:!1,owningTabId:ne,type:"subtask",title:R.trim()||void 0,projectId:o??null}),J({sessionId:Se,status:"error"})},onComplete:()=>{J({sessionId:Se,status:"complete"})},onConnectionStateChange:we=>{P(we==="reconnecting")}})},[J,re,R,o,ne]),lt=i.useCallback(async()=>{if(R.trim()){M(null),y([]),k(""),P(!1);try{const{sessionId:Se}=await KN(R.trim(),o);g({type:"generating",sessionId:Se}),ze(Se)}catch(Se){M(Re(Se)||"Failed to start subtask breakdown"),g({type:"initial"})}}},[ze,R,o]);i.useEffect(()=>{if(!e){Ue();return}if(e&&s&&!ge.current)L(s),ge.current=!0,lt();else if(e&&!s&&!ge.current){const Se=QI(o);Se&&L(Se)}},[e,s,lt,Ue]),i.useEffect(()=>{!e||!l||p.type!=="initial"||(async()=>{try{const Se=await Ci(l);if(!Se)return;const we=hr(Se.conversationHistory);if(y(we),Se.status==="generating"||Se.status==="awaiting_input")k(Se.thinkingOutput??""),g({type:"generating",sessionId:l}),ze(l);else if(Se.status==="complete"&&Se.result){ed(o);const Ae=JSON.parse(Se.result);w(Ae),g({type:"editing",sessionId:l})}else Se.status==="error"&&(M(null),g({type:"error",sessionId:l,errorMessage:Se.error??"Session encountered an error"}))}catch(Se){M(Re(Se)||"Failed to resume session")}})()},[ze,e,l,p.type,o]),i.useEffect(()=>{if(!e){je.current&&(ve(je.current,ne),je.current=null);return}if(ke&&je.current!==ke){je.current&&ve(je.current,ne),B(ke,ne),je.current=ke;return}!ke&&je.current&&(ve(je.current,ne),je.current=null)},[B,ve,e,ke,ne]),i.useEffect(()=>{if(!e||!ke||je.current!==ke)return;Ne(ne);const Se=setInterval(()=>{Ne(ne)},3e4);return()=>{clearInterval(Se)}},[Ne,e,ke,ne]),i.useEffect(()=>()=>{N.current?.close(),je.current&&(ve(je.current,ne),je.current=null)},[ve,ne]),i.useEffect(()=>{if(!e)return;const Se=we=>{we.key==="Escape"&&(we.preventDefault(),Oe())};return document.addEventListener("keydown",Se),()=>document.removeEventListener("keydown",Se)},[e,Oe]);const Be=i.useCallback((Se,we)=>{w(Ae=>Ae.map(he=>he.id===Se?{...he,...we}:he)),q(!0)},[]),ye=i.useCallback(()=>{w(Se=>[...Se,ZT(Se.length+1)]),q(!0)},[]),Y=i.useCallback(Se=>{w(we=>we.filter(Ae=>Ae.id!==Se).map(Ae=>({...Ae,dependsOn:Ae.dependsOn.filter(he=>he!==Se)}))),q(!0)},[]),_e=i.useCallback(Se=>we=>{Z(Se),we.dataTransfer.setData("text/plain",Se),we.dataTransfer.effectAllowed="move"},[]),ct=i.useCallback(()=>{Z(null),A(null),$(null)},[]),pt=i.useCallback(Se=>we=>{if(we.preventDefault(),Se===te)return;const Ae=we.currentTarget.getBoundingClientRect(),he=Ae.top+Ae.height/2,We=we.clientY<he?"before":"after";A(Se),$(We)},[te]),de=i.useCallback(Se=>we=>{we.preventDefault();const Ae=we.dataTransfer.getData("text/plain");if(!Ae||Ae===Se){Z(null),A(null),$(null);return}w(he=>{const We=he.findIndex($t=>$t.id===Ae),me=he.findIndex($t=>$t.id===Se);if(We===-1||me===-1)return he;const nt=[...he],[Ct]=nt.splice(We,1);let wt=me;return I==="after"&&We<me&&wt--,I==="after"&&wt++,nt.splice(wt,0,Ct),nt}),q(!0),Z(null),A(null),$(null)},[I]),Ve=i.useCallback(Se=>{const we=Se.currentTarget.getBoundingClientRect(),Ae=Se.clientX,he=Se.clientY;(Ae<we.left||Ae>we.right||he<we.top||he>we.bottom)&&(A(null),$(null))},[]),Ee=i.useCallback((Se,we)=>{we<0||we>=x.length||(w(Ae=>{const he=[...Ae],[We]=he.splice(Se,1);return he.splice(we,0,We),he}),q(!0))},[x.length]),$e=i.useCallback(Se=>{G.current[Se+1]?.focus()},[]),ut=i.useCallback(async()=>{if(!(!ke||H)){M(null),g({type:"creating",sessionId:ke});try{const Se=await QN(ke,x,r,o);a(Se.tasks),Ue(),n()}catch(Se){M(Re(Se)||"Failed to create tasks"),g({type:"editing",sessionId:ke})}}},[H,n,a,r,o,Ue,ke,x]),ht=i.useCallback(async()=>{if(p.type!=="error")return;const Se=p.sessionId;M(null),E(!0),k(""),g({type:"generating",sessionId:Se}),ze(Se);try{await GN(Se,o,ne)}catch(we){let Ae=we;if((Re(we)||"").includes("not in an error state"))try{const We=await Ci(Se);if(!We)throw new Error("Failed to refresh subtask session.");if(y(hr(We.conversationHistory)),We.status==="generating"||We.status==="awaiting_input")k(We.thinkingOutput??""),g({type:"generating",sessionId:We.id}),N.current?.isConnected()||ze(We.id);else if(We.status==="complete"){if(!We.result)throw new Error("Subtask session is complete but has no result.");ed(o);const me=JSON.parse(We.result);w(me),g({type:"editing",sessionId:We.id}),q(!1)}else We.status==="error"&&g({type:"error",sessionId:We.id,errorMessage:We.error??"Retry failed. Please try again."});P(!1);return}catch(We){Ae=We}N.current?.close(),N.current=null,g({type:"error",sessionId:Se,errorMessage:Re(Ae)||"Retry failed. Please try again."}),P(!1)}finally{E(!1)}},[ze,o,ne,p]);return e?t.jsx("div",{className:"modal-overlay open",onClick:Se=>Se.target===Se.currentTarget&&void Oe(),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(Jl,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Subtask Breakdown"})]}),t.jsxs("div",{className:"modal-header-actions",children:[be&&t.jsx("button",{className:"modal-send-to-background",onClick:pe,title:"Send to background","aria-label":"Send to background",children:t.jsx(jo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:()=>void Oe(),"aria-label":"Close",children:t.jsx(nn,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[F&&t.jsx("div",{className:"form-error planning-error",children:F}),j&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),He&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),p.type==="initial"&&t.jsx("div",{className:"planning-initial",children:t.jsxs("div",{className:"planning-view-scroll",children:[t.jsx("p",{className:"text-muted",children:"Preparing to break this task into subtasks."}),t.jsx("pre",{className:"planning-thinking-output",children:R})]})}),p.type==="generating"&&t.jsxs("div",{className:"planning-loading",children:[b.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(si,{entries:b,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsx(xt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:"AI is generating subtasks..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>v(!C),type:"button",children:C?"Hide thinking":"Show thinking"}),C&&S&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:S})})]})]}),p.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[b.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(si,{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 ht(),disabled:U,children:[U?t.jsx(xt,{size:14,className:"spin"}):t.jsx(rs,{size:14}),t.jsx("span",{className:"icon-ml-6",children:U?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:()=>void Oe(),disabled:U,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(si,{entries:b}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx($n,{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((Se,we)=>{const Ae=te===Se.id,he=K===Se.id,We=["task-detail-section","subtask-item",Ae?"subtask-item-dragging":"",he?"subtask-item-drop-target":"",he&&I==="before"?"subtask-item-drop-before":"",he&&I==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:We,"data-testid":`subtask-item-${we}`,draggable:p.type!=="creating",onDragStart:_e(Se.id),onDragEnd:ct,onDragOver:pt(Se.id),onDrop:de(Se.id),onDragLeave:Ve,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(Gl,{size:16}),t.jsx("strong",{children:Se.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ee(we,we-1),disabled:p.type==="creating"||we===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(ka,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ee(we,we+1),disabled:p.type==="creating"||we===x.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(vo,{})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>Y(Se.id),disabled:p.type==="creating",children:[t.jsx(vn,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:me=>{G.current[we]=me},value:Se.title,onChange:me=>Be(Se.id,{title:me.target.value}),onKeyDown:me=>{me.key==="Enter"&&(me.preventDefault(),$e(we))},disabled:p.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:8,value:Se.description,onChange:me=>Be(Se.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:Se.suggestedSize,onChange:me=>Be(Se.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,we).filter(me=>me.id!==Se.id).map(me=>{const nt=Se.dependsOn.includes(me.id);return t.jsxs("label",{className:`planning-dep-chip ${nt?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:nt,onChange:()=>{const Ct=nt?Se.dependsOn.filter(wt=>wt!==me.id):[...Se.dependsOn,me.id];Be(Se.id,{dependsOn:Ct})},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)}),we===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),we>0&&x.slice(0,we).filter(me=>me.id!==Se.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},Se.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:ye,disabled:p.type==="creating",children:[t.jsx(bn,{size:16,className:"icon-mr-6"})," Add subtask"]}),Gp(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 Oe(),disabled:p.type==="creating",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:()=>void ut(),disabled:p.type==="creating"||H,children:p.type==="creating"?t.jsxs(t.Fragment,{children:[t.jsx(xt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]}),qe&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Yl,{size:16}),t.jsx("span",{children:gt?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),gt&&t.jsx("button",{type:"button",onClick:()=>{ee()},disabled:le,className:"btn btn-primary session-lock-take-control",children:le?"Taking control...":"Take Control"})]})})]})]})}):null}const t4=5,n4=1e3,s4=45e3;function ll(){return{scrollback:null,connected:null,data:[]}}function i4(e,n){const[s,a]=i.useState("disconnected"),r=i.useRef(0),o=i.useRef(e),l=i.useRef(n),c=o.current!==e||l.current!==n;c&&(o.current=e,l.current=n,r.current++);const d=i.useRef(null),u=i.useRef(0),m=i.useRef(null),h=i.useRef(null),f=i.useRef(!1),p=i.useRef(new Set),g=i.useRef(new Set),x=i.useRef(new Set),w=i.useRef(new Set),b=i.useRef(new Set),y=i.useRef(ll()),S=i.useCallback(M=>{p.current.add(M);const O=y.current;return O.data.length>0&&(O.data.forEach(q=>M(q)),O.data=[]),()=>p.current.delete(M)},[]),k=i.useCallback(M=>(g.current.add(M),()=>g.current.delete(M)),[]),C=i.useCallback(M=>{x.current.add(M);const O=y.current;return O.connected&&(M(O.connected),O.connected=null),()=>x.current.delete(M)},[]),v=i.useCallback(M=>{w.current.add(M);const O=y.current;return O.scrollback&&(M(O.scrollback),O.scrollback=null),()=>w.current.delete(M)},[]),j=i.useCallback(M=>(b.current.add(M),()=>b.current.delete(M)),[]),P=i.useCallback(M=>{const O=d.current;O?.readyState===WebSocket.OPEN&&O.send(JSON.stringify({type:"input",data:M}))},[]),U=i.useCallback((M,O)=>{const q=d.current;q?.readyState===WebSocket.OPEN&&q.send(JSON.stringify({type:"resize",cols:M,rows:O}))},[]),E=i.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),d.current&&(d.current.onopen=null,d.current.onmessage=null,d.current.onclose=null,d.current.onerror=null,d.current.close(),d.current=null),y.current=ll()},[]),R=i.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),d.current&&(f.current=!0,d.current.onopen=null,d.current.onmessage=null,d.current.onclose=null,d.current.onerror=null,d.current.close(),d.current=null),y.current=ll()},[]),L=i.useCallback(()=>{if(!e){a("disconnected");return}if(d.current?.readyState===WebSocket.OPEN)return;d.current&&(f.current=!0,d.current.onopen=null,d.current.onmessage=null,d.current.onclose=null,d.current.onerror=null,d.current.close(),d.current=null),f.current=!1,a("connecting");const M=r.current;let q=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(e)}`;n&&(q+=`&projectId=${encodeURIComponent(n)}`);const te=new WebSocket(Mi(q));d.current=te,te.onopen=()=>{if(r.current!==M){te.close();return}y.current=ll(),a("connected"),u.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===M&&te.readyState===WebSocket.OPEN&&te.send(JSON.stringify({type:"ping"}))},s4)},te.onmessage=Z=>{if(r.current===M)try{const K=JSON.parse(Z.data),A=y.current;switch(K.type){case"data":K.data&&(p.current.size===0&&A.data.push(K.data),p.current.forEach(I=>I(K.data)));break;case"scrollback":K.data&&(A.scrollback=K.data,w.current.forEach(I=>I(K.data)));break;case"connected":K.shell&&K.cwd&&(A.connected={shell:K.shell,cwd:K.cwd},x.current.forEach(I=>I({shell:K.shell,cwd:K.cwd})));break;case"exit":K.exitCode!==void 0&&g.current.forEach(I=>I(K.exitCode));break;case"ping":te.readyState===WebSocket.OPEN&&te.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},te.onclose=Z=>{if(r.current!==M)return;if(d.current=null,h.current&&(clearInterval(h.current),h.current=null),f.current){a("disconnected");return}if(Z.code===4e3||Z.code===4004){a("disconnected"),Z.code===4004&&b.current.forEach(I=>I());return}if(u.current++,u.current>t4){a("disconnected");return}const K=n4*Math.pow(2,u.current-1);a("reconnecting");const A=r.current;m.current=setTimeout(()=>{r.current===A&&(f.current||L())},Math.min(K,16e3))},te.onerror=()=>{}},[e,n]),F=i.useCallback(()=>{u.current=0,R(),L()},[R,L]);return i.useEffect(()=>(c&&(E(),u.current=0,a("disconnected")),e?L():a("disconnected"),R),[e,n,c,L,R,E]),{connectionStatus:s,sendInput:P,resize:U,onData:S,onExit:k,onConnect:C,onScrollback:v,reconnect:F,onSessionInvalid:j}}const Ax="kb-terminal-tabs",a4=15e3,r4=15e3;function Jp(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function Yp(e){if(typeof window>"u")return[];try{const n=Dn(Ax,e);if(n)return JSON.parse(n)}catch{}return[]}function ld(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function Qp(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 o4(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{os(Ax,JSON.stringify(n),e)}catch{}},[e,n]),i.useEffect(()=>{let C=!1;const v=h.current;return(async()=>{if(!C)try{const P=await Qp(Fj(e),a4,"listTerminalSessions");if(C||v!==h.current)return;const U=new Set(P.map(E=>E.id));l(!0),s(E=>{if(C||v!==h.current)return E;const L=E.map(O=>({...O,_verified:U.has(O.sessionId)})).filter(O=>O._verified);if(L.length===0)return[];const F=L.map(({_verified:O,...q})=>q);return F.find(O=>O.isActive)?F:F.map((O,q)=>({...O,isActive:q===0}))}),r(!0)}catch(P){if(C||v!==h.current)return;const U=ld(P);U||console.warn("Failed to validate terminal sessions with server:",P),l(!U),r(!0)}})(),()=>{C=!0}},[e]),i.useEffect(()=>{if(n.length===0&&a&&o){const C=h.current,v=setTimeout(()=>{Qp(Lo(void 0,void 0,void 0,e),r4,"createTerminalSession").then(j=>{if(C!==h.current)return;const P={id:Jp(),sessionId:j.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(U=>U.length>0?U:[...U.map(R=>({...R,isActive:!1})),P]),d(null)}).catch(j=>{if(C!==h.current)return;ld(j)||console.error(j);const P=j instanceof Error?j.message:typeof j=="string"?j:"Failed to create terminal session";d(P)})},0);return()=>clearTimeout(v)}},[a,o,n.length,u]);const f=i.useCallback(async()=>{const C=await Lo(void 0,void 0,void 0,e),v={id:Jp(),sessionId:C.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(j=>[...j.map(U=>({...U,isActive:!1})),v]),v},[n.length]),p=i.useCallback(async()=>f(),[f]),g=i.useCallback(C=>{s(v=>{const j=v.find(R=>R.id===C);if(!j)return v;am(j.sessionId,e).catch(R=>{console.warn(`Failed to kill terminal session ${j.sessionId}:`,R)});const P=v.findIndex(R=>R.id===C),U=j.isActive,E=v.filter(R=>R.id!==C);if(E.length===0)return[];if(U){const R=Math.min(P,E.length-1);return E.map((L,F)=>({...L,isActive:F===R}))}return E})},[]),x=i.useCallback(C=>{s(v=>{let j=!1;const P=v.map(U=>U.id===C?(j=!0,{...U,isActive:!0}):{...U,isActive:!1});return j?P:v})},[]),w=i.useCallback((C,v)=>{s(j=>j.map(P=>P.id===C?{...P,title:v}:P))},[]),b=i.useCallback(async()=>{s(j=>{const P=j.find(U=>U.isActive);return P&&am(P.sessionId,e).catch(U=>{console.warn(`Failed to kill old session ${P.sessionId}:`,U)}),j});const C=n.find(j=>j.isActive);if(!C)return;const v=await Lo(void 0,void 0,void 0,e);s(j=>j.map(P=>P.id===C.id?{...P,sessionId:v.sessionId}:P))},[n]),y=i.useCallback(async()=>{const C=n.find(v=>v.isActive);if(C)try{const v=await Lo(void 0,void 0,void 0,e);s(j=>j.map(P=>P.id===C.id?{...P,sessionId:v.sessionId}:P)),d(null)}catch(v){ld(v)||console.error(v);const j=v instanceof Error?v.message:typeof v=="string"?v:"Failed to create terminal session";d(j)}},[n]),S=n.find(C=>C.isActive)??null,k=i.useCallback(()=>{d(null),h.current+=1,m(C=>C+1)},[]);return{tabs:n,activeTab:S,isReady:a,bootstrapError:c,createTab:p,closeTab:g,setActiveTab:x,updateTabTitle:w,restartActiveTab:b,retryBootstrap:k,replaceActiveTabSession:y}}const l4=1e4,c4=[500,1500,3e3],Px="kb-terminal-font-size",Xr=14,d4=8,u4=32,m4='"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 h4(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 p4(e){return`\x1B${e}`}const f4=[{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 Zr(e){return Math.min(u4,Math.max(d4,e))}function g4(){if(typeof window>"u")return Xr;try{const e=window.localStorage.getItem(Px);if(!e)return Xr;const n=Number.parseInt(e,10);return Number.isFinite(n)?Zr(n):Xr}catch{return Xr}}function b4(e){const n=typeof e=="string"?e:e instanceof Error?e.message:String(e);return n.includes("MIME type")||n.includes("Failed to fetch dynamically imported module")}function x4(e){return new Promise(n=>setTimeout(n,e))}async function v4(e,n=c4){let s;for(let a=0;a<=n.length;a+=1)try{return await e()}catch(r){if(!b4(r))throw r;s===void 0&&(s=r);const o=n[a];if(o===void 0)throw s??r;const l=r instanceof Error?r.message:String(r);console.warn(`[TerminalModal] Dynamic xterm import failed (attempt ${a+1}/${n.length+1}). Retrying in ${o}ms...`,l),await x4(o)}throw s??new Error("Dynamic import failed")}function Xp(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}function y4(){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=w4()-e.offsetTop-e.height;return a>=30&&a>80?a:0}let cd=null;function w4(){return cd===null&&(cd=window.innerHeight),cd}function k4({isOpen:e,onClose:n,initialCommand:s,projectId:a}){const[r,o]=i.useState(null),[l,c]=i.useState(null),[d,u]=i.useState(!1),[m,h]=i.useState(null),[f,p]=i.useState(0),[g,x]=i.useState(0),[w,b]=i.useState(null),[y,S]=i.useState(()=>g4()),[k,C]=i.useState(!1),[v,j]=i.useState(null),P=i.useRef(null),U=i.useRef(null),E=i.useRef(!1);Ai(U,e,"fusion:terminal-modal-size");const R=i.useRef(null),L=i.useRef(null),F=i.useRef(!1),M=i.useRef(!1),O=i.useRef(null),q=i.useRef(()=>{}),te=i.useRef(null),Z=i.useRef(0),K=i.useRef(y),A=i.useRef(null),I=i.useRef(a);Z.current=g,K.current=y;const $=i.useCallback(Ee=>{if(Ee&&M.current!==Ee)return;const $e=L.current,ut=R.current,ht=O.current;if(!(!$e||!ut)&&!(Ee&&M.current!==Ee))try{$e.fit(),ht&&ht(ut.cols,ut.rows)}catch{}},[]);i.useEffect(()=>{e&&p(Ee=>Ee+1)},[e]),i.useEffect(()=>{if(!e||!Xp())return;const Ee=window.visualViewport;if(!Ee)return;const $e=()=>{const ut=y4();x(ut),b(Ee.height),ut>0&&U.current?.scrollIntoView&&U.current.scrollIntoView({block:"end",behavior:"smooth"}),A.current!==null&&(cancelAnimationFrame(A.current),A.current=null);const ht=typeof M.current=="string"?M.current:void 0;A.current=requestAnimationFrame(()=>{A.current=null,$(ht)})};return $e(),Ee.addEventListener("resize",$e),Ee.addEventListener("scroll",$e),()=>{Ee.removeEventListener("resize",$e),Ee.removeEventListener("scroll",$e),A.current!==null&&(cancelAnimationFrame(A.current),A.current=null),x(0),b(null)}},[$,e]),i.useEffect(()=>{if(!e)return;const Ee=U.current;if(!Ee||typeof ResizeObserver>"u")return;let $e=null;const ut=new ResizeObserver(()=>{$e!==null&&cancelAnimationFrame($e),$e=requestAnimationFrame(()=>{$e=null;const ht=typeof M.current=="string"?M.current:void 0;$(ht)})});return ut.observe(Ee),()=>{ut.disconnect(),$e!==null&&cancelAnimationFrame($e)}},[$,e]);const{tabs:N,activeTab:G,isReady:ge,bootstrapError:je,createTab:ke,closeTab:ne,setActiveTab:qe,updateTabTitle:ee,restartActiveTab:le,retryBootstrap:se,replaceActiveTabSession:re}=o4(a),{connectionStatus:J,sendInput:B,resize:ve,onData:Ne,onConnect:H,onExit:be,onScrollback:ce,reconnect:Me,onSessionInvalid:Le}=i4(G?.sessionId??null,a);O.current=ve,q.current=B,i.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Px,String(y))}catch{}},[y]);const He=i.useCallback(()=>{const Ee=R.current;if(Ee)try{L.current?.fit(),ve(Ee.cols,Ee.rows)}catch{}},[ve]);i.useEffect(()=>{if(!e||!ge)return;const Ee=G?.sessionId;if(!Ee)return;const $e=I.current!==a;if($e&&(I.current=a),M.current===Ee&&R.current&&!$e)return;R.current&&(M.current!==Ee||$e)&&(R.current.dispose(),R.current=null,L.current=null,M.current=!1,te.current&&(window.removeEventListener("resize",te.current),te.current=null),u(!1),h(null));let ut=!0,ht;return(async()=>{const we=v4(()=>Promise.all([gn(()=>import("./vendor-xterm-DzcZoU0P.js").then(me=>me.x),__vite__mapDeps([5,1,6])),gn(()=>import("./addon-fit-C7jRorKK.js").then(me=>me.a),__vite__mapDeps([8,1])),gn(()=>import("./addon-web-links-CkJwd4cQ.js").then(me=>me.a),__vite__mapDeps([9,1]))])),Ae=new Promise((me,nt)=>{ht=setTimeout(()=>{nt(new Error("xterm initialization timed out"))},l4)});let he,We;try{const[{Terminal:me},{FitAddon:nt},{WebLinksAddon:Ct}]=await Promise.race([we,Ae]);if(!ut||!P.current||R.current)return;he=new me({cursorBlink:!0,cursorStyle:"block",fontSize:K.current,fontFamily:m4,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}),We=new nt,he.loadAddon(We);const wt=new Ct;if(he.loadAddon(wt),!Xp())try{const{WebglAddon:Mt}=await gn(async()=>{const{WebglAddon:Qt}=await import("./addon-webgl-BjvOw43o.js").then(Kt=>Kt.a);return{WebglAddon:Qt}},__vite__mapDeps([10,1])),Dt=new Mt;Dt.onContextLoss(()=>{Dt.dispose()}),he.loadAddon(Dt)}catch{}he.open(P.current),ht&&clearTimeout(ht);const $t=P.current?.querySelector(".xterm-helper-textarea");if($t&&$t.focus(),P.current)try{P.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{We.fit();const Mt=P.current?.querySelector(".xterm-helper-textarea");Mt&&Mt.focus()},50),R.current=he,L.current=We,M.current=Ee,Z.current>0&&(A.current!==null&&(cancelAnimationFrame(A.current),A.current=null),A.current=requestAnimationFrame(()=>{A.current=null,$(Ee)})),he.onData(Mt=>{M.current===Ee&&q.current(Mt)});const Vt=()=>{if(M.current===Ee&&L.current&&R.current)try{L.current.fit();const{cols:Mt,rows:Dt}=R.current;O.current?.(Mt,Dt)}catch{}};window.addEventListener("resize",Vt),te.current&&window.removeEventListener("resize",te.current),te.current=Vt,u(!0),h(null)}catch(me){if(ht&&clearTimeout(ht),!ut)return;const nt=me instanceof Error?me.message:"xterm initialization failed";h(nt)}})(),()=>{ut=!1,ht&&clearTimeout(ht)}},[$,e,ge,G?.sessionId,a]),i.useEffect(()=>{e||(R.current&&(R.current.dispose(),R.current=null),L.current=null,M.current=!1,te.current&&(window.removeEventListener("resize",te.current),te.current=null),u(!1),h(null),F.current=!1,o(null),c(null),C(!1),j(null))},[e]),i.useEffect(()=>{if(!d||!R.current||!G)return;const Ee=G.sessionId,$e=Ae=>{M.current===Ee&&R.current?.write(Ae)},ut=Ne(Ae=>{$e(Ae)}),ht=ce(Ae=>{$e(Ae)}),Se=H(Ae=>{ee(G.id,gu(Ae.shell)||Ae.shell)}),we=be(Ae=>{M.current===Ee&&(c(Ae),R.current?.write(`\r
|
|
687
|
+
\x1B[33m[Process exited with code ${Ae}]\x1B[0m\r
|
|
688
|
+
`))});return()=>{ut(),ht(),Se(),we()}},[d,G?.sessionId,G?.id,G,J,Ne,ce,H,be,ee]),i.useEffect(()=>{J==="connected"&&s&&F.current!==s&&G&&(F.current=s,setTimeout(()=>{B(s+`
|
|
689
|
+
`)},500))},[J,s,B,G,f]),i.useEffect(()=>{if(!d||!R.current)return;R.current.options.fontSize=y,A.current!==null&&(cancelAnimationFrame(A.current),A.current=null);const Ee=requestAnimationFrame(()=>{A.current=null,He()});return A.current=Ee,()=>{A.current===Ee&&(cancelAnimationFrame(Ee),A.current=null)}},[y,d,He]),i.useEffect(()=>{if(!e)return;const Ee=$e=>{if(!(!$e.ctrlKey&&!$e.metaKey)){if($e.code==="Equal"||$e.code==="NumpadAdd"){$e.preventDefault(),S(ut=>Zr(ut+1));return}if($e.code==="Minus"||$e.code==="NumpadSubtract"){$e.preventDefault(),S(ut=>Zr(ut-1));return}if($e.code==="Digit0"||$e.code==="Numpad0"){$e.preventDefault(),S(Xr);return}}};return window.addEventListener("keydown",Ee),()=>window.removeEventListener("keydown",Ee)},[e,He]),i.useEffect(()=>{if(!e)return;const Ee=$e=>{$e.key==="Escape"&&n()};return document.addEventListener("keydown",Ee),()=>document.removeEventListener("keydown",Ee)},[e,n]),i.useEffect(()=>{J==="connected"&&R.current&&setTimeout(()=>{if(!R.current||!P.current)return;const Ee=P.current.querySelector(".xterm-helper-textarea");Ee&&Ee.focus();try{P.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[J]);const gt=i.useCallback(()=>{if(!P.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;R.current?.focus();const $e=P.current.querySelector(".xterm-helper-textarea");if(!$e)return;$e.autocapitalize="off",$e.autocomplete="off",$e.autocorrect="off",$e.spellcheck=!1,$e.setAttribute("inputmode","text");try{$e.focus({preventScroll:!0})}catch{$e.focus()}const ut=$e.value.length;$e.setSelectionRange(ut,ut)},[]);i.useEffect(()=>Le(()=>{R.current?.clear(),c(null),F.current=!1,R.current&&(R.current.dispose(),R.current=null),L.current=null,M.current=!1,te.current&&(window.removeEventListener("resize",te.current),te.current=null),u(!1),h(null),re().catch($e=>{console.error("Failed to replace invalid terminal session:",$e)})}),[Le,re]);const Ue=i.useCallback(Ee=>{Ee.target===Ee.currentTarget&&(E.current=!0)},[]),pe=i.useCallback(Ee=>{E.current&&Ee.target===Ee.currentTarget&&n(),E.current=!1},[n]),Oe=i.useCallback(()=>{R.current?.clear()},[]),ze=i.useCallback(async()=>{R.current?.clear(),c(null),F.current=!1;try{await le()}catch(Ee){o(Re(Ee)||"Failed to restart terminal session")}},[le]),lt=i.useCallback(()=>{R.current&&(R.current.dispose(),R.current=null),L.current=null,M.current=!1,te.current&&(window.removeEventListener("resize",te.current),te.current=null),h(null),u(!1)},[]),Be=i.useCallback(()=>{window.location.reload()},[]),ye=i.useCallback(()=>{S(Ee=>Zr(Ee+1))},[]),Y=i.useCallback(()=>{S(Ee=>Zr(Ee-1))},[]),_e=i.useCallback(Ee=>{j($e=>$e===Ee?null:Ee)},[]),ct=i.useCallback(Ee=>{if(v==="ctrl"){B(h4(Ee)),j(null);return}if(v==="alt"){B(p4(Ee)),j(null);return}B(Ee)},[B,v]),pt=i.useCallback(Ee=>{B(Ee),j(null)},[B]);if(!e)return null;const de=()=>{switch(J){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}},Ve=!ge||!G&&!je;return t.jsx("div",{className:"modal-overlay open",onMouseDown:Ue,onMouseUp:pe,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:g>0?{"--overlay-padding-top":"0px"}:void 0,children:t.jsxs("div",{ref:U,className:"modal terminal-modal","data-testid":"terminal-modal",style:g>0?{"--keyboard-overlap":`${g}px`,"--vv-height":w?`${w}px`:void 0}:void 0,children:[t.jsxs("div",{className:"terminal-header",children:[t.jsxs("div",{className:"terminal-tabs","data-testid":"terminal-tabs",children:[N.map(Ee=>t.jsxs("div",{className:`terminal-tab ${Ee.isActive?"terminal-tab--active":""}`,onClick:()=>qe(Ee.id),title:Ee.title,role:"tab","aria-selected":Ee.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:Ee.title}),N.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:$e=>{$e.stopPropagation(),ne(Ee.id)},title:"Close tab",children:"×"})]},Ee.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:ke,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(Bi,{size:16}),de()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[J==="disconnected"&&G&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:Me,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(rs,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:ze,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(rs,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:Oe,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[t.jsx(vn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),t.jsxs("button",{className:"terminal-clear-btn terminal-clear-btn--shortcut",onClick:()=>C(Ee=>!Ee),"data-testid":"terminal-shortcut-toggle",title:"Shortcuts","aria-pressed":k,children:[t.jsx(Ky,{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(nn,{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:[Ve&&!je&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),je&&!G&&t.jsx("div",{className:"terminal-loading","data-testid":"terminal-bootstrap-error",children:t.jsxs("div",{className:"terminal-error-content",children:[t.jsxs("span",{children:["Failed to start terminal: ",je]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:se,"data-testid":"terminal-retry-btn",children:[t.jsx(rs,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Be,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(rs,{size:14}),"Refresh page"]})]})]})}),m&&G&&t.jsx("div",{className:"terminal-loading","data-testid":"terminal-xterm-init-error",children:t.jsxs("div",{className:"terminal-error-content",children:[t.jsxs("span",{children:["Terminal UI failed to initialize: ",m]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:lt,"data-testid":"terminal-reinit-btn",children:[t.jsx(rs,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Be,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(rs,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:P,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:gt,onTouchStart:gt},G?.sessionId)]}),k&&t.jsxs("div",{className:"terminal-shortcut-panel","data-testid":"terminal-shortcut-panel",children:[t.jsxs("div",{className:"terminal-shortcut-modifier-row",children:[t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${v==="ctrl"?"is-active":""}`,"data-testid":"terminal-modifier-ctrl",onClick:()=>_e("ctrl"),"aria-pressed":v==="ctrl",children:"Ctrl"}),t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${v==="alt"?"is-active":""}`,"data-testid":"terminal-modifier-alt",onClick:()=>_e("alt"),"aria-pressed":v==="alt",children:"Alt"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>pt("\x1B"),children:"ESC"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>pt(" "),children:"Tab"})]}),f4.map(Ee=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>ct(Ee.key),title:Ee.description,children:Ee.label},Ee.label))]}),t.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[t.jsxs("span",{className:`terminal-connection-status ${J}`,children:[J==="connected"&&"Connected",J==="connecting"&&"Connecting...",J==="reconnecting"&&"Reconnecting...",J==="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:Y,"data-testid":"terminal-font-size-decrease","aria-label":"Decrease terminal font size",children:t.jsx(bw,{size:14})}),t.jsxs("span",{className:"terminal-font-size-value","data-testid":"terminal-font-size-value",children:[y,"px"]}),t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:ye,"data-testid":"terminal-font-size-increase","aria-label":"Increase terminal font size",children:t.jsx(bn,{size:14})})]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • ⌨ Shortcuts panel • Esc close"})]})]})})}const Ur={name:"",command:""};function Zp(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function j4(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function N4({isOpen:e,onClose:n,addToast:s,projectId:a,onRunScript:r}){vi(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(Ur),[x,w]=i.useState(!1),[b,y]=i.useState(null),[S,k]=i.useState(null),C=qi(n),v=i.useCallback(async()=>{try{d(!0);const q=await mo(a);l(q)}catch(q){s(Re(q)||"Failed to load scripts","error")}finally{d(!1)}},[s,a]);i.useEffect(()=>{e&&v()},[e,v]);const j=i.useCallback(()=>{m(!0),f(null),g(Ur),k(null)},[]),P=i.useCallback((q,te)=>{f(q),m(!1),g({name:q,command:te}),k(null)},[]),U=i.useCallback(()=>{f(null),m(!1),g(Ur),k(null)},[]),E=i.useCallback(q=>{g(te=>({...te,name:q})),q&&!Zp(q)?k("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):k(null)},[]),R=i.useCallback(async()=>{const q=p.name.trim(),te=p.command.trim();if(!q){s("Script name is required","error");return}if(!Zp(q)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!te){s("Script command is required","error");return}w(!0);try{await VN(q,te,a),s(h?"Script updated":"Script created","success"),f(null),m(!1),g(Ur),k(null),await v()}catch(Z){const K=Re(Z);K?.includes("already exists")?s("A script with this name already exists","error"):s(K||"Failed to save script","error")}finally{w(!1)}},[p,h,s,v,a]),L=i.useCallback(async q=>{try{await WN(q,a),s("Script deleted","success"),y(null),h===q&&(f(null),g(Ur)),await v()}catch(te){s(Re(te)||"Failed to delete script","error")}},[h,s,v,a]),F=i.useCallback((q,te)=>{r&&r(q,te)},[r]);if(!e)return null;const M=u||h!==null,O=Object.entries(o).map(([q,te])=>({name:q,command:te}));return t.jsx("div",{className:"modal-overlay open",...C,"data-testid":"scripts-modal",children:t.jsxs("div",{className:"modal scripts-modal",role:"dialog","aria-modal":"true","aria-label":"Scripts",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{children:[t.jsx(Bi,{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(xt,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),"Loading scripts..."]}):M?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:q=>E(q.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:q=>g(te=>({...te,command:q.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:U,disabled:x,"data-testid":"script-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:R,disabled:x||!!S,"data-testid":"script-save-btn",children:x?t.jsxs(t.Fragment,{children:[t.jsx(xt,{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:O.length===0?"No scripts defined":`${O.length} script${O.length===1?"":"s"}`}),t.jsxs("button",{className:"btn btn-primary",onClick:j,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx(bn,{size:14}),"Add Script"]})]}),O.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(Bi,{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:O.map(q=>t.jsx("div",{className:"script-card","data-testid":`script-${q.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:q.name})}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:q.command,children:j4(q.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:()=>F(q.name,q.command),title:"Run script","aria-label":`Run ${q.name}`,"data-testid":`run-script-${q.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[t.jsx(Yn,{size:12}),"Run"]}),t.jsx("button",{className:"btn-icon",onClick:()=>P(q.name,q.command),title:"Edit","aria-label":`Edit ${q.name}`,"data-testid":`edit-script-${q.name}`,children:t.jsx(bn,{size:14,style:{transform:"rotate(45deg)"}})}),b===q.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>L(q.name),title:"Confirm delete","aria-label":`Confirm delete ${q.name}`,"data-testid":`confirm-delete-script-${q.name}`,style:{color:"var(--color-error)"},children:t.jsx(vn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>y(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${q.name}`,children:t.jsx(nn,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>y(q.name),title:"Delete","aria-label":`Delete ${q.name}`,"data-testid":`delete-script-${q.name}`,children:t.jsx(vn,{size:14})})]})]})},q.name))})]})})]})})}function S4(e,n,s){const[a,r]=i.useState([]),[o,l]=i.useState("."),[c,d]=i.useState(!1),[u,m]=i.useState(null),[h,f]=i.useState(0),p=i.useCallback(()=>{f(x=>x+1)},[]),g=i.useCallback(x=>{l(x),m(null)},[]);return i.useEffect(()=>{l("."),m(null),r([])},[e]),i.useEffect(()=>{if(!n||!e)return;let x=!1;async function w(){d(!0),m(null);try{const b=await aN(e,o==="."?void 0:o,s);x||r(b.entries)}catch(b){x||(m(Re(b)||"Failed to load files"),r([]))}finally{x||d(!1)}}return w(),()=>{x=!0}},[e,o,n,h,s]),{entries:a,currentPath:o,setPath:g,loading:c,error:u,refresh:p}}function C4(e,n,s,a){const[r,o]=i.useState(""),[l,c]=i.useState(""),[d,u]=i.useState(null),[m,h]=i.useState(!1),[f,p]=i.useState(!1),[g,x]=i.useState(null),w=i.useCallback(S=>{o(S),x(null)},[]);i.useEffect(()=>{if(!e||!n){o(""),c(""),u(null),x(null);return}let S=!1;async function k(){h(!0),x(null);try{const C=await rN(e,n,a);S||(o(C.content),c(C.content),u(C.mtime))}catch(C){S||(x(Re(C)||"Failed to load file"),o(""),c(""),u(null))}finally{S||h(!1)}}return k(),()=>{S=!0}},[e,n,s,a]);const b=r!==l,y=i.useCallback(async()=>{if(!(!e||!n||!b)){p(!0),x(null);try{const S=await oN(e,n,r,a);c(r),u(S.mtime)}catch(S){throw x(Re(S)||"Failed to save file"),S}finally{p(!1)}}},[e,n,r,b,a]);return{content:r,setContent:w,originalContent:l,loading:m,saving:f,error:g,save:y,hasChanges:b,mtime:d}}const E4=1e4;function _4(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function M4(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function A4(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 iN(e);if(u)return;s(_4(f.project)),r(f.tasks.map(M4)),d(null)}catch(f){u||d(Re(f)||"Failed to load workspaces")}finally{u||l(!1)}}m();const h=window.setInterval(()=>{m()},E4);return()=>{u=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:a,loading:o,error:c}}function P4(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function R4(e){return e?new Date(e).toLocaleDateString():""}function ef(e,n){return b0(e,n)}const Br={visible:!1,x:0,y:0,entry:null,entryFullPath:""},dd={type:null,entry:null,entryFullPath:""},I4=200,T4=500,tf=10;function $4({x:e,y:n,entry:s,onAction:a,onClose:r}){const o=i.useRef(null),[l,c]=i.useState({x:e,y:n});i.useEffect(()=>{const m=o.current;if(!m)return;const h=m.getBoundingClientRect(),f=window.visualViewport,p=f?.width&&f.width>0?f.width:window.innerWidth,g=f?.height&&f.height>0?f.height:window.innerHeight,x=f?.offsetLeft??0,w=f?.offsetTop??0,b=8;let y=e-x,S=n-w;y+h.width>p-b&&(y=p-b-h.width),S+h.height>g-b&&(S=g-b-h.height),y<b&&(y=b),S<b&&(S=b),c({x:y+x,y:S+w})},[e,n]),i.useEffect(()=>{const m=h=>{h.key==="Escape"&&r()};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[r]);const d=s.type==="directory",u=[{id:"copy",label:"Copy",icon:sa,disabled:!1},{id:"move",label:"Move",icon:yw,disabled:!1},{id:"rename",label:"Rename",icon:Ds,disabled:!1},...d?[{id:"download-zip",label:"Download as ZIP",icon:xo,disabled:!1}]:[{id:"download",label:"Download",icon:ry,disabled:!1}],{id:"divider",label:"",icon:sa,disabled:!0},{id:"delete",label:"Delete",icon:vn,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 D4({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 L4({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(Br),[f,p]=i.useState(dd),[g,x]=i.useState(!1),[w,b]=i.useState(null),[y,S]=i.useState(!1),[k,C]=i.useState(null),v=i.useRef(null),j=i.useRef(null),P=i.useRef(null),U=i.useRef(!1),E=i.useCallback(()=>{v.current!==null&&(window.clearTimeout(v.current),v.current=null),j.current!==null&&(window.clearTimeout(j.current),j.current=null)},[]),R=i.useCallback(()=>{E(),P.current=null,S(!1),C(null)},[E]);i.useEffect(()=>()=>{E()},[E]);const L=i.useCallback((I,$,N,G)=>{h({visible:!0,x:I,y:$,entry:N,entryFullPath:G})},[]),F=i.useCallback((I,$,N)=>{if(I.touches.length!==1)return;const G=I.touches[0];G&&(R(),P.current={x:G.clientX,y:G.clientY},j.current=window.setTimeout(()=>{S(!0),C(N)},I4),v.current=window.setTimeout(()=>{const ge=P.current;ge&&(U.current=!0,S(!1),C(null),E(),L(ge.x,ge.y,$,N))},T4))},[R,E,L]),M=i.useCallback(I=>{const $=P.current,N=I.touches[0];!$||!N||(Math.abs(N.clientX-$.x)>tf||Math.abs(N.clientY-$.y)>tf)&&R()},[R]),O=i.useCallback(()=>{R()},[R]);i.useEffect(()=>{if(!m.visible)return;const I=document.querySelector(".file-browser-list"),$=()=>{U.current=!1,R(),h(Br)};return I?.addEventListener("scroll",$),()=>I?.removeEventListener("scroll",$)},[R,m.visible]),i.useEffect(()=>{if(!m.visible)return;const I=$=>{$.key==="Escape"&&(U.current=!1,h(Br))};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[m.visible]);const q=i.useCallback((I,$)=>{I.preventDefault(),I.stopPropagation(),R(),U.current=!1,L(I.clientX,I.clientY,$,ef(n,$.name))},[R,n,L]),te=i.useCallback(I=>{if(!m.entry)return;U.current=!1;const $=m.entry,N=m.entryFullPath;if(h(Br),I==="download"){if(!c)return;const G=Ng(c,N,u);window.open(Mi(G),"_blank");return}if(I==="download-zip"){if(!c)return;const G=hN(c,N,u);window.open(Mi(G),"_blank");return}p({type:I,entry:$,entryFullPath:N}),b(null)},[m,c,u]),Z=i.useCallback(async I=>{if(!(!f.type||!f.entry||!c)){x(!0),b(null);try{switch(f.type){case"copy":await cN(c,f.entryFullPath,I,u);break;case"move":await dN(c,f.entryFullPath,I,u);break;case"rename":await mN(c,f.entryFullPath,I,u);break;case"delete":await uN(c,f.entryFullPath,u);break}p(dd),d?.()}catch($){b(Re($)||"Operation failed")}finally{x(!1)}}},[f,c,d,u]),K=i.useCallback(()=>{p(dd),b(null)},[]),A=i.useCallback((I,$)=>{if(U.current){U.current=!1;return}m.visible||(I.type==="directory"?a($):s($))},[m.visible,a,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(xt,{className:"spin",size:24}),t.jsx("span",{children:"Loading files..."})]}):o?t.jsxs("div",{className:"file-browser-error",children:[t.jsxs("p",{children:["Error: ",o]}),l&&t.jsx("button",{className:"btn btn-sm",onClick:l,children:"Retry"})]}):t.jsxs("div",{className:"file-browser",children:[t.jsxs("div",{className:"file-browser-header",children:[n!=="."&&t.jsxs("button",{className:"file-browser-up",onClick:()=>{a(x0(n))},children:[t.jsx(Mn,{size:16,style:{transform:"rotate(-90deg)"}}),"Up one level"]}),t.jsx("span",{className:"file-browser-path",children:n==="."?"Root":Sr(n)})]}),t.jsx("div",{className:"file-browser-list",children:e.length===0?t.jsx("div",{className:"file-browser-empty",children:"(empty directory)"}):e.map(I=>{const $=ef(n,I.name),N=y&&k===$;return t.jsxs("div",{className:`file-node file-node--${I.type} ${N?"file-node--long-pressing":""}`,onClick:()=>A(I,$),onContextMenu:G=>q(G,I),onTouchStart:G=>F(G,I,$),onTouchMove:M,onTouchEnd:O,onTouchCancel:O,children:[t.jsx("div",{className:"file-node-icon",children:I.type==="directory"?t.jsx(bs,{size:16}):t.jsx(mg,{size:16})}),t.jsx("div",{className:"file-node-name",children:I.name}),I.type==="file"&&I.size!==void 0&&t.jsx("div",{className:"file-node-size",children:P4(I.size)}),I.mtime&&t.jsx("div",{className:"file-node-time",children:R4(I.mtime)})]},I.name)})}),m.visible&&m.entry&&t.jsx($4,{x:m.x,y:m.y,entry:m.entry,onAction:te,onClose:()=>{U.current=!1,h(Br)}}),f.type&&f.entry&&t.jsx(D4,{type:f.type,entry:f.entry,entryFullPath:f.entryFullPath,onConfirm:Z,onCancel:K,loading:g,error:w})]})}function O4(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function z4({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=O4(a),h=m&&(s?!0:o),f=r&&!s&&!h,p=i.useMemo(()=>f?e.split(`
|
|
690
|
+
`).length:0,[e,f]),g=i.useCallback(()=>{l(!1)},[]),x=i.useCallback(()=>{l(!0)},[]),w=i.useCallback(()=>{d(y=>!y)},[]),b=i.useCallback(y=>{u.current&&(u.current.scrollTop=y.currentTarget.scrollTop)},[]);return t.jsxs("div",{className:"file-editor-container",children:[m?t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsxs("div",{className:"file-editor-mode-toggle",children:[!s&&t.jsxs("button",{className:`btn btn-sm ${h?"":"btn-primary"}`,onClick:g,disabled:!h,"aria-label":"Edit mode",children:[t.jsx(ug,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${h?"btn-primary":""}`,onClick:x,disabled:h,"aria-label":"Preview mode",children:[t.jsx(kr,{size:14}),"Preview"]})]}),!s&&t.jsx("button",{className:`btn btn-sm ${c?"btn-primary":""}`,onClick:w,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(Nl,{size:14})})]}):!s&&t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsx("div",{className:"file-editor-mode-toggle"}),t.jsx("button",{className:`btn btn-sm ${c?"btn-primary":""}`,onClick:w,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(Nl,{size:14})})]}),h?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(bi,{remarkPlugins:[xi],children:e})}):t.jsxs("div",{className:`file-editor-textarea-shell ${f?"file-editor-textarea-shell--line-numbers":""}`,children:[f&&t.jsx("div",{className:"file-editor-line-numbers",ref:u,"aria-hidden":"true",children:Array.from({length:p},(y,S)=>t.jsx("div",{className:"file-editor-line-number",children:S+1},`line-${S+1}`))}),t.jsx("textarea",{className:`file-editor-textarea ${c?"file-editor-textarea--wrap":""}`,value:e,onChange:y=>n(y.target.value),onScroll:b,readOnly:s,spellCheck:!1,"aria-label":a?`Editor for ${a}`:"File editor"})]})]})}function F4(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function U4({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(Gu,{size:14}):t.jsx(Cd,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(rn,{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(Gu,{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(Cd,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:F4(c.title)})]},c.id))]})]})]})}const B4=768,H4=280,cl=180,dl=500,nf="fusion:file-browser-sidebar-width",sf="kb-files-line-numbers",Rx=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),q4=new Set([...Rx,".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 ud(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return q4.has(n)}function V4(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return Rx.has(n)}function W4({initialWorkspace:e="project",onClose:n,onWorkspaceChange:s,projectId:a}){const{projectName:r,workspaces:o}=A4(a),l=i.useRef(null);Ai(l,!0,"fusion:files-modal-size");const c=qi(n),[d,u]=i.useState(e),[m,h]=i.useState(null),[f,p]=i.useState(!1),[g,x]=i.useState("list"),[w,b]=i.useState(H4),[y,S]=i.useState(!1),{entries:k,currentPath:C,setPath:v,loading:j,error:P,refresh:U}=S4(d,!0,a),{content:E,setContent:R,originalContent:L,loading:F,saving:M,error:O,save:q,hasChanges:te,mtime:Z}=C4(d,m,!0,a);i.useEffect(()=>{u(e)},[e]),i.useEffect(()=>{const le=()=>{p(window.innerWidth<=B4)};return le(),window.addEventListener("resize",le),()=>window.removeEventListener("resize",le)},[]),i.useEffect(()=>{m||x("list")},[m]),i.useEffect(()=>{try{const le=localStorage.getItem(nf);if(!le)return;const se=Number.parseInt(le,10);if(!Number.isNaN(se)){const re=Math.max(cl,Math.min(dl,se));b(re)}}catch{}},[]),i.useEffect(()=>{const le=Dn(sf,a);S(le==="true")},[a]),i.useEffect(()=>{const le=se=>{se.key==="Escape"&&n(),(se.metaKey||se.ctrlKey)&&se.key==="s"&&(se.preventDefault(),te&&!M&&q())};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[n,te,M,q]);const K=i.useCallback(le=>{h(le),f&&x("editor")},[f]),A=i.useCallback(()=>{x("list")},[]),I=i.useCallback(()=>{R(L)},[L,R]),$=i.useCallback(le=>{u(le),h(null),x("list"),s?.(le)},[s]),N=i.useCallback(le=>{try{localStorage.setItem(nf,String(le))}catch{}},[]),G=i.useCallback(le=>{if(f)return;le.preventDefault(),le.stopPropagation();const se=le.currentTarget;typeof se.setPointerCapture=="function"&&se.setPointerCapture(le.pointerId);const re=le.clientX,J=w;let B=J;document.body.style.userSelect="none";const ve=H=>{const be=H.clientX-re,ce=Math.max(cl,Math.min(dl,J+be));B=ce,b(ce)},Ne=H=>{typeof se.releasePointerCapture=="function"&&se.releasePointerCapture(H.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",ve),document.removeEventListener("pointerup",Ne),N(B)};document.addEventListener("pointermove",ve),document.addEventListener("pointerup",Ne)},[f,N,w]),ge=i.useCallback(le=>{if(f)return;const se=20;if(le.key!=="ArrowLeft"&&le.key!=="ArrowRight")return;le.preventDefault();const re=le.key==="ArrowLeft"?-se:se,J=Math.max(cl,Math.min(dl,w+re));b(J),N(J)},[f,N,w]),je=i.useCallback(()=>{S(le=>{const se=!le;return os(sf,String(se),a),se})},[a]),ne=`Files — ${i.useMemo(()=>d==="project"?"Project":o.find(le=>le.id===d)?.id??d,[d,o])}`,qe=i.useMemo(()=>!m||!V4(m)?null:Ng(d,m,a),[m,d,a]),ee=le=>{const se=new Blob([le]).size;return se<1024?`${se} B`:`${(se/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(bs,{size:18}),t.jsx("span",{children:ne}),m&&t.jsx("span",{className:"file-browser-header-path",children:m})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsxs("button",{className:`btn btn-sm file-browser-line-numbers-toggle ${y?"btn-primary":""}`,onClick:je,"aria-label":"Toggle line numbers","aria-pressed":y,title:"Toggle line numbers",children:[t.jsx(tw,{size:14}),t.jsx("span",{children:"Line #"})]}),t.jsx(U4,{currentWorkspace:d,projectName:r,workspaces:o,onSelect:$}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(nn,{size:20})})]})]}),t.jsxs("div",{className:"file-browser-body",children:[t.jsx("div",{className:`file-browser-sidebar ${f?"mobile":""} ${g==="list"?"active":""}`,style:f?void 0:{width:`${w}px`},children:t.jsx(L4,{entries:k,currentPath:C,onSelectFile:K,onNavigate:v,loading:j,error:P,onRetry:U,workspace:d,onRefresh:U,projectId:a})}),!f&&t.jsx("div",{className:"file-browser-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":cl,"aria-valuemax":dl,"aria-valuenow":w,"aria-label":"Resize sidebar",tabIndex:0,onPointerDown:G,onKeyDown:ge}),t.jsx("div",{className:`file-browser-content ${f?"mobile":""} ${g==="editor"?"active":""}`,children:m?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"file-browser-toolbar",children:[t.jsxs("div",{className:"file-browser-file-info",children:[f&&g==="editor"&&t.jsxs("button",{className:"file-browser-back-button",onClick:A,"aria-label":"Back to file list",children:[t.jsx(Aa,{size:16}),t.jsx("span",{children:"Back"})]}),m,ud(m)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(Ny,{size:12}),"Binary file — read only"]}),Z&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(Z).toLocaleString()]}),F&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!qe&&te&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:I,disabled:M,children:[t.jsx($w,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void q(),disabled:M,children:[t.jsx(bg,{size:14}),M?"Saving...":"Save"]})]})})]}),O&&!qe&&t.jsx("div",{className:"file-browser-error-banner",children:O}),qe?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:qe,alt:m??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(z4,{content:E,onChange:R,filePath:m,readOnly:ud(m),showLineNumbers:y&&!ud(m)})}),!qe&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:ee(E)}),te&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(bs,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}const K4=i.lazy(()=>gn(()=>import("./TodoView-DCRIkDZ-.js"),__vite__mapDeps([11,1,5,6,12])).then(e=>({default:e.TodoView})));function G4({onClose:e,projectId:n,addToast:s,onPlanningMode:a}){const r=qi(e),l=Ys()==="mobile",{keyboardOverlap:c,viewportHeight:d,viewportOffsetTop:u,keyboardOpen:m}=Wi({enabled:l});vi(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(Zy,{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(nn,{size:20})})]}),t.jsx("div",{className:"todo-modal-body",children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(K4,{projectId:n,addToast:s,onPlanningMode:a,onClose:e,mobileKeyboardActive:l&&m})})})]})})}function J4(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 oj();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:Re(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 Y4(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 Q4(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const Ix="kb-usage-hidden-windows",Tx="kb-usage-modal-size",$x="kb-usage-provider-order";function af(e){const n=Dn(Tx,e);if(!n)return null;try{const s=JSON.parse(n);if(s&&typeof s.width=="number"&&typeof s.height=="number"&&s.width>0&&s.height>0)return{width:s.width,height:s.height}}catch{}return null}function rf(e){const n=Dn(Ix,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 X4(e,n){os(Ix,JSON.stringify(e),n)}function of(e){const n=Dn($x,e);if(!n)return[];try{const s=JSON.parse(n);return Array.isArray(s)?s.filter(a=>typeof a=="string"):[]}catch{return[]}}function lf(e,n){os($x,JSON.stringify(e),n)}function Dx(e,n,s){return s[e]?.includes(n)??!1}function Z4({window:e,viewMode:n,isHidden:s,onToggleHidden:a}){const r=Q4(e.percentUsed),o=n==="remaining",l=Math.round(o?e.percentLeft:e.percentUsed),c=o?`${Math.round(e.percentLeft)}% remaining`:`${Math.round(e.percentUsed)}% used`,d=o?`${Math.round(e.percentUsed)}% used`:`${Math.round(e.percentLeft)}% left`;let u=e.resetText;if(!u&&e.resetAt){const w=new Date(e.resetAt).getTime()-Date.now();if(w>0){const b=Math.floor(w/36e5),y=Math.floor(b/24),S=b%24;y>0&&S>0?u=`resets in ${y}d ${S}h`:y>0?u=`resets in ${y}d`:b>0?u=`resets in ${b}h`:u=`resets in ${Math.floor(w/6e4)}m`}}const m=e.pace,h=m!==void 0;let f=0;h&&(f=o?100-m.percentElapsed:m.percentElapsed);const p=m?.status==="ahead",g=m?.status==="behind",x=m?.status==="on-track";return t.jsxs("div",{className:`usage-window ${s?"usage-window--hidden":""}`,children:[t.jsxs("div",{className:"usage-window-header",children:[t.jsx("span",{className:"usage-window-label",children:e.label}),t.jsxs("div",{className:"usage-window-header-controls",children:[!s&&t.jsx("span",{className:"usage-window-percentage",children:c}),!s&&t.jsx("button",{className:"btn-icon usage-window-hide-btn",onClick:a,"aria-label":`Hide ${e.label}`,"data-testid":"usage-window-hide-btn",children:t.jsx(kr,{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:Y4(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(No,{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(sk,{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($n,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:m.message})]})]})]})}function e$(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 t$({provider:e,viewMode:n,hiddenWindows:s,onToggleWindow:a,onShowAllHidden:r,isDragging:o,isDragOver:l,dragOverPosition:c,onDragStart:d,onDragOver:u,onDragLeave:m,onDrop:h,onDragEnd:f,isTouchReorderMode:p,canMoveUp:g,canMoveDown:x,onMoveUp:w,onMoveDown:b}){const y=s[e.name]?.length??0,S=()=>{switch(e.status){case"ok":return null;case"error":return t.jsx("span",{className:"usage-status-badge usage-status-badge--error",children:"Error"});case"no-auth":default:return t.jsx("span",{className:"usage-status-badge usage-status-badge--not-configured",children:"Not configured"})}};return t.jsxs("div",{className:`usage-provider${o?" usage-provider--dragging":""}${l&&c==="before"?" usage-provider--drag-over-before":""}${l&&c==="after"?" usage-provider--drag-over-after":""}`,"data-provider":e.name,"data-status":e.status,draggable:!p,onDragStart:p?void 0:d,onDragOver:p?void 0:u,onDragLeave:p?void 0:m,onDrop:p?void 0:h,onDragEnd:p?void 0:f,children:[t.jsxs("div",{className:"usage-provider-header",children:[t.jsxs("div",{className:"usage-provider-info",children:[t.jsx(Sn,{provider:e$(e.name),size:"md"}),t.jsx("span",{className:"usage-provider-name",children:e.name}),y>0&&t.jsxs("button",{className:"btn btn-sm usage-show-hidden-btn",onClick:()=>r(e.name),"data-testid":"usage-show-hidden-btn",children:["Show hidden (",y,")"]})]}),t.jsxs("div",{className:"usage-provider-actions",children:[p&&t.jsxs("div",{className:"usage-provider-reorder-controls",role:"group","aria-label":`Reorder ${e.name}`,children:[t.jsx("button",{className:"btn-icon usage-provider-reorder-btn",type:"button",onClick:w,disabled:!g,"aria-label":`Move ${e.name} up`,children:t.jsx(Ei,{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(rn,{size:14})})]}),S(),t.jsx("div",{className:"usage-provider-drag-handle","aria-hidden":"true",children:t.jsx(Gl,{size:16})})]})]}),e.error&&t.jsx("div",{className:"usage-provider-error",children:e.error}),e.plan&&t.jsx("div",{className:"usage-provider-meta",children:t.jsx("span",{className:"usage-provider-plan",children:e.plan})}),e.windows.length>0?t.jsx("div",{className:"usage-provider-windows",children:e.windows.map((k,C)=>{const v=Dx(e.name,k.label,s);return t.jsx(Z4,{window:k,viewMode:n,isHidden:v,onToggleHidden:()=>a(e.name,k.label)},`${e.name}-${k.label}-${C}`)})}):e.status==="ok"?t.jsx("div",{className:"usage-provider-empty",children:"No usage data available"}):null]})}function n$(){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 s$({isOpen:e,onClose:n,projectId:s,anchorRect:a}){const{providers:r,loading:o,error:l,lastUpdated:c,refresh:d}=J4({autoRefresh:e}),[u,m]=i.useState(!1),[h,f]=i.useState(()=>typeof window<"u"?window.innerWidth>=769:!1),[p,g]=i.useState(()=>typeof window>"u"?!1:window.matchMedia?.("(pointer: coarse)").matches??!1),[x,w]=i.useState("used"),[b,y]=i.useState(()=>rf(s)),[S,k]=i.useState(()=>of(s)),[C,v]=i.useState(null),[j,P]=i.useState(null),[U,E]=i.useState(null),R=i.useRef(null),L=i.useRef(null),F=i.useRef(e),M=i.useRef(!1),[O,q]=i.useState(()=>af(s));i.useEffect(()=>{q(af(s))},[s]),i.useEffect(()=>{if(!e||!h)return;const H=L.current;if(!H||typeof ResizeObserver>"u")return;let be=null;const ce=new ResizeObserver(Me=>{const Le=Me[0];if(!Le)return;const{width:He,height:gt}=Le.contentRect;He<=0||gt<=0||(be&&clearTimeout(be),be=setTimeout(()=>{os(Tx,JSON.stringify({width:Math.round(He),height:Math.round(gt)}),s)},250))});return ce.observe(H),()=>{be&&clearTimeout(be),ce.disconnect()}},[e,h,s]),i.useEffect(()=>{e||(M.current=!1)},[e]),i.useEffect(()=>{r.length>0&&(M.current=!0)},[r.length]),i.useEffect(()=>{if(typeof window>"u")return;const H=window.matchMedia?.("(pointer: coarse)"),be=()=>{f(window.innerWidth>=769),g(H?.matches??!1)};return be(),window.addEventListener("resize",be),H?.addEventListener?.("change",be),()=>{window.removeEventListener("resize",be),H?.removeEventListener?.("change",be)}},[]),i.useEffect(()=>{!F.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&d(),F.current=e},[e,c,d]),i.useEffect(()=>{const H=Dn("kb-usage-view-mode",s);if(H==="used"||H==="remaining"){w(H);return}w("used")},[s]);const te=i.useCallback(H=>{w(H),os("kb-usage-view-mode",H,s)},[s]);i.useEffect(()=>{y(rf(s)),k(of(s))},[s]),i.useEffect(()=>{X4(b,s)},[b,s]);const Z=i.useCallback((H,be)=>{y(ce=>{if(Dx(H,be,ce)){const Me=(ce[H]??[]).filter(Le=>Le!==be);if(Me.length===0){const{[H]:Le,...He}=ce;return He}return{...ce,[H]:Me}}return{...ce,[H]:[...ce[H]??[],be]}})},[]),K=i.useCallback(H=>{y(be=>{if(!be[H])return be;const{[H]:ce,...Me}=be;return Me})},[]),A=i.useCallback(H=>{if(S.length===0)return H;const be=new Map(H.map(Me=>[Me.name,Me])),ce=[];for(const Me of S){const Le=be.get(Me);Le&&(ce.push(Le),be.delete(Me))}return[...ce,...be.values()]},[S]),I=i.useCallback((H,be)=>{H.dataTransfer.effectAllowed="move",H.dataTransfer.setData("text/plain",be),v(be)},[]),$=i.useCallback((H,be)=>{if(!C||C===be)return;H.preventDefault(),H.dataTransfer.dropEffect="move";const{top:ce,height:Me}=H.currentTarget.getBoundingClientRect(),Le=ce+Me/2,He=H.clientY<Le?"before":"after";P(be),E(He)},[C]),N=i.useCallback((H,be)=>{H.preventDefault();const ce=C??H.dataTransfer.getData("text/plain");if(!ce||ce===be){P(null),E(null);return}const Le=A(r).map(Ue=>Ue.name).filter(Ue=>Ue!==ce),He=Le.indexOf(be);if(He<0){P(null),E(null);return}const gt=U==="after"?He+1:He;Le.splice(gt,0,ce),lf(Le,s),k(Le),P(null),E(null)},[C,U,s,r,A]),G=i.useCallback(()=>{v(null),P(null),E(null)},[]),ge=i.useCallback((H,be)=>{const ce=A(r).map(Ue=>Ue.name),Me=ce.indexOf(H),Le=Me+be;if(Me<0||Le<0||Le>=ce.length)return;const He=[...ce],[gt]=He.splice(Me,1);He.splice(Le,0,gt),lf(He,s),k(He)},[s,r,A]),je=i.useCallback(async()=>{m(!0),await d(),m(!1)},[d]);i.useEffect(()=>{if(!e)return;const H=be=>{be.key==="Escape"&&n()};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[e,n]);const ke=i.useCallback(H=>{H.target===H.currentTarget&&n()},[n]);if(!e)return null;const ne=!!(a&&h),qe=8,ee=12,se=O?.width??420,re=ne?Math.min((a?.bottom??0)+qe,window.innerHeight-ee):void 0,J=ne?Math.max(8,(a?.right??0)-se):void 0,B=h&&O?{width:O.width,height:O.height}:{},ve=A(r),Ne=t.jsxs("div",{ref:L,className:`usage-modal${ne?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:ne?{position:"fixed",top:re,left:J,...B}:B,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Ks,{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:()=>te("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:()=>te("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(nn,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:R,children:(o||!M.current&&!l)&&r.length===0?t.jsx(n$,{}):l&&r.length===0?t.jsxs("div",{className:"usage-error",children:[t.jsx("p",{children:"Failed to load usage data"}),t.jsx("p",{className:"usage-error-message",children:l}),t.jsx("button",{className:"btn btn-sm",onClick:je,children:"Retry"})]}):r.length===0?t.jsxs("div",{className:"usage-empty",children:[t.jsx("p",{children:"No AI providers configured"}),t.jsx("p",{className:"usage-empty-hint",children:"Configure authentication in Settings to see usage data."})]}):t.jsx("div",{className:"usage-providers",children:ve.map((H,be)=>t.jsx(t$,{provider:H,viewMode:x,hiddenWindows:b,onToggleWindow:Z,onShowAllHidden:K,isDragging:C===H.name,isDragOver:j===H.name,dragOverPosition:j===H.name?U:null,onDragStart:ce=>I(ce,H.name),onDragOver:ce=>$(ce,H.name),onDragLeave:()=>{j===H.name&&(P(null),E(null))},onDrop:ce=>N(ce,H.name),onDragEnd:G,isTouchReorderMode:p,canMoveUp:be>0,canMoveDown:be<ve.length-1,onMoveUp:()=>ge(H.name,-1),onMoveDown:()=>ge(H.name,1)},H.name))})}),t.jsxs("div",{className:"modal-actions usage-actions",children:[t.jsx("div",{className:"modal-actions-left usage-actions-left",children:t.jsx("div",{className:"usage-last-updated",children:c&&t.jsxs("span",{children:["Last updated: ",c.toLocaleTimeString()]})})}),t.jsxs("div",{className:"modal-actions-right usage-actions-right",children:[t.jsxs("button",{className:"btn btn-sm",onClick:je,disabled:o||u,"data-testid":"usage-refresh-btn",children:[t.jsx(rs,{size:14,className:u?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]});return ne?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"usage-popover-backdrop",onClick:n,"data-testid":"usage-modal-overlay"}),Ne]}):t.jsx("div",{className:"modal-overlay open",onClick:ke,"data-testid":"usage-modal-overlay",children:Ne})}function Lx(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 zl(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 i$={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},Ox={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},a$={cron:og,webhook:xg,api:lg,manual:Qn},r$={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},o$={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function l$({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($n,{size:12}):t.jsx(wo,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:Lx(n)})]})}function c$({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"} ${zl(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx($n,{size:12}):t.jsx(wo,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:zl(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:Ox[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:Lx(r)}),s?t.jsx(Ei,{size:12}):t.jsx(rn,{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 d$({routine:e,onEdit:n,onDelete:s,onRun:a,onToggle:r,running:o,lastRunOutput:l}){const[c,d]=i.useState(!1),{confirm:u}=ai(),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=i$[e.trigger.type],f=a$[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}),Ox[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(Wl,{size:10}):t.jsx(bs,{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(xt,{className:"spinner"}):t.jsx(Yn,{})}),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(pi,{}):t.jsx(Yn,{})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(Ds,{})}),t.jsx("button",{className:"btn-icon",onClick:m,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(vn,{})})]})]}),t.jsxs("div",{className:"routine-card-meta",children:[e.steps&&e.steps.length>0?t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(ja,{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(Hi,{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:r$[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:o$[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:zl(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:zl(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(l$,{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(Ei,{size:12}):t.jsx(rn,{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(c$,{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 u$({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(Bi,{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(sw,{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(ps,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function md(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function m$(e){return e==="command"?{id:md(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:md(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:md(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function h$({step:e,onSave:n,onCancel:s}){const[a,r]=i.useState(e.name),[o,l]=i.useState(e.type),[c,d]=i.useState(e.command??""),[u,m]=i.useState(e.prompt??""),[h,f]=i.useState(e.modelProvider??""),[p,g]=i.useState(e.modelId??""),[x,w]=i.useState(e.taskTitle??""),[b,y]=i.useState(e.taskDescription??""),[S,k]=i.useState(e.taskColumn??"triage"),[C,v]=i.useState(e.timeoutMs),[j,P]=i.useState(e.continueOnFailure??!1),[U,E]=i.useState({}),[R,L]=i.useState([]),[F,M]=i.useState(!1),[O,q]=i.useState(null);i.useEffect(()=>{let I=!1;return M(!0),q(null),Os().then($=>{I||L($.models)}).catch($=>{I||q($ instanceof Error?$.message:"Failed to load models")}).finally(()=>{I||M(!1)}),()=>{I=!0}},[]);const te=i.useCallback(()=>{const I={};return a.trim()||(I.name="Step name is required"),o==="command"&&!c.trim()&&(I.command="Command is required"),o==="ai-prompt"&&!u.trim()&&(I.prompt="Prompt is required"),o==="create-task"&&!b.trim()&&(I.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(h||p)&&(!h||!p)&&(I.modelProvider="Both model provider and model ID must be set together"),C!==void 0&&C<1e3&&(I.timeoutMs="Timeout must be at least 1 second (1000ms)"),E(I),Object.keys(I).length===0},[a,o,c,u,b,h,p,C]),Z=h&&p?`${h}/${p}`:"",K=i.useCallback(I=>{if(!I)f(""),g("");else{const $=I.indexOf("/");$!==-1&&(f(I.slice(0,$)),g(I.slice($+1)))}},[]),A=i.useCallback(()=>{if(!te())return;const I={...e,name:a.trim(),type:o,command:o==="command"?c.trim():void 0,prompt:o==="ai-prompt"?u.trim():void 0,taskTitle:o==="create-task"&&x.trim()?x.trim():void 0,taskDescription:o==="create-task"&&b.trim()?b.trim():void 0,taskColumn:o==="create-task"?S:void 0,modelProvider:(o==="ai-prompt"||o==="create-task")&&h.trim()?h.trim():void 0,modelId:(o==="ai-prompt"||o==="create-task")&&p.trim()?p.trim():void 0,timeoutMs:C||void 0,continueOnFailure:j};o!=="ai-prompt"&&delete I.prompt,o!=="create-task"&&(delete I.taskTitle,delete I.taskDescription,delete I.taskColumn),n(I)},[te,n,e,a,o,c,u,x,b,S,h,p,C,j]);return t.jsxs("div",{className:"step-editor",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-name-${e.id}`,children:"Step Name"}),t.jsx("input",{id:`step-name-${e.id}`,type:"text",placeholder:"e.g. Run tests",value:a,onChange:I=>r(I.target.value),"aria-invalid":!!U.name}),U.name&&t.jsx("small",{className:"field-error",children:U.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-type-${e.id}`,children:"Step Type"}),t.jsxs("select",{id:`step-type-${e.id}`,value:o,onChange:I=>l(I.target.value),children:[t.jsx("option",{value:"command",children:"Command"}),t.jsx("option",{value:"ai-prompt",children:"AI Prompt"}),t.jsx("option",{value:"create-task",children:"Create Task"})]})]}),o==="command"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-command-${e.id}`,children:"Command"}),t.jsx("textarea",{id:`step-command-${e.id}`,placeholder:"e.g. npm test",value:c,onChange:I=>d(I.target.value),rows:2,"aria-invalid":!!U.command}),U.command&&t.jsx("small",{className:"field-error",children:U.command})]}),o==="ai-prompt"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-prompt-${e.id}`,children:"Prompt"}),t.jsx("textarea",{id:`step-prompt-${e.id}`,placeholder:"e.g. Summarize the test results and highlight any failures",value:u,onChange:I=>m(I.target.value),rows:3,"aria-invalid":!!U.prompt}),U.prompt&&t.jsx("small",{className:"field-error",children:U.prompt})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-model-${e.id}`,children:"Model (optional)"}),t.jsx(ys,{id:`step-model-${e.id}`,label:"Model",models:R,value:Z,onChange:K,placeholder:"Use default",disabled:F}),O&&t.jsx("small",{className:"field-error",children:O}),t.jsx("small",{children:"AI model for this step. Uses default if not selected."})]})]}),o==="create-task"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-title-${e.id}`,children:"Task Title (optional)"}),t.jsx("input",{id:`step-task-title-${e.id}`,type:"text",placeholder:"e.g. Review weekly dependencies",value:x,onChange:I=>w(I.target.value)}),t.jsx("small",{children:"Leave blank to auto-summarize from description"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-description-${e.id}`,children:"Task Description *"}),t.jsx("textarea",{id:`step-task-description-${e.id}`,placeholder:"e.g. Check all npm dependencies for security vulnerabilities and update outdated packages",value:b,onChange:I=>y(I.target.value),rows:4,"aria-invalid":!!U.taskDescription}),U.taskDescription&&t.jsx("small",{className:"field-error",children:U.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:I=>k(I.target.value),children:[t.jsx("option",{value:"triage",children:"Triage"}),t.jsx("option",{value:"todo",children:"To Do"})]}),t.jsx("small",{children:"Column where the new task will be created"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-model-${e.id}`,children:"Executor Model (optional)"}),t.jsx(ys,{id:`step-task-model-${e.id}`,label:"Model",models:R,value:Z,onChange:K,placeholder:"Use default",disabled:F}),O&&t.jsx("small",{className:"field-error",children:O}),U.modelProvider&&t.jsx("small",{className:"field-error",children:U.modelProvider}),t.jsx("small",{children:"AI model for executing the created task. Uses default if not selected."})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-timeout-${e.id}`,children:"Timeout (ms, optional)"}),t.jsx("input",{id:`step-timeout-${e.id}`,type:"number",min:1e3,step:1e3,placeholder:"Override schedule timeout",value:C??"",onChange:I=>v(I.target.value?Number(I.target.value):void 0),"aria-invalid":!!U.timeoutMs}),U.timeoutMs&&t.jsx("small",{className:"field-error",children:U.timeoutMs})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:`step-continue-${e.id}`,className:"checkbox-label",children:[t.jsx("input",{id:`step-continue-${e.id}`,type:"checkbox",checked:j,onChange:I=>P(I.target.checked)}),"Continue on failure"]}),t.jsx("small",{children:"If checked, the next step will run even if this one fails"})]}),t.jsxs("div",{className:"step-editor-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:A,children:"Save Step"})]})]})}function p$({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=m$(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(h$,{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(Gl,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(u$,{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(Ei,{})}),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(rn,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(u.id),title:"Edit","aria-label":`Edit ${u.name}`,children:t.jsx(Ds,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(u.id),title:"Delete","aria-label":`Delete ${u.name}`,children:t.jsx(vn,{})})]})]})},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(bn,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx(bn,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx(bn,{size:14}),"Add Create Task Step"]})]})]})}const zx={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},f$={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function g$(e){const n=e.trim();for(const[s,a]of Object.entries(zx))if(a===n)return s;return"custom"}function b$(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function x$(e,n,s,a,r){switch(e){case"cron":return{type:"cron",cronExpression:n};case"webhook":return{type:"webhook",webhookPath:s||"/trigger/"+Math.random().toString(36).slice(2,10),secret:a||void 0};case"api":return{type:"api",endpoint:r||"/api/routine/"+Math.random().toString(36).slice(2,10)};case"manual":return{type:"manual"}}}function v$(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 y$=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],w$=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function cf(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function df({routine:e,onSubmit:n,onCancel:s,scope:a,projectId:r,onScopeChange:o}){const l=!!e,c=e?v$(e):{triggerType:"cron",cronExpression:"0 * * * *",webhookPath:"",webhookSecret:"",endpoint:""},[d,u]=i.useState(e?.name??""),[m,h]=i.useState(e?.description??""),[f,p]=i.useState(c.triggerType),[g,x]=i.useState(c.cronExpression),[w,b]=i.useState(()=>c.triggerType!=="cron"?"custom":g$(c.cronExpression)),[y,S]=i.useState(c.webhookPath),[k,C]=i.useState(c.webhookSecret),[v,j]=i.useState(c.endpoint),[P,U]=i.useState(e?.executionPolicy??"queue"),[E,R]=i.useState(e?.catchUpPolicy??"run_one"),[L,F]=i.useState(e?.enabled??!0),M=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,O=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[q,te]=i.useState(e?.steps&&e.steps.length>0&&!M&&!O?"advanced":"simple"),[Z,K]=i.useState(()=>M?"ai-prompt":O?"create-task":"command"),[A,I]=i.useState(e?.command??""),[$,N]=i.useState(e?.steps??[]),[G,ge]=i.useState(!1),[je,ke]=i.useState(e?.timeoutMs??3e5),[ne,qe]=i.useState(M?e.steps?.[0]?.prompt??"":""),[ee,le]=i.useState(O?e.steps?.[0]?.taskTitle??"":""),[se,re]=i.useState(O?e.steps?.[0]?.taskDescription??"":""),[J,B]=i.useState(O?e.steps?.[0]?.taskColumn??"triage":"triage"),[ve,Ne]=i.useState(M||O?e.steps?.[0]?.modelProvider??"":""),[H,be]=i.useState(M||O?e.steps?.[0]?.modelId??"":""),[ce,Me]=i.useState([]),[Le,He]=i.useState(!1),[gt,Ue]=i.useState(null),[pe,Oe]=i.useState(a??"global"),[ze,lt]=i.useState({}),[Be,ye]=i.useState(!1),Y=i.useRef(!0);i.useEffect(()=>()=>{Y.current=!1},[]),i.useEffect(()=>{a&&Oe(a)},[a]),i.useEffect(()=>{let me=!1;return He(!0),Ue(null),Os().then(nt=>{me||Me(nt.models)}).catch(nt=>{me||Ue(nt instanceof Error?nt.message:"Failed to load models")}).finally(()=>{me||He(!1)}),()=>{me=!0}},[]);const _e=ve&&H?`${ve}/${H}`:"",ct=i.useCallback(me=>{if(!me){Ne(""),be("");return}const nt=me.indexOf("/");nt!==-1&&(Ne(me.slice(0,nt)),be(me.slice(nt+1)))},[]),pt=i.useCallback(()=>{const me={};if(d.trim()||(me.name="Name is required"),pe==="project"&&!r&&(me.scope="Project-specific entries require an active project."),f==="cron"&&w==="custom"&&(g.trim()?b$(g)||(me.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):me.cronExpression="Cron expression is required"),f==="webhook"&&!y.trim()&&(me.webhookPath="Webhook path is required"),f==="api"&&!v.trim()&&(me.endpoint="API endpoint is required"),q==="simple")Z==="command"&&!A.trim()&&(me.command="Command is required"),Z==="ai-prompt"&&!ne.trim()&&(me.prompt="Prompt is required"),Z==="create-task"&&!se.trim()&&(me.taskDescription="Task description is required"),(ve.trim()&&!H.trim()||!ve.trim()&&H.trim())&&(me.model="Both model provider and model ID must be set, or both must be empty");else{$.length===0&&(me.steps="At least one step is required"),G&&(me.stepsEditing="Please save or cancel all step edits before saving the routine");const nt=[];$.forEach((Ct,wt)=>{Ct.name?.trim()||nt.push(`Step ${wt+1}: Name is required`),Ct.type==="command"&&!Ct.command?.trim()&&nt.push(`Step ${wt+1}: Command is required`),Ct.type==="ai-prompt"&&!Ct.prompt?.trim()&&nt.push(`Step ${wt+1}: Prompt is required`),Ct.type==="create-task"&&!Ct.taskDescription?.trim()&&nt.push(`Step ${wt+1}: Task description is required`)}),nt.length>0&&(me.steps=nt.join("; "))}return je<1e3&&(me.timeoutMs="Timeout must be at least 1 second (1000ms)"),lt(me),Object.keys(me).length===0},[d,f,g,w,y,v,pe,r,q,Z,A,ne,se,ve,H,$,G,je]),de=i.useCallback(async me=>{if(me.preventDefault(),!!pt()){ye(!0);try{let nt=e?.scope??pe??(r?"project":"global");nt==="project"&&!r&&(nt="global");const Ct=x$(f,g,y,k,v);let wt,$t;q==="simple"?Z==="command"?wt=A.trim()||void 0:Z==="ai-prompt"?$t=[{id:cf(),type:"ai-prompt",name:d.trim(),prompt:ne.trim(),modelProvider:ve.trim()||void 0,modelId:H.trim()||void 0}]:$t=[{id:cf(),type:"create-task",name:d.trim(),taskTitle:ee.trim()||void 0,taskDescription:se.trim(),taskColumn:J,modelProvider:ve.trim()||void 0,modelId:H.trim()||void 0}]:$t=$;const Vt={name:d.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:Ct,command:wt,steps:$t,timeoutMs:je,executionPolicy:P,catchUpPolicy:E,enabled:L,scope:nt};await n(Vt)}finally{Y.current&&ye(!1)}}},[pt,n,d,m,f,g,y,k,v,q,Z,A,ne,ve,H,ee,se,J,$,je,P,E,L,pe,r,e?.scope,e?.agentId]),Ve="routine-name-error",Ee="routine-cron-error",$e="routine-webhook-error",ut="routine-endpoint-error",ht="routine-command-error",Se="routine-prompt-error",we="routine-task-description-error",Ae="routine-model-error",he="routine-timeout-error",We=i.useCallback(me=>{b(me),me!=="custom"&&x(zx[me])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:de,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":!!ze.name,"aria-describedby":ze.name?Ve:void 0}),ze.name&&t.jsx("small",{id:Ve,className:"field-error",children:ze.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${pe==="global"?" active":""}`,onClick:()=>{Oe("global"),o?.("global")},role:"radio","aria-checked":pe==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:"Global scope",children:[t.jsx(Wl,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${pe==="project"?" active":""}`,onClick:()=>{Oe("project"),o?.("project")},role:"radio","aria-checked":pe==="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(bs,{size:12}),"Project"]})]}),t.jsx("small",{children:!r&&!e?.scope?"No active project. Routines will be created at global scope.":pe==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),ze.scope&&t.jsx("small",{className:"field-error",children:ze.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(og,{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(xg,{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(lg,{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(Qn,{size:14}),"Manual"]})]})]}),f==="cron"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-frequency",children:"Frequency"}),t.jsx("select",{id:"routine-frequency",value:w,onChange:me=>We(me.target.value),children:Object.entries(f$).map(([me,nt])=>t.jsx("option",{value:me,children:nt},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:w!=="custom","aria-invalid":!!ze.cronExpression,"aria-describedby":ze.cronExpression?Ee:void 0}),ze.cronExpression?t.jsx("small",{id:Ee,className:"field-error",children:ze.cronExpression}):t.jsx("small",{children:w==="custom"?t.jsxs(t.Fragment,{children:["min hour day month weekday — ",t.jsx("a",{href:"https://crontab.guru",target:"_blank",rel:"noopener noreferrer",children:"crontab.guru"})]}):`Auto-filled from preset: ${g}`})]}),f==="webhook"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-path",children:"Webhook Path"}),t.jsx("input",{id:"routine-webhook-path",type:"text",placeholder:"/trigger/my-routine",value:y,onChange:me=>S(me.target.value),"aria-invalid":!!ze.webhookPath,"aria-describedby":ze.webhookPath?$e:void 0}),ze.webhookPath?t.jsx("small",{id:$e,className:"field-error",children:ze.webhookPath}):t.jsx("small",{children:"URL path for the webhook endpoint"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-secret",children:"Webhook Secret (optional)"}),t.jsx("input",{id:"routine-webhook-secret",type:"password",placeholder:"Optional — leave empty for unauthenticated webhooks",value:k,onChange:me=>C(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:v,onChange:me=>j(me.target.value),"aria-invalid":!!ze.endpoint,"aria-describedby":ze.endpoint?ut:void 0}),ze.endpoint?t.jsx("small",{id:ut,className:"field-error",children:ze.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${q==="simple"?" active":""}`,onClick:()=>te("simple"),role:"radio","aria-checked":q==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${q==="advanced"?" active":""}`,onClick:()=>te("advanced"),role:"radio","aria-checked":q==="advanced",children:"Multi-Step"})]}),t.jsx("small",{children:q==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),q==="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${Z==="command"?" active":""}`,onClick:()=>K("command"),role:"radio","aria-checked":Z==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${Z==="ai-prompt"?" active":""}`,onClick:()=>K("ai-prompt"),role:"radio","aria-checked":Z==="ai-prompt",children:"AI Prompt"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${Z==="create-task"?" active":""}`,onClick:()=>K("create-task"),role:"radio","aria-checked":Z==="create-task",children:"Create Task"})]})]}),Z==="command"?t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-command",children:"Command"}),t.jsx("input",{id:"routine-command",type:"text",placeholder:"e.g. npx runfusion.ai backup --create",value:A,onChange:me=>I(me.target.value),"aria-invalid":!!ze.command,"aria-describedby":ze.command?ht:void 0}),ze.command?t.jsx("small",{id:ht,className:"field-error",children:ze.command}):t.jsx("small",{children:"Shell command to execute."})]}):Z==="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:ne,onChange:me=>qe(me.target.value),rows:3,"aria-invalid":!!ze.prompt,"aria-describedby":ze.prompt?Se:void 0}),ze.prompt?t.jsx("small",{id:Se,className:"field-error",children:ze.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(ys,{id:"routine-model",label:"Model",models:ce,value:_e,onChange:ct,placeholder:"Use default",disabled:Le}),gt&&t.jsx("small",{className:"field-error",children:gt}),ze.model&&t.jsx("small",{id:Ae,className:"field-error",children:ze.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:ee,onChange:me=>le(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:se,onChange:me=>re(me.target.value),rows:4,"aria-invalid":!!ze.taskDescription,"aria-describedby":ze.taskDescription?we:void 0}),ze.taskDescription?t.jsx("small",{id:we,className:"field-error",children:ze.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:J,onChange:me=>B(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(ys,{id:"routine-task-model",label:"Executor Model",models:ce,value:_e,onChange:ct,placeholder:"Use default",disabled:Le}),gt&&t.jsx("small",{className:"field-error",children:gt}),ze.model&&t.jsx("small",{id:Ae,className:"field-error",children:ze.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(p$,{steps:$,onChange:N,onEditingChange:ge}),ze.steps&&t.jsx("small",{className:"field-error",children:ze.steps}),ze.stepsEditing&&t.jsx("small",{className:"field-error",children:ze.stepsEditing})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-timeout",children:"Timeout (ms)"}),t.jsx("input",{id:"routine-timeout",type:"number",min:1e3,step:1e3,value:je,onChange:me=>ke(Number(me.target.value)),"aria-invalid":!!ze.timeoutMs,"aria-describedby":ze.timeoutMs?he:void 0}),ze.timeoutMs?t.jsx("small",{id:he,className:"field-error",children:ze.timeoutMs}):t.jsx("small",{children:"Maximum execution time in milliseconds."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-execution-policy",children:"Execution Policy"}),t.jsx("select",{id:"routine-execution-policy",value:P,onChange:me=>U(me.target.value),children:y$.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:E,onChange:me=>R(me.target.value),children:w$.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:L,onChange:me=>F(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:Be,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:Be,children:Be?"Saving…":l?"Save Changes":"Create Routine"})]})]})}const k$=3e4;function j$({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);Ai(x,!0,"fusion:automation-modal-size");const w=i.useMemo(()=>({scope:a,projectId:a==="project"?s:void 0}),[a,s]),b=i.useCallback(async()=>{try{const M=await TN(w);l(M),g(O=>{const q={...O};for(const te of M){const Z=q[te.id];if(!Z||!te.lastRunResult)continue;const K=te.lastRunResult;K.success===Z.success&&(K.output||"")===Z.output&&(K.error||"")===(Z.error||"")&&delete q[te.id]}return q})}catch(M){n(Re(M)||"Failed to load routines","error")}},[n,w]);i.useEffect(()=>{b()},[b]),i.useEffect(()=>{const M=setInterval(()=>{b()},k$);return()=>clearInterval(M)},[b]),i.useEffect(()=>{const M=O=>{O.key==="Escape"&&(c!=="list"?(d("list"),m(void 0)):e())};return document.addEventListener("keydown",M),()=>document.removeEventListener("keydown",M)},[e,c]);const y=qi(e),S=i.useCallback(async M=>{try{await $N(M,w),n("Routine created","success"),d("list"),await b()}catch(O){n(Re(O)||"Failed to create routine","error")}},[n,b,w]),k=i.useCallback(M=>{m(M),d("edit")},[]),C=i.useCallback(async M=>{if(u)try{await mm(u.id,M,w),n("Routine updated","success"),d("list"),m(void 0),await b()}catch(O){n(Re(O)||"Failed to update routine","error")}},[u,n,b,w]),v=i.useCallback(async M=>{try{await DN(M.id,w),n(`Deleted "${M.name}"`,"success"),await b()}catch(O){n(Re(O)||"Failed to delete routine","error")}},[n,b,w]),j=i.useCallback(async M=>{f(M.id);try{const{result:O}=await LN(M.id,w);g(q=>({...q,[M.id]:{output:O.output||"",error:O.error,success:O.success}})),O.success?n(`"${M.name}" completed successfully`,"success"):n(`"${M.name}" failed: ${O.error||"Unknown error"}`,"error"),await b()}catch(O){n(Re(O)||"Failed to run routine","error")}finally{f(null)}},[n,b,w]),P=i.useCallback(async M=>{try{await mm(M.id,{enabled:!M.enabled},w),n(`"${M.name}" ${M.enabled?"disabled":"enabled"}`,"success"),await b()}catch(O){n(Re(O)||"Failed to toggle routine","error")}},[n,b,w]),U=i.useCallback(()=>{d("list"),m(void 0)},[]);i.useEffect(()=>{c!=="list"&&g({})},[c]);const E=i.useCallback(M=>{r(M),d("list"),m(void 0),g({})},[]),R=()=>c==="create"?t.jsx(df,{onSubmit:S,onCancel:U,scope:a,projectId:s}):c==="edit"&&u?t.jsx(df,{routine:u,onSubmit:C,onCancel:U,scope:a,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(Qn,{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(bn,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map(M=>t.jsx(d$,{routine:M,onEdit:k,onDelete:v,onRun:j,onToggle:P,running:h===M.id,lastRunOutput:p[M.id]??null},M.id))}),L=()=>R(),F=c==="list"&&o.length>0;return t.jsx("div",{className:"modal-overlay open",...y,children:t.jsxs("div",{ref:x,className:"modal modal-lg automation-modal",role:"dialog","aria-modal":"true","aria-labelledby":"schedules-modal-title",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(Qn,{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(nn,{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:()=>E("global"),"aria-pressed":a==="global",title:"Global (user-level) automations",children:[t.jsx(Wl,{size:14}),"Global"]}),t.jsxs("button",{type:"button",className:`scope-btn${a==="project"?" active":""}`,onClick:()=>E("project"),"aria-pressed":a==="project",title:"Project-scoped automations",children:[t.jsx(bs,{size:14}),"Project"]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(Qn,{size:14}),o.length," automation",o.length===1?"":"s"]})]}),t.jsx("div",{className:"scheduling-toolbar-right",children:F&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>d("create"),"aria-label":"Create new automation",children:[t.jsx(bn,{size:14}),"New Automation"]})})]}),t.jsx("div",{className:"schedule-modal-content",id:"scheduled-tasks-content",children:L()})]})})}const N$=3e4,Xd=new Map,hd=new Map;function uf(e){return e??"default"}function mf(e){const n=Xd.get(e);return n?Date.now()>=n.expiresAt?(Xd.delete(e),null):n:null}function S$(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 C$(e){const n=hd.get(e);if(n)return n;const s=uo().then(({providers:a,ghCli:r})=>{const l={...S$(a,r),ghCli:r,expiresAt:Date.now()+N$};return Xd.set(e,l),l}).finally(()=>{hd.delete(e)});return hd.set(e,s),s}function Fx(e){const n=uf(e),s=mf(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=uf(e),p=mf(f);if(p)return r(p.hasAiProvider),l(p.hasGithub),c(p.ghCli),u(!1),m.current=!0,()=>{h=!0};m.current=!1;async function g(){!m.current&&u(!0);try{const w=await C$(f);if(h)return;r(w.hasAiProvider),l(w.hasGithub),c(w.ghCli)}catch{}finally{h||(m.current=!0,u(!1))}}return g(),()=>{h=!0}},[e]),i.useMemo(()=>({hasAiProvider:a,hasGithub:o,loading:d,hasWarnings:!a||!o}),[a,o,d])}function Ux({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(nn,{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 E$({isOpen:e,onClose:n,projectId:s,tasks:a,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const{confirm:d}=ai(),u=Ys();vi(e);const{keyboardOverlap:m,viewportHeight:h,viewportOffsetTop:f,keyboardOpen:p}=Wi({enabled:u==="mobile"}),g=p?{"--keyboard-overlap":`${m}px`,"--vv-offset-top":`${f}px`,...h!==null?{"--vv-height":`${h}px`}:{}}:{},[x,w]=i.useState(""),[b,y]=i.useState([]),[S,k]=i.useState(""),[C,v]=i.useState(""),[j,P]=i.useState([]),[U,E]=i.useState(!1),[R,L]=i.useState(""),[F,M]=i.useState(""),[O,q]=i.useState(""),[te,Z]=i.useState(""),[K,A]=i.useState(""),[I,$]=i.useState("default"),[N,G]=i.useState(!1),[ge,je]=i.useState([]),[ke,ne]=i.useState(!1),[qe,ee]=i.useState(void 0),[le,se]=i.useState(js),[re,J]=i.useState(void 0),[B,ve]=i.useState(null),[Ne,H]=i.useState([]),[be,ce]=i.useState(!1),[Me,Le]=i.useState(!1),He=i.useRef(null),[gt,Ue]=i.useState(!1),[pe,Oe]=i.useState(""),ze=i.useRef(null),{hasAiProvider:lt,hasGithub:Be,loading:ye}=Fx(s),{nodes:Y}=tc(),_e=i.useCallback(he=>{ne(!0),je(he)},[]),ct=i.useCallback(()=>{ne(!1)},[]),pt=i.useCallback(async()=>{if(Ne.length>0){ce(!0);return}Le(!0);try{const he=await Nr(void 0,s);H(he),ce(!0)}catch(he){const We=Re(he);o(We?`Failed to load agents: ${We}`:"Failed to load agents","error"),ce(!1)}finally{Le(!1)}},[Ne.length,s,o]);i.useEffect(()=>{if(!be)return;const he=We=>{He.current&&!He.current.contains(We.target)&&ce(!1)};return document.addEventListener("mousedown",he),()=>document.removeEventListener("mousedown",he)},[be]),i.useEffect(()=>{if(!gt)return;const he=We=>{ze.current&&!ze.current.contains(We.target)&&(Ue(!1),Oe(""))};return document.addEventListener("mousedown",he),()=>document.removeEventListener("mousedown",he)},[gt]);const de=a.filter(he=>!b.includes(he.id)).sort((he,We)=>{const me=We.createdAt.localeCompare(he.createdAt);if(me!==0)return me;const nt=parseInt(he.id.slice(he.id.lastIndexOf("-")+1),10)||0;return(parseInt(We.id.slice(We.id.lastIndexOf("-")+1),10)||0)-nt}),Ve=pe?de.filter(he=>he.id.toLowerCase().includes(pe.toLowerCase())||he.title&&he.title.toLowerCase().includes(pe.toLowerCase())||he.description&&he.description.toLowerCase().includes(pe.toLowerCase())):de,Ee=(he,We)=>he.length>We?he.slice(0,We)+"…":he;i.useEffect(()=>{const he=x.trim()!==""||b.length>0||j.length>0||R!==""||F!==""||O!==""||te!==""||ge.length>0||B!==null||qe!==void 0||le!==js||re!==void 0||S!==""||C!=="";G(he)},[x,b,j,R,F,O,te,ge,B,qe,le,re,S,C]);const $e=i.useCallback(async()=>{N&&!await d({title:"Discard Changes",message:"You have unsaved changes. Discard them?",danger:!0})||(j.forEach(he=>URL.revokeObjectURL(he.previewUrl)),P([]),w(""),y([]),L(""),M(""),q(""),Z(""),A(""),$("default"),je([]),ne(!1),ve(null),ce(!1),ee(void 0),se(js),J(void 0),k(""),v(""),G(!1),n())},[N,n,j,d]),ut=i.useCallback(async()=>{const he=x.trim();if(!(!he||U)){E(!0);try{const We=R.indexOf("/"),me=F.indexOf("/"),nt=O.indexOf("/"),Ct=await r({title:void 0,description:he,column:"triage",dependencies:b.length?b:void 0,enabledWorkflowSteps:ke?ge.length>0?ge:[]:void 0,...B?{assignedAgentId:B}:{},modelPresetId:I==="preset"&&K||void 0,modelProvider:R&&We!==-1?R.slice(0,We):void 0,modelId:R&&We!==-1?R.slice(We+1):void 0,validatorModelProvider:F&&me!==-1?F.slice(0,me):void 0,validatorModelId:F&&me!==-1?F.slice(me+1):void 0,planningModelProvider:O&&nt!==-1?O.slice(0,nt):void 0,planningModelId:O&&nt!==-1?O.slice(nt+1):void 0,thinkingLevel:te!==""?te:void 0,reviewLevel:qe,priority:le,nodeId:re,branch:S.trim()===""?void 0:S.trim(),baseBranch:C.trim()===""?void 0:C.trim()});if(j.length>0){const wt=[];for(const $t of j)try{await Zl(Ct.id,$t.file,s)}catch{wt.push($t.file.name)}wt.length>0&&o(`Failed to upload: ${wt.join(", ")}`,"error")}j.forEach(wt=>URL.revokeObjectURL(wt.previewUrl)),P([]),w(""),y([]),L(""),M(""),q(""),Z(""),A(""),$("default"),je([]),ne(!1),ve(null),ce(!1),ee(void 0),se(js),J(void 0),k(""),v(""),o(`Created ${Ct.id}`,"success"),n()}catch(We){o(Re(We)||"Failed to create task","error")}finally{E(!1)}}},[x,b,j,R,F,O,te,U,r,o,n,s,I,K,ge,ke,B,qe,le,re,S,C]),ht=i.useCallback(he=>{he.key==="Escape"&&(he.preventDefault(),$e())},[$e]),we=(B?Ne.find(he=>he.id===B):void 0)?.name??B,Ae=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:ze,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>Ue(he=>!he),disabled:U,"data-testid":"dep-trigger",children:b.length>0?`${b.length} selected`:"Add dependencies"}),gt&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:pe,onChange:he=>Oe(he.target.value),onClick:he=>he.stopPropagation()}),Ve.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Ve.map(he=>t.jsxs("div",{className:`dep-dropdown-item${b.includes(he.id)?" selected":""}`,onClick:()=>{y(b.includes(he.id)?b.filter(We=>We!==he.id):[...b,he.id]),Ue(!1),Oe("")},onMouseDown:We=>We.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:he.id}),t.jsx("span",{className:"dep-dropdown-title",children:Ee(he.title||he.description||he.id,30)})]},he.id))]})]}),b.length>0&&t.jsx("div",{className:"selected-deps",children:b.map(he=>t.jsxs("span",{className:"dep-chip",children:[he,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>y(b.filter(We=>We!==he)),disabled:U,children:"×"})]},he))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:He,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{be?ce(!1):pt()},disabled:U,"data-testid":"new-task-agent-button",children:[t.jsx(Tn,{size:12,style:{verticalAlign:"middle"}}),we?` ${we}`:" Assign agent"]}),be&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:he=>he.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),Me&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!Me&&Ne.map(he=>t.jsxs("div",{className:`dep-dropdown-item${B===he.id?" selected":""}`,onMouseDown:We=>We.preventDefault(),onClick:()=>{ve(he.id===B?null:he.id),ce(!1)},"data-testid":`agent-option-${he.id}`,children:[t.jsx(Tn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:he.role}),t.jsx("span",{className:"dep-dropdown-title",children:he.name})]},he.id)),!Me&&Ne.length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),B&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:he=>he.preventDefault(),onClick:()=>{ve(null),ce(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:$e,onKeyDown:ht,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:he=>he.stopPropagation(),style:g,children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:$e,disabled:U,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!ye&&t.jsx(Ux,{hasAiProvider:lt,hasGithub:Be}),t.jsx(wx,{mode:"create",description:x,onDescriptionChange:w,dependencies:b,onDependenciesChange:y,executorModel:R,onExecutorModelChange:L,validatorModel:F,onValidatorModelChange:M,presetMode:I,onPresetModeChange:$,selectedPresetId:K,onSelectedPresetIdChange:A,selectedWorkflowSteps:ge,onWorkflowStepsChange:_e,onDefaultOnApplied:ct,pendingImages:j,onImagesChange:P,tasks:a,projectId:s,disabled:U,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:$e,planningModel:O,onPlanningModelChange:q,thinkingLevel:te,onThinkingLevelChange:Z,reviewLevel:qe,onReviewLevelChange:ee,priority:le,onPriorityChange:se,branch:S,onBranchChange:k,baseBranch:C,onBaseBranchChange:v,nodeId:re,onNodeIdChange:J,nodeOptions:Y,renderBelowPrimary:Ae,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:$e,disabled:U,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:ut,disabled:!x.trim()||U,children:U?"Creating...":"Create Task"})]})]})}):null}function ui(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 hf(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function _$(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function M$(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function A$(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function P$(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 ul(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function R$(e){if(!e)return"Not yet";const n=new Date(e);return Number.isNaN(n.getTime())?"Not yet":n.toLocaleString()}function I$({isOpen:e,onClose:n,projectId:s}){const[a,r]=i.useState(null),[o,l]=i.useState(!1),[c,d]=i.useState(null),[u,m]=i.useState(!0),[h,f]=i.useState(90),[p,g]=i.useState(!1),[x,w]=i.useState(!1),[b,y]=i.useState(null),[S,k]=i.useState(null),[C,v]=i.useState(null),j=i.useCallback(async ee=>{l(!0);try{const le=await xS(s);r(le),d(null),v(Date.now()),ee?.preserveKillResult||y(null)}catch(le){d(le instanceof Error?le.message:"Failed to load system stats")}finally{l(!1)}},[s]);i.useEffect(()=>{if(!e)return;j();const ee=window.setInterval(()=>{j()},5e3);return()=>{window.clearInterval(ee)}},[e,j]),i.useEffect(()=>{if(!e)return;(async()=>{try{const le=await Pa();m(le.vitestAutoKillEnabled??!0),f(le.vitestKillThresholdPct??90),k(null)}catch(le){k(le instanceof Error?le.message:"Failed to load vitest settings")}})()},[e]),i.useEffect(()=>{if(!e)return;const ee=le=>{le.key==="Escape"&&n()};return document.addEventListener("keydown",ee),()=>document.removeEventListener("keydown",ee)},[e,n]);const P=i.useMemo(()=>{if(!a)return[];const ee=a.systemStats,le=ul(_$(ee.heapUsed,ee.heapLimit)),se=ul(M$(ee.rss,ee.systemTotalMem));return[{label:"RSS",value:ui(ee.rss),detail:hf(ee.rss,ee.systemTotalMem),className:se},{label:"Heap Used",value:ui(ee.heapUsed),detail:`of ${ui(ee.heapTotal)}`,className:le},{label:"Heap Limit",value:ui(ee.heapLimit),detail:"V8 limit"},{label:"External",value:ui(ee.external)},{label:"Array Buffers",value:ui(ee.arrayBuffers)}]},[a]),U=i.useCallback(async ee=>{m(ee);try{await kn({vitestAutoKillEnabled:ee}),k(null)}catch(le){k(le instanceof Error?le.message:"Failed to save vitest settings")}},[]),E=i.useCallback(async ee=>{const le=Math.min(99,Math.max(50,Number.isFinite(ee)?Math.round(ee):90));f(le);try{await kn({vitestKillThresholdPct:le}),k(null)}catch(se){k(se instanceof Error?se.message:"Failed to save vitest settings")}},[]),R=i.useCallback(async()=>{if(!p){if(!x){w(!0);return}g(!0);try{const ee=await vS(s);y(ee),w(!1),await j({preserveKillResult:!0})}catch(ee){d(ee instanceof Error?ee.message:"Failed to kill vitest processes")}finally{g(!1)}}},[x,p,j,s]);if(!e)return null;const L=a?.systemStats,F=o&&!!a,M=C?`Updated ${new Date(C).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`:"Waiting for first update",O=a?.taskStats,q=L?L.systemTotalMem-L.systemFreeMem:0,te=L?A$(q,L.systemTotalMem):"normal",Z=L?ul(te):"",K=L&&Number.isFinite(L.systemTotalMem)&&L.systemTotalMem>0?Math.max(0,Math.min(100,q/L.systemTotalMem*100)):0,A=L?`System memory used: ${K.toFixed(1)}% (${ui(q)} of ${ui(L.systemTotalMem)})`:"System memory usage unavailable",I=a?.vitestProcessCount,$=P$(L?.cpuPercent??null,L?.cpuCount??0),N=ul($),G=L?.cpuPercent??null,ge=G===null?0:Math.max(0,Math.min(100,G)),je=G===null?"Sampling…":`${G.toFixed(1)}%`,ke=G===null?"App CPU usage unavailable: waiting for another sample":`App CPU usage: ${G.toFixed(1)}%`,ne=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":"",qe=R$(a?.vitestLastAutoKillAt);return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"system-stats-modal-title",onClick:ee=>{ee.target===ee.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(dr,{}),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:M})]}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void j(),title:"Refresh","aria-label":"Refresh system stats",children:t.jsx(rs,{size:16,className:F?"system-stats-modal__refresh--spinning":void 0})}),t.jsx("button",{type:"button",className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(nn,{})})]})]}),o&&!a&&t.jsx("div",{className:"system-stats-modal__state",children:"Loading system stats…"}),c&&!a&&t.jsx("div",{className:"system-stats-modal__state system-stats-modal__state--error",role:"alert",children:c}),a&&t.jsxs("div",{className:"system-stats-modal__content",children:[t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Process stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Process"}),t.jsx("dl",{className:"system-stats-modal__grid",children:P.map(ee=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:ee.label}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${ee.className}`.trim(),children:ee.value}),ee.detail?t.jsx("span",{className:"system-stats-modal__detail",children:ee.detail}):null]})]},ee.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 ${N}`.trim(),children:je}),t.jsx("span",{className:"system-stats-modal__detail",children:G===null?"First sample pending":"process usage"})]}),t.jsx("div",{className:"system-stats-modal__memory-progress-wrapper",children:t.jsx("div",{className:`system-stats-modal__memory-progress-track system-stats-modal__memory-progress-track--${$}`,role:"progressbar","aria-valuenow":Math.round(ge),"aria-valuemin":0,"aria-valuemax":100,"aria-label":ke,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${$}`,style:{width:`${ge}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Load Avg"}),t.jsx("dd",{children:L?.loadAvg.map(ee=>ee.toFixed(2)).join(" ")??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Cores"}),t.jsx("dd",{children:L?.cpuCount??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Platform"}),t.jsx("dd",{children:L?.platform??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Node"}),t.jsx("dd",{children:L?.nodeVersion??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"PID"}),t.jsx("dd",{children:L?.pid??"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"System memory stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"System"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row system-stats-modal__row--memory-used",children:[t.jsx("dt",{children:"Memory Used"}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${Z}`.trim(),children:L?ui(q):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:L?`${hf(q,L.systemTotalMem)} of ${ui(L.systemTotalMem)}`:""})]}),t.jsx("div",{className:"system-stats-modal__memory-progress-wrapper",children:t.jsx("div",{className:`system-stats-modal__memory-progress-track system-stats-modal__memory-progress-track--${te}`,role:"progressbar","aria-valuenow":Math.round(K),"aria-valuemin":0,"aria-valuemax":100,"aria-label":A,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${te}`,style:{width:`${K}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Free"}),t.jsx("dd",{children:L?ui(L.systemFreeMem):"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Task stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Tasks"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Total"}),t.jsx("dd",{children:O?.total??0})]}),Object.entries(O?.byColumn??{}).map(([ee,le])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:ee}),t.jsx("dd",{children:le})]},ee))]})]}),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:O?.agents.idle??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"active"}),t.jsx("dd",{children:O?.agents.active??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"running"}),t.jsx("dd",{children:O?.agents.running??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"error"}),t.jsx("dd",{children:O?.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(qw,{}),t.jsx("span",{children:"Vitest Controls"})]}),t.jsx("dl",{className:"system-stats-modal__grid system-stats-modal__vitest-controls",children:t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Vitest Processes"}),t.jsx("dd",{children:I??"—"})]})}),t.jsxs("div",{className:"system-stats-modal__vitest-controls",children:[t.jsx("div",{className:"system-stats-modal__kill-row",children:t.jsxs("button",{type:"button",className:"btn btn-danger",onClick:()=>void R(),disabled:p||I===0,children:[t.jsx(Gw,{}),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:ee=>{U(ee.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:ee=>{const le=Number.parseInt(ee.target.value,10);E(Number.isNaN(le)?90:le)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:h,"aria-label":"Kill threshold (%)",onChange:ee=>{const le=Number.parseInt(ee.target.value,10);E(Number.isNaN(le)?90:le)},onBlur:()=>{E(h)}})]})]}),b&&t.jsxs("p",{className:ne,children:["Killed ",b.killed," processes"]}),t.jsxs("p",{className:"system-stats-modal__last-kill",children:["Last auto-kill: ",qe]}),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 T$=5e3;function $$(e={}){const{projectId:n,type:s,limit:a=50,autoRefresh:r=!0,useCentralFeed:o=!1}=e,[l,c]=i.useState([]),[d,u]=i.useState(!1),[m,h]=i.useState(null),[f,p]=i.useState(!1),g=i.useRef(null),x=i.useRef(void 0),w=i.useCallback(async()=>{try{u(!0),h(null);let S;o?S=await ym({limit:a,projectId:n,type:s}):S=(await hm({limit:a,type:s,projectId:n})).map(C=>({...C,projectId:n??"",projectName:""})),c(S),p(S.length===a),S.length>0&&(x.current=S[S.length-1].timestamp)}catch(S){h(S instanceof Error?S.message:"Failed to load activity log")}finally{u(!1)}},[a,n,s,o]),b=i.useCallback(async()=>{if(x.current)try{u(!0);let S;o?S=await ym({limit:a,projectId:n,type:s,since:x.current}):S=(await hm({limit:a,type:s,since:x.current,projectId:n})).map(C=>({...C,projectId:n??"",projectName:""})),c(k=>[...k,...S]),p(S.length===a),S.length>0&&(x.current=S[S.length-1].timestamp)}catch(S){h(S instanceof Error?S.message:"Failed to load more entries")}finally{u(!1)}},[a,n,s,o]),y=i.useCallback(()=>{c([]),p(!1),x.current=void 0},[]);return i.useEffect(()=>{w()},[w]),i.useEffect(()=>{if(r)return g.current=setInterval(()=>{w()},T$),()=>{g.current&&(clearInterval(g.current),g.current=null)}},[r,w]),{entries:l,loading:d,error:m,refresh:w,clear:y,hasMore:f,loadMore:b}}const pd={"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"},D$={"task:created":t.jsx(bn,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(yo,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(rs,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(nn,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx($n,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(wo,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(to,{size:14,className:"activity-icon settings"})};function L$(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 O$({isOpen:e,onClose:n,tasks:s,onOpenTaskDetail:a,projectId:r,projects:o=[],onProjectFilterChange:l,currentProject:c}){const[d,u]=i.useState("all"),[m,h]=i.useState(r||"all"),[f,p]=i.useState(!1);i.useEffect(()=>{h(r||"all")},[r]);const g=d==="all"?void 0:d,x=m==="all"?void 0:m,w=!c&&o.length>0,{entries:b,loading:y,error:S,refresh:k,hasMore:C}=$$({projectId:x,type:g,limit:100,autoRefresh:e,useCentralFeed:w}),v=b.map(R=>({id:R.id,timestamp:R.timestamp,type:R.type,taskId:R.taskId,taskTitle:R.taskTitle,details:R.details,metadata:R.metadata,projectId:R.projectId,projectName:R.projectName})),j=async()=>{try{await ON(),k(),p(!1)}catch{p(!1)}},P=R=>{a&&a(R)},U=R=>{h(R),l?.(R==="all"?void 0:R)};i.useEffect(()=>{if(!e)return;const R=L=>{L.key==="Escape"&&(f?p(!1):n())};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[e,n,f]);const E=d!=="all"||m!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:R=>{R.target===R.currentTarget&&n()},role:"dialog","aria-modal":"true","data-testid":"activity-log-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg activity-log-modal","data-testid":"activity-log-modal",children:[t.jsxs("div",{className:"modal-header activity-log-header",children:[t.jsxs("div",{className:"activity-log-title",children:[t.jsx(lo,{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(bs,{size:14}),t.jsxs("select",{value:m,onChange:R=>U(R.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map(R=>t.jsx("option",{value:R.id,children:R.name},R.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(jl,{size:14}),t.jsxs("select",{value:d,onChange:R=>u(R.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(pd).map(([R,L])=>t.jsx("option",{value:R,children:L},R))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>k(),title:"Refresh","data-testid":"activity-refresh",children:y?t.jsx(xt,{size:14,className:"spin"}):t.jsx(rs,{size:14})}),v.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:t.jsx(vn,{size:14})})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",title:"Close","data-testid":"activity-close",children:"×"})]}),E&&t.jsxs("div",{className:"activity-log-active-filters",children:[t.jsx("span",{className:"activity-log-filter-label",children:"Active filters:"}),m!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Project: ",o.find(R=>R.id===m)?.name||m]}),d!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",pd[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(Ps,{size:16}),t.jsx("span",{children:S})]}),v.length===0&&!y&&!S&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(lo,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:E?"No activity matches the current filters":"No activity recorded yet"}),E&&t.jsx("button",{className:"btn btn-secondary",onClick:()=>{u("all"),h("all"),l?.(void 0)},children:"Clear Filters"})]}),t.jsx("div",{className:"activity-log-list",children:v.map(R=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:D$[R.type]}),t.jsxs("div",{className:"activity-log-entry-content",children:[t.jsxs("div",{className:"activity-log-entry-header",children:[t.jsx("span",{className:"activity-log-entry-type",children:pd[R.type]}),t.jsx("span",{className:"activity-log-entry-time",children:L$(R.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[R.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>P(R.taskId),"data-testid":"activity-task-link",children:R.taskId}),R.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:R.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:R.details})]}),R.metadata&&Object.keys(R.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof R.metadata.from=="string"&&typeof R.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[R.metadata.from," → ",R.metadata.to]}),typeof R.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${R.metadata.merged?"success":"error"}`,children:R.metadata.merged?"Merged":"Not merged"})]})]})]},R.id))}),C&&!y&&t.jsx("button",{className:"activity-log-load-more",onClick:k,"data-testid":"activity-load-more",children:"Load More"}),y&&v.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(xt,{size:20,className:"spin"})})]}),f&&t.jsx("div",{className:"activity-log-confirm-overlay",children:t.jsxs("div",{className:"activity-log-confirm-dialog",children:[t.jsx("h3",{children:"Clear Activity Log?"}),t.jsx("p",{children:"This will permanently delete all activity log entries. This action cannot be undone."}),t.jsxs("div",{className:"activity-log-confirm-actions",children:[t.jsx("button",{className:"activity-log-confirm-cancel",onClick:()=>p(!1),children:"Cancel"}),t.jsx("button",{className:"activity-log-confirm-clear",onClick:j,children:"Clear Log"})]})]})})]})}):null}const Hr=[{id:"status",label:"Status",icon:gg},{id:"changes",label:"Changes",icon:Sd},{id:"commits",label:"Commits",icon:ko},{id:"branches",label:"Branches",icon:Us},{id:"worktrees",label:"Worktrees",icon:Fy},{id:"stashes",label:"Stashes",icon:xo},{id:"remotes",label:"Remotes",icon:hg}];function pf({status:e}){switch(e){case"added":case"untracked":return t.jsx(vy,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(ug,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(gy,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(ia,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(wy,{size:14,className:"gm-file-icon"})}}function ff({status:e}){const n=e==="untracked"?"U":e==="added"?"A":e==="modified"?"M":e==="deleted"?"D":e==="renamed"?"R":e==="copied"?"C":"?";return t.jsx("span",{className:`gm-file-badge gm-file-badge-${e}`,children:n})}function z$(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 br(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 F$({isOpen:e,onClose:n,tasks:s,addToast:a,projectId:r}){const o=ai(),l=Ys();vi(e);const{keyboardOverlap:c,viewportHeight:d,viewportOffsetTop:u,keyboardOpen:m}=Wi({enabled:l==="mobile"}),h=m?{"--keyboard-overlap":`${c}px`,"--vv-offset-top":`${u}px`,...d!==null?{"--vv-height":`${d}px`}:{}}:{},f=i.useCallback(()=>{if(l==="mobile"){const Te=document.activeElement;Te instanceof HTMLElement&&Te.blur(),window.scrollTo(0,0),requestAnimationFrame(()=>{window.scrollTo(0,0)})}n()},[n,l]),[p,g]=i.useState("status"),[x,w]=i.useState(!1),[b,y]=i.useState(null),S=i.useRef(null);Ai(S,e,"fusion:git-modal-size");const k=qi(f),C=z$(a),[v,j]=i.useState(null),[P,U]=i.useState([]),[E,R]=i.useState(new Set),[L,F]=i.useState(""),[M,O]=i.useState(!1),[q,te]=i.useState(null),[Z,K]=i.useState(!1),[A,I]=i.useState(null),[$,N]=i.useState(null),G=i.useRef(0),[ge,je]=i.useState([]),[ke,ne]=i.useState(null),[qe,ee]=i.useState(null),[le,se]=i.useState(!1),[re,J]=i.useState(20),[B,ve]=i.useState(""),[Ne,H]=i.useState([]),[be,ce]=i.useState(""),[Me,Le]=i.useState(""),[He,gt]=i.useState(""),[Ue,pe]=i.useState(null),[Oe,ze]=i.useState([]),[lt,Be]=i.useState(!1),[ye,Y]=i.useState(null),[_e,ct]=i.useState(null),[pt,de]=i.useState(!1),[Ve,Ee]=i.useState([]),[$e,ut]=i.useState([]),[ht,Se]=i.useState(""),[we,Ae]=i.useState(null),[he,We]=i.useState(null),[me,nt]=i.useState(null),[Ct,wt]=i.useState(!1),[$t,Vt]=i.useState(null),Mt=i.useRef(0),[Dt,Qt]=i.useState(null),[Kt,Bt]=i.useState(null),on=i.useCallback(async()=>{if(e){w(!0),y(null);try{switch(p){case"status":{const Te=await di(r);j(Te);break}case"changes":{const[Te,Ye]=await Promise.all([di(r),Ga(r)]);j(Te),U(Ye),R(new Set),N(null),te(null),I(null);break}case"commits":{const Te=await Uj(re,r);je(Te);break}case"branches":{const[Te,Ye]=await Promise.all([Ar(r),di(r)]);H(Te),j(Ye);break}case"worktrees":{const Te=await Vj(r);Ee(Te);break}case"stashes":{const Te=await Oo(r);ut(Te),We(null),nt(null),Vt(null),Mt.current+=1;break}case"remotes":{const Te=await di(r);j(Te);break}}}catch(Te){y(Re(Te)||"Failed to fetch git data"),a(Re(Te)||"Failed to fetch git data","error")}finally{w(!1)}}},[p,e,re,a,r]);i.useEffect(()=>{e&&on()},[on,e]),i.useEffect(()=>{if(!e)return;const Te=Ye=>{if(Ye.key==="Escape"){f();return}if((Ye.key==="ArrowUp"||Ye.key==="ArrowDown")&&Ye.altKey){Ye.preventDefault();const Nt=Hr.findIndex(Ut=>Ut.id===p);Ye.key==="ArrowUp"&&Nt>0?g(Hr[Nt-1].id):Ye.key==="ArrowDown"&&Nt<Hr.length-1&&g(Hr[Nt+1].id)}};return document.addEventListener("keydown",Te),()=>document.removeEventListener("keydown",Te)},[e,f,p]);const fn=i.useCallback(async Te=>{try{await om(Te,r),a(`Staged ${Te.length} file(s)`,"success");const Ye=await Ga(r);U(Ye),R(new Set),N(null),te(null),I(null)}catch(Ye){a(Re(Ye)||"Failed to stage files","error")}},[a,r]),Jt=i.useCallback(async Te=>{try{await nN(Te,r),a(`Unstaged ${Te.length} file(s)`,"success");const Ye=await Ga(r);U(Ye),R(new Set),N(null),te(null),I(null)}catch(Ye){a(Re(Ye)||"Failed to unstage files","error")}},[a,r]),an=i.useCallback(async Te=>{if(await o.confirm({title:"Discard Changes",message:`Discard changes to ${Te.length} file(s)? This cannot be undone.`,danger:!0}))try{await sN(Te,r),a(`Discarded changes to ${Te.length} file(s)`,"success");const[Nt,Ut]=await Promise.all([Ga(r),di(r)]);U(Nt),j(Ut),R(new Set),N(null),te(null),I(null)}catch(Nt){a(Re(Nt)||"Failed to discard changes","error")}},[a,r,o]),zt=i.useCallback(async Te=>{if(Te.preventDefault(),!!L.trim()){O(!0);try{const Ye=await lm(L.trim(),r);a(`Committed: ${Ye.hash}`,"success"),F("");const[Nt,Ut]=await Promise.all([Ga(r),di(r)]);U(Nt),j(Ut),N(null),te(null),I(null)}catch(Ye){a(Re(Ye)||"Failed to commit","error")}finally{O(!1)}}},[L,a,r]),en=i.useCallback(async()=>{if(L.trim()){O(!0);try{const Te=P.filter(tn=>!tn.staged).map(tn=>tn.file);Te.length>0&&await om(Te,r);const Ye=await lm(L.trim(),r);a(`Committed: ${Ye.hash}`,"success"),F("");const[Nt,Ut]=await Promise.all([Ga(r),di(r)]);U(Nt),j(Ut),N(null),te(null),I(null)}catch(Te){a(Re(Te)||"Failed to commit","error")}finally{O(!1)}}},[L,P,a,r]),Zt=i.useCallback(async(Te,Ye)=>{N({file:Te,staged:Ye}),K(!0),I(null);const Nt=G.current+1;G.current=Nt;try{const Ut=await tN(Te,Ye,r);if(G.current!==Nt)return;te(Ut)}catch(Ut){if(G.current!==Nt)return;const tn=Re(Ut)||"Failed to load file diff";te(null),I(tn),a(tn,"error")}finally{G.current===Nt&&K(!1)}},[a,r]),dn=i.useCallback(Te=>{R(Ye=>{const Nt=new Set(Ye);return Nt.has(Te)?Nt.delete(Te):Nt.add(Te),Nt})},[]),xe=i.useCallback(async Te=>{if(ke===Te){ne(null),ee(null);return}ne(Te),se(!0);try{const Ye=await El(Te,r);ee(Ye)}catch(Ye){a(Re(Ye)||"Failed to load diff","error"),ee(null)}finally{se(!1)}},[ke,a,r]),Fe=i.useCallback(()=>{J(Te=>Math.min(Te+20,100))},[]),Ke=i.useMemo(()=>{if(!B.trim())return ge;const Te=B.toLowerCase();return ge.filter(Ye=>Ye.message.toLowerCase().includes(Te)||Ye.author.toLowerCase().includes(Te)||Ye.shortHash.toLowerCase().includes(Te))},[ge,B]),et=i.useCallback(async Te=>{if(Te.preventDefault(),!!be.trim()){w(!0);try{await Wj(be.trim(),Me.trim()||void 0,r),a(`Created branch ${be}`,"success"),ce(""),Le("");const Ye=await Ar(r);H(Ye)}catch(Ye){a(Re(Ye)||"Failed to create branch","error")}finally{w(!1)}}},[be,Me,a,r]),Qe=i.useCallback(async Te=>{w(!0);try{await Kj(Te,r),a(`Switched to ${Te}`,"success");const[Ye,Nt]=await Promise.all([di(r),Ar(r)]);j(Ye),H(Nt)}catch(Ye){a(Re(Ye)||"Failed to checkout branch","error")}finally{w(!1)}},[a,r]),It=i.useCallback(async Te=>{if(await o.confirm({title:"Delete Branch",message:`Delete branch "${Te}"?`,danger:!0})){w(!0);try{await rm(Te,void 0,r),a(`Deleted branch ${Te}`,"success");const Nt=await Ar(r);H(Nt)}catch(Nt){if(Re(Nt).includes("not fully merged")){if(await o.confirm({title:"Force Delete Branch",message:"Branch has unmerged commits. Force delete?",danger:!0}))try{await rm(Te,!0,r),a(`Force deleted branch ${Te}`,"success");const tn=await Ar(r);H(tn)}catch(tn){a(Re(tn)||"Failed to delete branch","error")}}else a(Re(Nt)||"Failed to delete branch","error")}finally{w(!1)}}},[a,r,o]),St=i.useMemo(()=>{if(!He.trim())return Ne;const Te=He.toLowerCase();return Ne.filter(Ye=>Ye.name.toLowerCase().includes(Te))},[Ne,He]),Ht=i.useCallback(async Te=>{if(Ue===Te){pe(null),ze([]),Y(null),ct(null);return}pe(Te),ze([]),Y(null),ct(null),Be(!0);try{const Ye=await qj(Te,10,r);ze(Ye)}catch{ze([])}finally{Be(!1)}},[Ue,r]),jt=i.useCallback(async Te=>{if(ye===Te){Y(null),ct(null);return}Y(Te),ct(null),de(!0);try{const Ye=await El(Te,r);ct(Ye)}catch{ct(null)}finally{de(!1)}},[ye,r]),ae=i.useCallback(()=>{pe(null),ze([]),Y(null),ct(null)},[]),De=i.useCallback(()=>{Mt.current+=1,We(null),nt(null),Vt(null),wt(!1)},[]),At=i.useCallback(async Te=>{Te.preventDefault(),Ae("create"),De();try{await Qj(ht.trim()||void 0,r),a("Changes stashed","success"),Se("");const Ye=await Oo(r);ut(Ye)}catch(Ye){a(Re(Ye)||"Failed to stash changes","error")}finally{Ae(null)}},[ht,a,r,De]),Lt=i.useCallback(async(Te,Ye=!1)=>{Ae(`apply-${Te}`),De();try{await Xj(Te,Ye,r),a(Ye?"Stash popped":"Stash applied","success");const Nt=await Oo(r);ut(Nt)}catch(Nt){a(Re(Nt)||"Failed to apply stash","error")}finally{Ae(null)}},[a,r,De]),Ft=i.useCallback(async Te=>{if(await o.confirm({title:"Drop Stash",message:`Drop stash@{${Te}}? This cannot be undone.`,danger:!0})){Ae(`drop-${Te}`),De();try{await Zj(Te,r),a("Stash dropped","success");const Nt=await Oo(r);ut(Nt)}catch(Nt){a(Re(Nt)||"Failed to drop stash","error")}finally{Ae(null)}}},[a,r,o,De]),Pe=i.useCallback(async Te=>{if(he===Te){De();return}const Ye=Mt.current+1;Mt.current=Ye,We(Te),nt(null),Vt(null),wt(!0);try{const Nt=await eN(Te,r);if(Mt.current!==Ye)return;nt(Nt)}catch(Nt){if(Mt.current!==Ye)return;nt(null),Vt(Re(Nt)||"Failed to load stash diff")}finally{Mt.current===Ye&&wt(!1)}},[he,r,De]),dt=i.useCallback(async()=>{Qt("fetch");try{const Te=await Gj(void 0,r);Bt(Te),a(Te.message||"Fetch completed",Te.fetched?"success":"info");const Ye=await di(r);j(Ye)}catch(Te){a(Re(Te)||"Fetch failed","error")}finally{Qt(null)}},[a,r]),bt=i.useCallback(async Te=>{Qt("pull");try{const Ye=await Jj(Te,r);if(Bt(Ye),Ye.conflict)a("Merge conflict detected. Resolve manually.","error");else{const Ut=Te?.rebase?"Pull --rebase completed":"Pull completed";a(Ye.message||Ut,"success")}const Nt=await di(r);j(Nt)}catch(Ye){a(Re(Ye)||"Pull failed","error")}finally{Qt(null)}},[a,r]),_t=i.useCallback(async()=>{Qt("push");try{const Te=await Yj(r);Bt(Te),a(Te.message||"Push completed","success");const Ye=await di(r);j(Ye)}catch(Te){a(Re(Te)||"Push failed","error")}finally{Qt(null)}},[a,r]),Yt=i.useMemo(()=>P.filter(Te=>Te.staged),[P]),Xt=i.useMemo(()=>P.filter(Te=>!Te.staged),[P]);return e?t.jsx("div",{className:"modal-overlay open git-manager-modal-overlay",...k,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal gm-modal",ref:S,style:h,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h3",{children:[t.jsx(Cd,{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:on,disabled:x,title:"Refresh",children:t.jsx(rs,{size:14,className:x?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:f,"aria-label":"Close",children:t.jsx(nn,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:Hr.map(Te=>{const Ye=Te.icon;return t.jsxs("button",{role:"tab","aria-selected":p===Te.id,className:`gm-nav-item${p===Te.id?" active":""}`,onClick:()=>g(Te.id),children:[t.jsx(Ye,{size:16}),t.jsx("span",{className:"gm-nav-label",children:Te.label})]},Te.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[x&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(xt,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),b&&!x&&t.jsxs("div",{className:"gm-error",children:[t.jsx(Ps,{size:18}),t.jsx("span",{children:b}),t.jsx("button",{className:"btn btn-sm",onClick:on,children:"Retry"})]}),p==="status"&&!x&&v&&t.jsx(U$,{status:v,copyToClipboard:C}),p==="changes"&&!x&&t.jsx(B$,{status:v,stagedFiles:Yt,unstagedFiles:Xt,selectedFiles:E,toggleFileSelection:dn,onStageFiles:fn,onUnstageFiles:Jt,onDiscardChanges:an,onSelectDiffFile:Zt,selectedDiffTarget:$,changeDiff:q,loadingChangeDiff:Z,changeDiffError:A,commitMessage:L,setCommitMessage:F,onCommit:zt,onStageAllAndCommit:en,committing:M}),p==="commits"&&!x&&t.jsx(H$,{commits:Ke,commitSearch:B,setCommitSearch:ve,selectedCommit:ke,commitDiff:qe,loadingDiff:le,onCommitClick:xe,onLoadMore:Fe,canLoadMore:ge.length>=re&&re<100,copyToClipboard:C}),p==="branches"&&!x&&t.jsx(q$,{branches:St,branchSearch:He,setBranchSearch:gt,newBranchName:be,setNewBranchName:ce,branchBase:Me,setBranchBase:Le,onCreateBranch:et,onCheckoutBranch:Qe,onDeleteBranch:It,loading:x,allBranches:Ne,selectedBranch:Ue,branchCommits:Oe,loadingBranchCommits:lt,expandedBranchCommit:ye,branchCommitDiff:_e,loadingBranchCommitDiff:pt,onSelectBranch:Ht,onBranchCommitClick:jt,onCloseBranchDetails:ae}),p==="worktrees"&&!x&&t.jsx(V$,{worktrees:Ve}),p==="stashes"&&!x&&t.jsx(W$,{stashes:$e,stashMessage:ht,setStashMessage:Se,onCreateStash:At,onApplyStash:Lt,onDropStash:Ft,onToggleStashDiff:Pe,stashLoading:we,expandedStashIndex:he,stashDiff:me,loadingStashDiff:Ct,stashDiffError:$t}),p==="remotes"&&!x&&t.jsx(K$,{status:v,remoteLoading:Dt,lastRemoteResult:Kt,onFetch:dt,onPull:bt,onPush:_t,addToast:a,projectId:r,copyToClipboard:C})]})]})]})}):null}function U$({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(Us,{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(sa,{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(Ps,{size:12}),"Modified"]}):t.jsxs(t.Fragment,{children:[t.jsx($n,{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(ka,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx(vo,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx($n,{size:12}),"Up to date"]})]})]})]})]})}function B$({status:e,stagedFiles:n,unstagedFiles:s,selectedFiles:a,toggleFileSelection:r,onStageFiles:o,onUnstageFiles:l,onDiscardChanges:c,onSelectDiffFile:d,selectedDiffTarget:u,changeDiff:m,loadingChangeDiff:h,changeDiffError:f,commitMessage:p,setCommitMessage:g,onCommit:x,onStageAllAndCommit:w,committing:b}){const y=s.filter(k=>a.has(`unstaged:${k.file}`)),S=n.filter(k=>a.has(`staged:${k.file}`));return t.jsxs("div",{className:"gm-panel","data-testid":"changes-panel",children:[e&&t.jsxs("div",{className:"gm-changes-header",children:[t.jsxs("span",{className:"gm-branch-indicator",children:[t.jsx(Us,{size:14}),e.branch]}),e.isDirty&&t.jsx("span",{className:"gm-dirty-badge",children:"Modified"})]}),t.jsxs("div",{className:"gm-changes-split",children:[t.jsxs("div",{className:"gm-changes-lists",children:[t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Unstaged Changes (",s.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[y.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(y.map(k=>k.file)),title:"Stage selected",children:[t.jsx(bn,{size:12})," Stage (",y.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(y.map(k=>k.file)),title:"Discard selected",children:t.jsx(wo,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(k=>k.file)),title:"Stage all",children:"Stage All"})]})]}),t.jsx("div",{className:"gm-file-list gm-file-list-unstaged","data-testid":"gm-file-list-unstaged",children:s.length===0?t.jsx("div",{className:"gm-empty",children:"No unstaged changes"}):s.map(k=>{const C=u?.file===k.file&&u.staged===!1;return t.jsxs("div",{className:`gm-file-item${C?" active":""}`,onClick:()=>d(k.file,!1),role:"button",tabIndex:0,onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),d(k.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:v=>v.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`unstaged:${k.file}`),onChange:()=>r(`unstaged:${k.file}`)})}),t.jsx(pf,{status:k.status}),t.jsx("span",{className:"gm-file-name",title:k.file,children:t.jsx("bdo",{dir:"ltr",children:k.file})}),t.jsx(ff,{status:k.status}),t.jsx("button",{className:"gm-icon-btn",onClick:v=>{v.stopPropagation(),o([k.file])},title:"Stage file",children:t.jsx(bn,{size:12})})]},`unstaged:${k.file}`)})})]}),t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Staged Changes (",n.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[S.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(S.map(k=>k.file)),title:"Unstage selected",children:["Unstage (",S.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(k=>k.file)),title:"Unstage all",children:"Unstage All"})]})]}),t.jsx("div",{className:"gm-file-list gm-file-list-staged","data-testid":"gm-file-list-staged",children:n.length===0?t.jsx("div",{className:"gm-empty",children:"No staged changes"}):n.map(k=>{const C=u?.file===k.file&&u.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${C?" active":""}`,onClick:()=>d(k.file,!0),role:"button",tabIndex:0,onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),d(k.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:v=>v.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`staged:${k.file}`),onChange:()=>r(`staged:${k.file}`)})}),t.jsx(pf,{status:k.status}),t.jsx("span",{className:"gm-file-name",title:k.file,children:t.jsx("bdo",{dir:"ltr",children:k.file})}),t.jsx(ff,{status:k.status}),t.jsx("button",{className:"gm-icon-btn",onClick:v=>{v.stopPropagation(),l([k.file])},title:"Unstage file",children:t.jsx(nn,{size:12})})]},`staged:${k.file}`)})})]})]}),t.jsx("div",{className:"gm-changes-diff",children:u||h||m||f?t.jsxs("div",{className:"gm-diff-section",children:[u&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(Sd,{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(xt,{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(Sd,{size:20}),t.jsx("span",{children:"Select a file to view its diff"})]})})]}),t.jsxs("form",{className:"gm-commit-form",onSubmit:x,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:k=>g(k.target.value),rows:3,disabled:b}),t.jsxs("div",{className:"gm-commit-actions",children:[t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:b||!p.trim()||n.length===0,title:n.length===0?"No staged changes to commit":"Commit staged changes",children:[b?t.jsx(xt,{size:14,className:"spin"}):t.jsx(wa,{size:14}),"Commit"]}),s.length>0&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:w,disabled:b||!p.trim(),title:"Stage all and commit",children:"Stage All & Commit"})]})]})]})}function H$({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(Fi,{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:br(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(sa,{size:12})})}),a===m.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(xt,{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 q$({branches:e,branchSearch:n,setBranchSearch:s,newBranchName:a,setNewBranchName:r,branchBase:o,setBranchBase:l,onCreateBranch:c,onCheckoutBranch:d,onDeleteBranch:u,loading:m,allBranches:h,selectedBranch:f,branchCommits:p,loadingBranchCommits:g,expandedBranchCommit:x,branchCommitDiff:w,loadingBranchCommitDiff:b,onSelectBranch:y,onBranchCommitClick:S,onCloseBranchDetails:k}){return t.jsxs("div",{className:"gm-panel","data-testid":"branches-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Branches"}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(Fi,{size:14}),t.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:C=>s(C.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:c,children:[t.jsx("input",{type:"text",placeholder:"New branch name",value:a,onChange:C=>r(C.target.value),disabled:m}),t.jsxs("select",{value:o,onChange:C=>l(C.target.value),disabled:m,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:"Base: HEAD"}),h.map(C=>t.jsx("option",{value:C.name,children:C.name},C.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:m||!a.trim(),children:[t.jsx(bn,{size:14}),"Create"]})]}),t.jsx("div",{className:"gm-branches-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:n?"No matching branches":"No branches found"}):e.map(C=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${C.isCurrent?" current":""}${f===C.name?" selected":""}`,onClick:()=>y(C.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[C.isCurrent&&t.jsx(hs,{size:14,className:"gm-current-icon"}),C.name]}),C.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",C.remote]}),C.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:br(C.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!C.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:v=>{v.stopPropagation(),d(C.name)},disabled:m,title:"Checkout",children:t.jsx(Us,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:v=>{v.stopPropagation(),u(C.name)},disabled:m,title:"Delete",children:t.jsx(vn,{size:14})})]})})]}),f===C.name&&t.jsxs("div",{className:"gm-branch-details",children:[t.jsxs("div",{className:"gm-branch-details-header",children:[t.jsxs("span",{className:"gm-branch-details-title",children:[t.jsx(ko,{size:14}),"Commits on ",C.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:k,title:"Close","data-testid":"close-branch-details",children:t.jsx(nn,{size:14})})]}),g?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(xt,{size:16,className:"spin"}),"Loading commits..."]}):p.length===0?t.jsx("div",{className:"gm-empty",children:"No commits found"}):t.jsx("div",{className:"gm-branch-commits-list",children:p.map(v=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>S(v.hash),"data-testid":`branch-commit-${v.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:v.shortHash}),t.jsx("span",{className:"gm-commit-message",title:v.message,children:v.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:v.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:br(v.date)}),v.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),x===v.hash&&t.jsx("div",{className:"gm-commit-diff",children:b?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(xt,{size:16,className:"spin"}),"Loading diff..."]}):w?t.jsxs(t.Fragment,{children:[(v.body||v.message)&&t.jsx("div",{className:"gm-commit-message-full",children:v.body||v.message}),w.stat&&t.jsx("pre",{className:"gm-diff-stat",children:w.stat}),t.jsx("pre",{className:"gm-diff-patch",children:w.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},v.hash))})]})]},C.name))})]})}function V$({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:gu(n.path)||n.path})]}),t.jsxs("div",{className:"gm-worktree-detail",children:[n.branch&&t.jsxs("span",{className:"gm-worktree-branch",children:[t.jsx(Us,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function W$({stashes:e,stashMessage:n,setStashMessage:s,onCreateStash:a,onApplyStash:r,onDropStash:o,onToggleStashDiff:l,stashLoading:c,expandedStashIndex:d,stashDiff:u,loadingStashDiff:m,stashDiffError:h}){return t.jsxs("div",{className:"gm-panel","data-testid":"stashes-panel",children:[t.jsx("div",{className:"gm-panel-header",children:t.jsx("h4",{children:"Stashes"})}),t.jsxs("form",{className:"gm-create-form",onSubmit:a,children:[t.jsx("input",{type:"text",placeholder:"Stash message (optional)",value:n,onChange:f=>s(f.target.value),disabled:c!==null}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:c!==null,children:[c==="create"?t.jsx(xt,{size:14,className:"spin"}):t.jsx(xo,{size:14}),"Stash"]})]}),t.jsx("div",{className:"gm-stash-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:"No stashes"}):e.map(f=>t.jsxs("div",{className:"gm-stash-item",children:[t.jsxs("div",{className:"gm-stash-header",children:[t.jsxs("div",{className:"gm-stash-info",children:[t.jsxs("span",{className:"gm-stash-ref",children:["stash@",`{${f.index}}`]}),t.jsx("span",{className:"gm-stash-message",children:f.message}),t.jsxs("div",{className:"gm-stash-meta",children:[f.branch&&t.jsxs("span",{className:"gm-stash-branch",children:[t.jsx(Us,{size:12}),f.branch]}),t.jsx("span",{children:br(f.date)})]})]}),t.jsxs("div",{className:"gm-stash-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>l(f.index),disabled:c!==null,children:d===f.index?"Hide":"View"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>r(f.index,!1),disabled:c!==null,title:"Apply stash (keep)",children:c===`apply-${f.index}`?t.jsx(xt,{size:14,className:"spin"}):"Apply"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>r(f.index,!0),disabled:c!==null,title:"Pop stash (apply and drop)",children:"Pop"}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>o(f.index),disabled:c!==null,title:"Drop stash",children:c===`drop-${f.index}`?t.jsx(xt,{size:14,className:"spin"}):t.jsx(vn,{size:14})})]})]}),d===f.index&&t.jsx("div",{className:"gm-stash-diff",children:m?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(xt,{size:14,className:"spin"}),"Loading stash diff…"]}):h?t.jsx("div",{className:"gm-diff-error",children:h}):u?t.jsxs("div",{className:"gm-diff-viewer",children:[u.stat&&t.jsx("pre",{className:"gm-diff-stat",children:u.stat}),t.jsx("pre",{className:"gm-diff-patch",children:u.patch})]}):null})]},f.index))})]})}function K$({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:a,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:d}){const u=Y=>{try{return new URL(Y).hostname}catch{return Y.replace(/^git@/,"").split(":")[0]||Y}},[m,h]=i.useState([]),[f,p]=i.useState(!1),[g,x]=i.useState(null),[w,b]=i.useState(""),[y,S]=i.useState(""),[k,C]=i.useState(null),[v,j]=i.useState(""),[P,U]=i.useState(""),[E,R]=i.useState(!1),[L,F]=i.useState(!1),M=i.useRef(null),[O,q]=i.useState([]),[te,Z]=i.useState(!1),[K,A]=i.useState(null),[I,$]=i.useState([]),[N,G]=i.useState(!1),[ge,je]=i.useState(null),ke=i.useRef(0),ne=m.find(Y=>Y.name===K);i.useEffect(()=>{(n!==null||f)&&F(!1)},[n,f]),i.useEffect(()=>{if(!L)return;const Y=ct=>{M.current?.contains(ct.target)||F(!1)},_e=ct=>{ct.key==="Escape"&&F(!1)};return document.addEventListener("mousedown",Y),document.addEventListener("keydown",_e),()=>{document.removeEventListener("mousedown",Y),document.removeEventListener("keydown",_e)}},[L]);const[qe,ee]=i.useState(null),[le,se]=i.useState(null),[re,J]=i.useState(!1),[B,ve]=i.useState(null),[Ne,H]=i.useState(null),[be,ce]=i.useState(!1);i.useEffect(()=>{Me()},[]),i.useEffect(()=>{e&&e.ahead>0?Le():e&&e.ahead===0&&q([])},[e?.ahead]),i.useEffect(()=>{m.length>0&&!K&&A(m[0].name)},[m]),i.useEffect(()=>{K?He(K):($([]),je(null))},[K]),i.useEffect(()=>{!K||!s||He(K)},[K,s]),i.useEffect(()=>{K&&!m.find(Y=>Y.name===K)&&A(m.length>0?m[0].name:null)},[m,K]);const Me=async()=>{p(!0);try{const Y=await Rj(c);h(Y)}catch(Y){l(Re(Y)||"Failed to load remotes","error")}finally{p(!1)}},Le=async()=>{Z(!0);try{const Y=await Bj(c);q(Y)}catch{q([])}finally{Z(!1)}},He=async Y=>{const _e=ke.current+1;ke.current=_e,G(!0),je(null);try{const ct=await Hj(Y,void 0,10,c);if(ke.current!==_e)return;$(ct)}catch(ct){if(ke.current!==_e)return;je(Re(ct)||"Failed to load remote commits"),$([])}finally{ke.current===_e&&G(!1)}},gt=ai(),Ue=async Y=>{if(Y.preventDefault(),!(!w.trim()||!y.trim())){x("add");try{await Ij(w.trim(),y.trim(),c),l(`Remote '${w}' added successfully`,"success"),b(""),S(""),R(!1),await Me()}catch(_e){l(Re(_e)||"Failed to add remote","error")}finally{x(null)}}},pe=async Y=>{if(await gt.confirm({title:"Remove Remote",message:`Are you sure you want to remove remote '${Y}'?`,danger:!0})){x(`remove-${Y}`);try{await Tj(Y,c),l(`Remote '${Y}' removed`,"success"),await Me()}catch(ct){l(Re(ct)||"Failed to remove remote","error")}finally{x(null)}}},Oe=async Y=>{if(P.trim()){x(`rename-${Y}`);try{await $j(Y,P.trim(),c),l(`Remote renamed to '${P.trim()}'`,"success"),C(null),U(""),await Me()}catch(_e){l(Re(_e)||"Failed to rename remote","error")}finally{x(null)}}},ze=async Y=>{if(v.trim()){x(`url-${Y}`);try{await Dj(Y,v.trim(),c),l("Remote URL updated","success"),C(null),j(""),await Me()}catch(_e){l(Re(_e)||"Failed to update remote URL","error")}finally{x(null)}}},lt=i.useCallback(async(Y,_e)=>{if(_e==="ahead"){if(qe===Y){ee(null),se(null);return}ee(Y),se(null),J(!0);try{const ct=await El(Y);se(ct)}catch{se(null)}finally{J(!1)}}else{if(B===Y){ve(null),H(null);return}ve(Y),H(null),ce(!0);try{const ct=await El(Y);H(ct)}catch{H(null)}finally{ce(!1)}}},[qe,B]),Be=Y=>{C(`url-${Y.name}`),j(Y.pushUrl||Y.fetchUrl)},ye=Y=>{C(`name-${Y.name}`),U(Y.name)};return t.jsx("div",{className:"gm-panel gm-remotes-panel","data-testid":"remotes-panel",children:t.jsxs("div",{className:"gm-remotes-layout",children:[t.jsxs("div",{className:"gm-remote-selector","data-testid":"remote-selector",children:[t.jsxs("div",{className:"gm-remote-selector-header",children:[t.jsx("span",{className:"gm-remote-selector-title",children:"Remotes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>R(!E),disabled:g!==null,title:E?"Cancel":"Add Remote",children:E?t.jsx(nn,{size:14}):t.jsx(bn,{size:14})})]}),E&&t.jsxs("form",{className:"gm-remote-form",onSubmit:Ue,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:w,onChange:Y=>b(Y.target.value),disabled:g==="add",className:"input gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:y,onChange:Y=>S(Y.target.value),disabled:g==="add",className:"input gm-input gm-input-url"}),t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!w.trim()||!y.trim()||g==="add",children:[g==="add"?t.jsx(xt,{size:12,className:"spin"}):t.jsx(bn,{size:12}),"Add"]})]}),f?t.jsxs("div",{className:"gm-loading",children:[t.jsx(xt,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(Y=>t.jsxs("div",{className:`gm-remote-selector-item${K===Y.name?" selected":""}`,onClick:()=>A(Y.name),role:"button",tabIndex:0,onKeyDown:_e=>{(_e.key==="Enter"||_e.key===" ")&&(_e.preventDefault(),A(Y.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:Y.name}),Y.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",title:Y.fetchUrl,children:u(Y.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm gm-remote-remove-btn",onClick:_e=>{_e.stopPropagation(),pe(Y.name)},disabled:g!==null,title:"Remove remote",children:t.jsx(vn,{size:14})})]},Y.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[K&&ne?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:K}),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(ka,{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(vo,{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(xt,{size:14,className:"spin"}):t.jsx(rs,{size:14}),"Fetch"]}),t.jsxs("div",{className:"gm-pull-split",ref:M,children:[t.jsxs("button",{className:"btn btn-primary gm-pull-split-main",onClick:()=>{F(!1),r({rebase:!1})},disabled:n!==null||f,children:[n==="pull"?t.jsx(xt,{size:14,className:"spin"}):t.jsx(Ws,{size:14}),"Pull"]}),t.jsx("button",{className:"btn btn-primary btn-icon gm-pull-split-toggle",onClick:()=>F(Y=>!Y),disabled:n!==null||f,"aria-label":"Pull options","aria-haspopup":"menu","aria-expanded":L,children:t.jsx(rn,{size:14})}),L?t.jsxs("div",{className:"gm-pull-menu",role:"menu","aria-label":"Pull options menu",children:[t.jsx("button",{className:"gm-pull-menu-item",role:"menuitem",onClick:()=>{F(!1),r({rebase:!1})},children:"Pull"}),t.jsx("button",{className:"gm-pull-menu-item",role:"menuitem",onClick:()=>{F(!1),r({rebase:!0})},children:"Pull --rebase"})]}):null]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||f,children:[n==="push"?t.jsx(xt,{size:14,className:"spin"}):t.jsx(ka,{size:14}),"Push"]})]})]}),t.jsxs("div",{className:"gm-remote-detail-card","data-testid":"remote-detail-card",children:[t.jsxs("div",{className:"gm-remote-detail-urls",children:[t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Fetch:"}),k===`url-${K}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:v,onChange:Y=>j(Y.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>ze(K),disabled:g===`url-${K}`,children:g===`url-${K}`?t.jsx(xt,{size:12,className:"spin"}):t.jsx(hs,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{C(null),j("")},title:"Cancel",children:t.jsx(nn,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:ne.fetchUrl,children:t.jsx("bdo",{dir:"ltr",children:ne.fetchUrl})}),t.jsxs("div",{className:"gm-remote-inline-actions",children:[t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(ne.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(sa,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>Be(ne),disabled:g!==null,title:"Edit remote URL",children:t.jsx(Ds,{size:14})})]})]})]}),ne.pushUrl&&ne.pushUrl!==ne.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:ne.pushUrl,children:t.jsx("bdo",{dir:"ltr",children:ne.pushUrl})}),t.jsx("div",{className:"gm-remote-inline-actions",children:t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(ne.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(sa,{size:14})})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:k===`name-${K}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:P,onChange:Y=>U(Y.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Oe(K),disabled:g===`rename-${K}`,children:g===`rename-${K}`?t.jsx(xt,{size:12,className:"spin"}):t.jsx(hs,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{C(null),U("")},title:"Cancel",children:t.jsx(nn,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>ye(ne),disabled:g!==null,title:"Edit remote name",children:t.jsx(Ds,{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(ka,{size:14}),"Commits to Push (",e.ahead,")"]})}),te?t.jsxs("div",{className:"gm-loading",children:[t.jsx(xt,{size:14,className:"spin"}),"Loading..."]}):O.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:O.map(Y=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>lt(Y.hash,"ahead"),role:"button",tabIndex:0,onKeyDown:_e=>{(_e.key==="Enter"||_e.key===" ")&&(_e.preventDefault(),lt(Y.hash,"ahead"))},title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:Y.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:Y.message,children:Y.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:Y.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:br(Y.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:qe===Y.hash?t.jsx(rn,{size:14}):t.jsx(Mn,{size:14})})]}),qe===Y.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:re?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(xt,{size:16,className:"spin"}),"Loading diff..."]}):le?t.jsxs(t.Fragment,{children:[(Y.body||Y.message)&&t.jsx("div",{className:"gm-commit-message-full",children:Y.body||Y.message}),le.stat&&t.jsx("pre",{className:"gm-diff-stat",children:le.stat}),t.jsx("pre",{className:"gm-diff-patch",children:le.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},Y.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(gg,{size:14}),"Recent commits on ",K]})}),N?t.jsxs("div",{className:"gm-loading",children:[t.jsx(xt,{size:14,className:"spin"}),"Loading commits..."]}):ge?t.jsxs("div",{className:"gm-error",children:[t.jsx(Ps,{size:14}),ge]}):I.length===0?t.jsxs("div",{className:"gm-empty",children:["No commits found on ",K,". Try fetching first."]}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:I.map(Y=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>lt(Y.hash,"remote"),role:"button",tabIndex:0,onKeyDown:_e=>{(_e.key==="Enter"||_e.key===" ")&&(_e.preventDefault(),lt(Y.hash,"remote"))},title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:Y.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:Y.message,children:Y.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:Y.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:br(Y.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:B===Y.hash?t.jsx(rn,{size:14}):t.jsx(Mn,{size:14})})]}),B===Y.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:be?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(xt,{size:16,className:"spin"}),"Loading diff..."]}):Ne?t.jsxs(t.Fragment,{children:[(Y.body||Y.message)&&t.jsx("div",{className:"gm-commit-message-full",children:Y.body||Y.message}),Ne.stat&&t.jsx("pre",{className:"gm-diff-stat",children:Ne.stat}),t.jsx("pre",{className:"gm-diff-patch",children:Ne.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},Y.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 Za={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function G$(e,n){return e&&n?`${e}/${n}`:""}function J$(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 gf(e){switch(e){case"file-text":return ia;case"check-circle":return $n;case"shield":return Ww;case"zap":return Qn;case"eye":return kr;case"globe":return Wl;case"layout-grid":return aa;case"puzzle":return Aw;default:return $n}}function bf(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 Y$({isOpen:e,onClose:n,addToast:s,projectId:a}){const[r,o]=i.useState([]),[l,c]=i.useState([]),[d,u]=i.useState({}),[m,h]=i.useState(!0),[f,p]=i.useState(!0),[g,x]=i.useState("my-steps"),[w,b]=i.useState(null),[y,S]=i.useState(!1),[k,C]=i.useState(!1),[v,j]=i.useState(Za),[P,U]=i.useState(!1),[E,R]=i.useState(!1),[L,F]=i.useState(null),[M,O]=i.useState(null),[q,te]=i.useState({}),[Z,K]=i.useState([]),A=i.useRef(null);Ai(A,e,"fusion:workflow-steps-modal-size");const I=i.useCallback(async()=>{try{h(!0);const B=await _o(a);o(B)}catch(B){s(Re(B)||"Failed to load workflow steps","error")}finally{h(!1)}},[s,a]),$=i.useCallback(async()=>{try{const B=await mo(a);te(B||{})}catch{}},[a]),N=i.useCallback(async()=>{try{const B=await Os();K(B.models||[])}catch{}},[]),G=i.useCallback(async()=>{try{p(!0);const[B,ve]=await Promise.all([BN(),HN()]);c(B.templates);const Ne=Object.fromEntries(ve.templates.map(({pluginId:H,template:be})=>[be.id,H]));u(Ne)}catch(B){s(Re(B)||"Failed to load templates","error")}finally{p(!1)}},[s]);i.useEffect(()=>{e&&(I(),G(),$(),N())},[e,I,G,$,N]);const ge=i.useCallback(()=>{C(!0),S(!1),b(null),j(Za)},[]),je=i.useCallback(()=>{C(!1),S(!0),b(null),j(Za)},[]),ke=i.useCallback(B=>{b(B.id),S(!1),j({name:B.name,description:B.description,mode:B.mode||"prompt",phase:B.phase||"pre-merge",prompt:B.prompt,scriptName:B.scriptName||"",enabled:B.enabled,defaultOn:B.defaultOn||!1,modelProvider:B.modelProvider||"",modelId:B.modelId||""})},[]),ne=i.useCallback(()=>{b(null),S(!1),C(!1),j(Za)},[]),qe=i.useCallback(async()=>{if(!v.name.trim()||!v.description.trim()){s("Name and description are required","error");return}U(!0);try{const B=v.mode==="prompt"&&v.modelProvider&&v.modelId?{modelProvider:v.modelProvider,modelId:v.modelId}:v.mode==="prompt"?{modelProvider:void 0,modelId:void 0}:{};if(y){const ve={name:v.name.trim(),description:v.description.trim(),mode:v.mode,phase:v.phase,prompt:v.mode==="prompt"&&v.prompt.trim()||void 0,scriptName:v.mode==="script"?v.scriptName.trim():void 0,enabled:v.enabled,defaultOn:v.defaultOn||void 0,...B};await pm(ve,a),s("Workflow step created","success")}else w&&(await zN(w,{name:v.name.trim(),description:v.description.trim(),mode:v.mode,phase:v.phase,prompt:v.mode==="prompt"?v.prompt:"",scriptName:v.mode==="script"?v.scriptName.trim():void 0,enabled:v.enabled,defaultOn:v.defaultOn,...B},a),s("Workflow step updated","success"));S(!1),b(null),j(Za),await I()}catch(B){s(Re(B)||"Failed to save workflow step","error")}finally{U(!1)}},[v,y,w,s,I]),ee=i.useCallback(async B=>{try{await FN(B,a),s("Workflow step deleted","success"),F(null),w===B&&(b(null),j(Za)),await I()}catch(ve){s(Re(ve)||"Failed to delete workflow step","error")}},[w,s,I]),le=i.useCallback(async()=>{if(!(!w&&!y)&&v.mode==="prompt"){if(y){if(!v.name.trim()||!v.description.trim()){s("Name and description are required before refining","error");return}U(!0);try{const B=v.modelProvider&&v.modelId?{modelProvider:v.modelProvider,modelId:v.modelId}:{},ve={name:v.name.trim(),description:v.description.trim(),mode:"prompt",prompt:v.prompt.trim()||void 0,enabled:v.enabled,defaultOn:v.defaultOn||void 0,...B},Ne=await pm(ve,a);S(!1),b(Ne.id),R(!0);const H=await fm(Ne.id,a);j(be=>({...be,prompt:H.prompt})),s("Prompt refined with AI","success"),await I()}catch(B){s(Re(B)||"Failed to refine prompt","error")}finally{U(!1),R(!1)}return}if(w){R(!0);try{const B=await fm(w,a);j(ve=>({...ve,prompt:B.prompt})),s("Prompt refined with AI","success"),await I()}catch(B){s(Re(B)||"Failed to refine prompt","error")}finally{R(!1)}}}},[w,y,v,s,I]),se=i.useCallback(async B=>{O(B.id);try{await qN(B.id,a),s(`Added ${B.name} workflow step`,"success"),await I(),x("my-steps"),C(!1)}catch(ve){const Ne=Re(ve);Ne?.includes("already exists")?s(`A workflow step named '${B.name}' already exists`,"error"):s(Ne||"Failed to add workflow step from template","error")}finally{O(null)}},[s,I]),re=qi(n);if(!e)return null;const J=y||w!==null;return t.jsx("div",{className:"modal-overlay open",...re,"data-testid":"workflow-step-manager",children:t.jsxs("div",{ref:A,className:"modal workflow-step-manager-modal",role:"dialog","aria-modal":"true","aria-label":"Workflow Steps",children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h2",{children:"Workflow Steps"}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"wfm-body",children:m?t.jsx("div",{className:"wfm-loading",children:"Loading..."}):t.jsxs(t.Fragment,{children:[!J&&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(Tv,{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(aa,{size:14}),"Templates (",l.length,")"]})]}),g==="my-steps"&&!J&&!k&&t.jsxs(t.Fragment,{children:[r.length===0&&t.jsx("div",{className:"wfm-empty","data-testid":"empty-state",children:"No workflow steps defined. Create one to get started, or add one from the Templates tab."}),r.length>0&&t.jsx("div",{className:"wfm-step-list",children:r.map(B=>t.jsx("div",{className:"wfm-step-card","data-testid":`workflow-step-${B.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:B.name}),t.jsx("span",{className:`wfm-badge ${B.enabled?"wfm-badge-enabled":"wfm-badge-disabled"}`,children:B.enabled?"Enabled":"Disabled"}),t.jsx("span",{className:`wfm-badge ${(B.mode||"prompt")==="script"?"wfm-badge-script":"wfm-badge-prompt"}`,children:(B.mode||"prompt")==="script"?"Script":"AI Prompt"}),t.jsx("span",{className:`wfm-badge ${(B.phase||"pre-merge")==="post-merge"?"wfm-badge-post-merge":"wfm-badge-pre-merge"}`,children:(B.phase||"pre-merge")==="post-merge"?"Post-merge":"Pre-merge"}),B.defaultOn&&t.jsx("span",{className:"wfm-badge wfm-badge-default-on",children:"Default on"})]}),t.jsx("div",{className:"wfm-step-card-desc",children:B.description})]}),t.jsxs("div",{className:"wfm-step-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>ke(B),title:"Edit","aria-label":`Edit ${B.name}`,children:t.jsx(Ds,{size:14})}),L===B.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>ee(B.id),title:"Confirm delete","aria-label":`Confirm delete ${B.name}`,children:t.jsx(hs,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>F(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(nn,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>F(B.id),title:"Delete","aria-label":`Delete ${B.name}`,children:t.jsx(vn,{size:14})})]})]})},B.id))})]}),g==="templates"&&!J&&!k&&t.jsx(t.Fragment,{children:f?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(xt,{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(B=>{const ve=gf(B.icon),Ne=bf(B.category),H=M===B.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`template-${B.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(ve,{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:B.name}),t.jsx("span",{className:Ne,children:B.category}),d[B.id]&&t.jsx("span",{className:"wfm-badge-category wfm-badge-category-plugin",children:d[B.id]})]}),t.jsx("div",{className:"wfm-template-desc",children:B.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>se(B),disabled:H,"data-testid":`add-template-${B.id}`,children:H?t.jsxs(t.Fragment,{children:[t.jsx(xt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(bn,{size:12}),"Add"]})})]})]})},B.id)})})}),k&&!J&&t.jsxs("div",{className:"wfm-create-chooser","data-testid":"workflow-step-create-chooser",children:[t.jsx("h3",{className:"wfm-form-title",children:"How would you like to create this workflow step?"}),t.jsx("p",{className:"wfm-create-chooser-hint",children:"Start from a built-in template or create a fully custom workflow step."}),t.jsxs("button",{className:"btn wfm-create-custom-btn",onClick:je,"data-testid":"create-custom-step",children:[t.jsx(bn,{size:14}),"Custom workflow step"]}),f?t.jsxs("div",{className:"wfm-loading","data-testid":"create-chooser-template-loading",children:[t.jsx(xt,{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(B=>{const ve=gf(B.icon),Ne=bf(B.category),H=M===B.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`chooser-template-${B.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(ve,{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:B.name}),t.jsx("span",{className:Ne,children:B.category}),d[B.id]&&t.jsx("span",{className:"wfm-badge-category wfm-badge-category-plugin",children:d[B.id]})]}),t.jsx("div",{className:"wfm-template-desc",children:B.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>se(B),disabled:H,"data-testid":`chooser-add-template-${B.id}`,children:H?t.jsxs(t.Fragment,{children:[t.jsx(xt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(bn,{size:12}),"Add template"]})})]})]})},B.id)})})]}),J&&t.jsxs("div",{className:"wfm-form","data-testid":"workflow-step-form",children:[t.jsx("h3",{className:"wfm-form-title",children:y?"New Workflow Step":"Edit Workflow Step"}),t.jsxs("div",{className:"wfm-form-fields",children:[t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Name"}),t.jsx("input",{type:"text",value:v.name,onChange:B=>j(ve=>({...ve,name:B.target.value})),placeholder:"e.g. Documentation Review","data-testid":"workflow-step-name"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{value:v.description,onChange:B=>j(ve=>({...ve,description:B.target.value})),placeholder:"Brief description of what this step does",rows:2,"data-testid":"workflow-step-description"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Mode"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-mode-selector",children:[t.jsxs("button",{className:`btn ${v.mode==="prompt"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>j(B=>({...B,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(Ui,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${v.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>j(B=>({...B,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(Bi,{size:14}),"Run Script"]})]})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Phase"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-phase-selector",children:[t.jsx("button",{className:`btn ${v.phase==="pre-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>j(B=>({...B,phase:"pre-merge"})),"data-testid":"phase-pre-merge",children:"Pre-merge"}),t.jsx("button",{className:`btn ${v.phase==="post-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>j(B=>({...B,phase:"post-merge"})),"data-testid":"phase-post-merge",children:"Post-merge"})]}),t.jsx("div",{className:"wfm-field-hint",children:v.phase==="pre-merge"?"Runs before merge — can block merge on failure":"Runs after merge success — failures are logged but do not block"})]}),v.mode==="prompt"&&t.jsxs("div",{className:"wfm-field",children:[t.jsxs("div",{className:"wfm-prompt-header",children:[t.jsx("label",{children:"Agent Prompt"}),t.jsxs("button",{className:"btn-icon wfm-refine-btn",onClick:le,disabled:!v.description.trim()||E,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[E?t.jsx(xt,{size:12,className:"spin"}):t.jsx(ps,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:v.prompt,onChange:B=>j(ve=>({...ve,prompt:B.target.value})),placeholder:"Leave empty to use AI refinement",rows:6,className:"wfm-prompt-textarea","data-testid":"workflow-step-prompt"})]}),v.mode==="prompt"&&t.jsxs("div",{className:"wfm-field","data-testid":"workflow-step-model-field",children:[t.jsxs("div",{className:"wfm-model-header",children:[t.jsx("label",{children:"Model Override"}),v.modelProvider&&v.modelId&&t.jsxs("button",{type:"button",className:"btn-icon wfm-model-clear-btn",onClick:()=>j(B=>({...B,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(nn,{size:12}),t.jsx("span",{children:"Use default"})]})]}),t.jsx("span",{className:"wfm-model-hint",children:v.modelProvider&&v.modelId?`Using ${v.modelProvider}/${v.modelId}`:"Using global default model"}),t.jsx("div",{"data-testid":"workflow-step-model-select",children:t.jsx(ys,{models:Z,value:G$(v.modelProvider,v.modelId),onChange:B=>{const ve=J$(B);j(Ne=>({...Ne,modelProvider:ve.provider,modelId:ve.modelId}))},placeholder:"Select a model override…",label:"Model override for this workflow step"})})]}),v.mode==="script"&&t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Script"}),Object.keys(q).length===0?t.jsx("div",{className:"wfm-no-scripts","data-testid":"no-scripts-message",children:"No scripts configured. Add scripts in Settings → Scripts first."}):t.jsxs("select",{value:v.scriptName,onChange:B=>j(ve=>({...ve,scriptName:B.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(q).map(([B,ve])=>t.jsxs("option",{value:B,children:[B," (",ve,")"]},B))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:v.enabled,onChange:B=>j(ve=>({...ve,enabled:B.target.checked})),"data-testid":"workflow-step-enabled"}),"Enabled (available for selection on new tasks)"]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:v.defaultOn,onChange:B=>j(ve=>({...ve,defaultOn:B.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:ne,disabled:P,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:qe,disabled:P||!v.name.trim()||!v.description.trim()||v.mode==="script"&&!v.scriptName.trim(),"data-testid":"save-workflow-step",children:P?"Saving...":y?"Create":"Save"})]})]})]})]})}),!J&&!k&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:ge,"data-testid":"add-workflow-step",children:[t.jsx(bn,{size:14}),"Add Workflow Step"]})})]})})}const Q$=36e5,X$=3e5,fd=[{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 Z$(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 eD(e){return typeof e!="number"||!Number.isFinite(e)?Q$:Math.max(X$,Math.round(e))}function G6(e){if(fd.some(s=>s.value===e))return[...fd];const n={value:e,label:`${Z$(e)} (custom)`};return[...fd,n].sort((s,a)=>s.value-a.value)}const tD=4,nD=5*6e4;function sD(e){const n=eD(e?.heartbeatIntervalMs);return Math.max(n*tD,nD)}function xf(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 iD(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 aD(e){const{state:n,lastHeartbeatAt:s,lastError:a,pauseReason:r,runtimeConfig:o}=e,l=iD(e),c=l||o?.enabled!==!1;if(n==="error")return{label:a??"Error",icon:t.jsx(Ks,{size:14}),color:"var(--state-error-text)",stateDerived:!a};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(pi,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(Ks,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!c)return{label:"Heartbeat Disabled",icon:t.jsx(pi,{size:14}),color:"var(--state-paused-text)",stateDerived:!1};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(Tn,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const d=new Date(s).getTime(),u=Date.now()-d,m=sD(o);if(u>m){const h=`No heartbeat for ${xf(u)} (threshold: ${xf(m)})`;return{label:"Unresponsive",icon:t.jsx(Ks,{size:14}),color:"var(--state-error-text)",stateDerived:!1,reason:h}}return{label:"Healthy",icon:t.jsx(By,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}function Zd({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(Tn,{size:Math.max(14,Math.round(n*.55)),"aria-hidden":"true"})})}const rD="https://github.com/Runfusion/Fusion/issues/new";function oD(e,n){const s=`[Agent Error] ${n.surface}${n.agentName?` - ${n.agentName}`:""}`,a=["## Agent Error Report","",`- Surface: ${n.surface}`,`- Agent ID: ${n.agentId??"unknown"}`,`- Agent Name: ${n.agentName??"unknown"}`,`- Agent State: ${n.agentState??"unknown"}`,`- Run ID: ${n.runId??"n/a"}`,`- Task ID: ${n.taskId??"n/a"}`,`- Timestamp: ${n.timestamp??new Date().toISOString()}`,"","## Error","```text",e,"```"],r=new URLSearchParams({title:s,body:a.join(`
|
|
691
|
+
`)});return`${rD}?${r.toString()}`}function lD({open:e,onClose:n,errorText:s,issueContext:a}){const[r,o]=i.useState(!1),l=i.useMemo(()=>oD(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(Ps,{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(hs,{size:14}):t.jsx(sa,{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(dg,{size:14}),"Report on GitHub"]})]})]})}):null}function cD({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(Ps,{size:14}),t.jsx("span",{className:"agent-error-indicator__label",children:s})]}),t.jsx(lD,{open:a,onClose:()=>r(!1),errorText:e,issueContext:n})]})}const ml=[{value:"triage",label:"Triage",icon:"⊕"},{value:"executor",label:"Executor",icon:"▶"},{value:"reviewer",label:"Reviewer",icon:"⊙"},{value:"merger",label:"Merger",icon:"⊞"},{value:"scheduler",label:"Scheduler",icon:"◷"},{value:"engineer",label:"Engineer",icon:"⎔"},{value:"custom",label:"Custom",icon:"✦"}];function dD({isOpen:e,onClose:n,addToast:s,projectId:a}){const[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[m,h]=i.useState(""),[f,p]=i.useState("custom"),[g,x]=i.useState("all"),[w,b]=i.useState(()=>{if(typeof window>"u")return"list";const $=Dn("fn-agent-view",a);return $==="board"||$==="list"?$:"list"});i.useEffect(()=>{const $=Dn("fn-agent-view",a);if($==="board"||$==="list"){b($);return}b("list")},[a]),i.useEffect(()=>{os("fn-agent-view",w,a)},[a,w]);const[y,S]=i.useState(null),k=i.useRef(null),[C,v]=i.useState(new Set),[j,P]=i.useState(new Map),{confirm:U}=ai(),E=i.useMemo(()=>j.size===0?r:r.map($=>{const N=j.get($.id);return N?{...$,state:N}:$}),[r,j]),R=i.useMemo(()=>g!=="all"?E:[...E].sort(($,N)=>{const G=$.state==="paused"?1:0,ge=N.state==="paused"?1:0;return G!==ge?G-ge:(N.updatedAt??"").localeCompare($.updatedAt??"")}),[E,g]),L=i.useCallback(async()=>{c(!0);try{const N=await Nr(g!=="all"?{state:g}:void 0,a);o(N)}catch($){s(`Failed to load agents: ${Re($)}`,"error")}finally{c(!1)}},[g,s,a]);i.useEffect(()=>{e&&L()},[e,L]),i.useEffect(()=>{if(!e)return;const $=setInterval(()=>{L()},3e4);return()=>{clearInterval($)}},[e,L]);const F=async()=>{if(m.trim())try{await ZN({name:m.trim(),role:f},a),s(`Agent "${m}" created`,"success"),h(""),u(!1),L()}catch($){s(`Failed to create agent: ${Re($)}`,"error")}},M=async($,N)=>{if(!C.has($)){v(G=>new Set(G).add($)),P(G=>{const ge=new Map(G);return ge.set($,N),ge});try{await tS($,N,a),s(`Agent state updated to ${N}`,"success"),await L(),P(G=>{const ge=new Map(G);return ge.delete($),ge})}catch(G){P(ge=>{const je=new Map(ge);return je.delete($),je}),s(`Failed to update state: ${Re(G)}`,"error")}finally{v(G=>{const ge=new Set(G);return ge.delete($),ge})}}},O=async($,N)=>{if(await U({title:"Delete Agent",message:`Delete agent "${N}"? This cannot be undone.`,danger:!0}))try{await nS($,a),s(`Agent "${N}" deleted`,"success"),L()}catch(ge){s(`Failed to delete agent: ${Re(ge)}`,"error")}},q=async($,N)=>{const G=r.find(ge=>ge.id===$);if(G){if(G.role===N){S(null);return}try{await eS($,{role:N},a),s(`Agent role updated to ${ml.find(ge=>ge.value===N)?.label??N}`,"success"),S(null),L()}catch(ge){s(`Failed to update role: ${Re(ge)}`,"error")}}},te=($,N)=>{$.key==="Escape"&&S(null)},Z=$=>ml.find(N=>N.value===$)?.label??$,K=$=>aD($),A=$=>$.color==="var(--state-active-text)"?"active":$.color==="var(--state-paused-text)"?"paused":$.color==="var(--state-error-text)"?"error":"muted",I=($,N)=>$.state==="error"?{title:void 0,label:"Error"}:{title:N.reason??N.label,label:N.stateDerived?null:N.label};return e?t.jsx("div",{className:"modal-overlay open",onClick:$=>$.target===$.currentTarget&&n(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal--wide agent-list-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{className:"modal-title",children:[t.jsx(Tn,{size:20}),"Agents"]}),t.jsxs("div",{className:"modal-actions",children:[t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${w==="board"?" active":""}`,onClick:()=>b("board"),title:"Board view","aria-label":"Board view","aria-pressed":w==="board",children:t.jsx(aa,{size:16})}),t.jsx("button",{className:`view-toggle-btn${w==="list"?" active":""}`,onClick:()=>b("list"),title:"List view","aria-label":"List view","aria-pressed":w==="list",children:t.jsx(Ed,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void L(),title:"Refresh",disabled:l,children:t.jsx(rs,{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(jl,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:g,onChange:$=>x($.target.value),"aria-label":"Filter agents by state",children:[t.jsx("option",{value:"all",children:"All States"}),t.jsx("option",{value:"idle",children:"Idle"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"running",children:"Running"}),t.jsx("option",{value:"paused",children:"Paused"}),t.jsx("option",{value:"error",children:"Error"})]})]}),t.jsxs("button",{className:"btn btn-task-create btn-sm",onClick:()=>u(!d),children:[t.jsx(bn,{size:16}),d?"Cancel":"New Agent"]})]}),d&&t.jsxs("div",{className:"agent-create-form",children:[t.jsx("input",{type:"text",placeholder:"Agent name...",value:m,onChange:$=>h($.target.value),onKeyDown:$=>$.key==="Enter"&&F(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:f,onChange:$=>p($.target.value),children:ml.map($=>t.jsxs("option",{value:$.value,children:[$.icon," ",$.label]},$.value))}),t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:()=>void F(),children:"Create"})]}),t.jsx("div",{className:w==="board"?"agent-board":"agent-list",children:R.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(Tn,{size:48,opacity:.3}),t.jsx("p",{children:"No agents found"}),t.jsx("p",{className:"text-secondary",children:"Create an agent to get started"})]}):w==="board"?R.map($=>{const N=K($),G=I($,N),ge=A(N);return t.jsxs("div",{className:"agent-board-card","data-state":$.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:t.jsx(Zd,{agent:$,size:20})}),t.jsx("span",{className:"agent-board-badge","data-state":$.state,children:$.state}),t.jsx("span",{className:"agent-board-health","data-health":ge,title:G.title,children:N.icon})]}),t.jsx("div",{className:"agent-board-name",title:$.name,children:$.name}),t.jsx("div",{className:"agent-board-id",children:$.id}),t.jsxs("div",{className:"agent-board-actions",children:[$.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void M($.id,"active"),disabled:C.has($.id),title:"Activate",children:t.jsx(Yn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void O($.id,$.name),title:"Delete",children:t.jsx(vn,{size:14})})]}),$.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void M($.id,"paused"),disabled:C.has($.id),title:"Pause",children:t.jsx(pi,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void M($.id,"paused"),disabled:C.has($.id),title:"Stop",children:t.jsx(Si,{size:14})})]}),$.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void M($.id,"active"),disabled:C.has($.id),title:"Resume",children:t.jsx(Yn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void O($.id,$.name),title:"Delete",children:t.jsx(vn,{size:14})})]}),$.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void M($.id,"paused"),disabled:C.has($.id),title:"Pause",children:t.jsx(pi,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void M($.id,"paused"),disabled:C.has($.id),title:"Stop",children:t.jsx(Si,{size:14})})]}),$.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void M($.id,"active"),disabled:C.has($.id),title:"Retry",children:t.jsx(Yn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void M($.id,"paused"),disabled:C.has($.id),title:"Stop",children:t.jsx(Si,{size:14})})]})]})]},$.id)}):R.map($=>{const N=K($),G=I($,N),ge=A(N);return t.jsxs("div",{className:"agent-card","data-state":$.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[y===$.id?t.jsx("select",{ref:k,className:"select agent-role-select",value:$.role,onChange:je=>void q($.id,je.target.value),onKeyDown:je=>te(je,$.id),onBlur:()=>S(null),autoFocus:!0,children:ml.map(je=>t.jsxs("option",{value:je.value,children:[je.icon," ",je.label]},je.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>S($.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:je=>{(je.key==="Enter"||je.key===" ")&&S($.id)},children:t.jsx(Zd,{agent:$,size:20})}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:$.name}),t.jsx("span",{className:"agent-id text-secondary",children:$.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":$.state,children:$.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":ge,title:G.title,children:[N.icon,G.label?` ${G.label}`:""]}),t.jsx("span",{className:"badge text-secondary",children:Z($.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[$.state==="error"&&$.lastError?t.jsx(cD,{errorText:$.lastError,issueContext:{surface:"AgentListModal list",agentId:$.id,agentName:$.name,agentState:$.state,taskId:$.taskId}}):null,$.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:$.taskId})]}),$.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date($.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[$.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void M($.id,"active"),disabled:C.has($.id),title:"Activate",children:[t.jsx(Yn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void O($.id,$.name),title:"Delete",children:[t.jsx(vn,{size:14})," Delete"]})]}),$.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void M($.id,"paused"),disabled:C.has($.id),title:"Pause",children:[t.jsx(pi,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void M($.id,"paused"),disabled:C.has($.id),title:"Stop",children:[t.jsx(Si,{size:14})," Stop"]})]}),$.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void M($.id,"active"),disabled:C.has($.id),title:"Resume",children:[t.jsx(Yn,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void O($.id,$.name),title:"Delete",children:[t.jsx(vn,{size:14})," Delete"]})]}),$.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void M($.id,"paused"),disabled:C.has($.id),title:"Pause",children:[t.jsx(pi,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void M($.id,"paused"),disabled:C.has($.id),title:"Stop",children:[t.jsx(Si,{size:14})," Stop"]})]}),$.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void M($.id,"active"),disabled:C.has($.id),title:"Retry",children:[t.jsx(Yn,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void M($.id,"paused"),disabled:C.has($.id),title:"Stop",children:[t.jsx(Si,{size:14})," Stop"]})]})]})]},$.id)})})]})]})}):null}function uD({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 lj();return u.current&&r(b),b}catch(b){return u.current&&d({kind:"error",message:b instanceof Error?b.message:String(b)}),null}},[]);i.useEffect(()=>{m()},[m]);const h=i.useCallback(async()=>{l("testing"),d(null),await m(),u.current&&l(null)},[m]),f=i.useCallback(async b=>{l(b?"enabling":"disabling"),d(null);try{const y=await pj(b);u.current&&d({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await m()}catch(y){u.current&&d({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{u.current&&l(null)}},[n,m]),p=a?.binary.available??!1,g=a?.enabled??e,x=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"claude"})," CLI. Uses your existing Claude subscription / quota instead of an API key."]}),w=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(xt,{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(Sn,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(mD,{status:a,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:w})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:"Details"}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[x,t.jsx(vf,{status:a,authenticated:e}),c&&t.jsx(yf,{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(Sn,{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(vf,{status:a,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:w}),c&&t.jsx(yf,{action:c})]})}function mD({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 vf({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(xt,{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 yf({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 hD({authenticated:e,compact:n=!1,onToggled:s}){const[a,r]=i.useState(null),[o,l]=i.useState(null),c=i.useRef(!0);i.useEffect(()=>(c.current=!0,()=>{c.current=!1}),[]);const d=i.useCallback(async()=>{try{const g=await mj();return c.current&&r(g),g}catch{return null}},[]);i.useEffect(()=>{d()},[d]);const u=i.useCallback(async g=>{l(g?"enabling":"disabling");try{const x=await gj(g);s?.(x.enabled),await d()}finally{c.current&&l(null)}},[s,d]),m=a?.enabled??e,h=a?.binary.available??!1,f=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{l("testing"),d().finally(()=>{c.current&&l(null)})},disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(xt,{size:12,className:"animate-spin"})," Testing…"]}):"Test"}),m?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void u(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void u(!0),disabled:o!==null||!h,children:o==="enabling"?"Enabling…":"Enable"})]}),p=a?a.binary.available?m?`Connected${a.binary.version?` — ${a.binary.version}`:""}`:"Detected. Click Enable to route calls through Cursor CLI.":a.binary.reason??"`cursor-agent` not found on PATH":"Probing local CLI…";return n?t.jsxs("div",{className:`cursor-cli-provider-card auth-provider-card auth-provider-card--cli${e?" auth-provider-card--authenticated":""}`,"data-testid":"cursor-cli-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(Sn,{provider:"cursor-cli",size:"sm"}),t.jsx("strong",{children:"Cursor — via Cursor CLI"}),t.jsx("span",{className:`auth-status-badge ${m?"authenticated":"not-authenticated"}`,children:m?"✓ Active":"✗ Not connected"})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:f})]}),t.jsx("small",{className:"settings-muted",children:p})]}):t.jsxs("div",{className:`cursor-cli-provider-card onboarding-provider-card${e?" onboarding-provider-card--connected":""}`,"data-testid":"cursor-cli-provider-card",children:[t.jsx("div",{className:"onboarding-provider-card__icon",children:t.jsx(Sn,{provider:"cursor-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:"Cursor — via Cursor CLI"}),t.jsx("span",{className:"onboarding-provider-card__description",children:"Route AI calls through your local Cursor agent runtime."}),t.jsx("small",{className:"settings-muted",children:p})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:f})]})}function pD({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 hj();return c.current&&r(x),x},[]);i.useEffect(()=>{d()},[d]);const u=i.useCallback(async x=>{l(x?"enabling":"disabling");try{const w=await bj(x);n?.(w.enabled),await d()}finally{c.current&&l(null)}},[n,d]),m=i.useCallback(async()=>{l("testing");try{await d()}finally{c.current&&l(null)}},[d]),h=a?.enabled??e,f=a?.server.available??!1,p=a?a.server.available?`Server reachable at ${a.server.url}`:`Server unavailable: ${a.server.reason??"not reachable"}`:"Probing llama.cpp server…",g=t.jsxs("div",{className:"auth-provider-cli-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void m(),disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(xt,{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(Sn,{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(Sn,{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 fD(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 gd({instructions:e,"data-testid":n}){const[s,a]=i.useState(!1),r=fD(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(hs,{size:12}):t.jsx(sa,{size:12})})]})]},u))}):e})}function gD({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 bD=new Set(["anthropic","claude-cli","pi-claude-cli","openai","openai-codex","google","gemini","google-antigravity","antigravity","google-vertex","vertex","google-cloud-code","cloud-code","google-gemini-cli","google-generative-ai","ollama","github","github-copilot","openrouter","minimax","minimax-cn","zai","kimi","moonshot","kimi-coding","bedrock","amazon-bedrock","xai","grok","opencode","opencode-go","qwen","qwen-ai","qwen-coder","alibaba","tongyi","lmstudio","lm-studio","huggingface","hugging-face","hf","mistral","mistral-ai","azure","azure-openai","azure-openai-responses","fireworks","fireworks-ai","fireworksai","cerebras","groq","vercel","vercel-ai-gateway","hermes","hermes-agent","hermesagent","openclaw","open-claw","paperclip","paperclipai","paperclip-ai"]),xD=/^[a-z][a-z0-9-]*$/,wf=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function kf(){return{id:"",name:"",reasoning:!1}}function vD({initialConfig:e,onSave:n,onCancel:s,saving:a=!1,error:r}){const o=!!e,[l,c]=i.useState(e?.id??""),[d,u]=i.useState(e?.name??""),[m,h]=i.useState(e?.baseUrl??""),[f,p]=i.useState(e?.api??"openai-completions"),[g,x]=i.useState(e?.apiKey??""),[w,b]=i.useState(e?.models?.length?e.models:[kf()]),[y,S]=i.useState(null),k=w.length>1,C=i.useMemo(()=>y??r??null,[y,r]);function v(E,R){b(L=>L.map((F,M)=>M===E?{...F,...R}:F))}function j(E){b(R=>R.length<=1?R:R.filter((L,F)=>F!==E))}function P(){if(!l.trim())return"Provider ID is required.";if(!xD.test(l.trim()))return"Provider ID must be kebab-case.";if(!o&&bD.has(l.trim()))return"Provider ID conflicts with a built-in provider.";if(!m.trim())return"Base URL is required.";try{const E=new URL(m.trim());if(E.protocol!=="http:"&&E.protocol!=="https:")return"Base URL must use http or https."}catch{return"Base URL must be a valid URL."}return wf.includes(f)?w.length===0?"At least one model is required.":w.some(E=>!E.id?.trim())?"Each model must have a model ID.":null:"API type is required."}async function U(E){E.preventDefault();const R=P();S(R),!R&&await n({id:l.trim(),name:d.trim()||void 0,baseUrl:m.trim(),api:f,apiKey:g.trim()||void 0,models:w.map(L=>({id:L.id.trim(),name:L.name?.trim()||void 0,reasoning:!!L.reasoning,contextWindow:L.contextWindow,maxTokens:L.maxTokens}))})}return t.jsxs("form",{onSubmit:U,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:E=>c(E.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:E=>u(E.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:E=>h(E.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:E=>p(E.target.value),disabled:a,children:wf.map(E=>t.jsx("option",{value:E,children:E},E))})]}),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:E=>x(E.target.value),disabled:a})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{children:"Models"}),t.jsx("div",{className:"custom-provider-form__models",children:w.map((E,R)=>t.jsxs("div",{className:"custom-provider-form__model-row",children:[t.jsx("input",{className:"input","aria-label":`Model ID ${R+1}`,placeholder:"Model ID",value:E.id,onChange:L=>v(R,{id:L.target.value}),disabled:a}),t.jsx("input",{className:"input","aria-label":`Model name ${R+1}`,placeholder:"Display name",value:E.name??"",onChange:L=>v(R,{name:L.target.value}),disabled:a}),t.jsxs("label",{className:"checkbox-label custom-provider-form__toggle",children:[t.jsx("input",{type:"checkbox",checked:!!E.reasoning,onChange:L=>v(R,{reasoning:L.target.checked}),disabled:a}),"Reasoning"]}),t.jsx("input",{className:"input","aria-label":`Context window ${R+1}`,placeholder:"Context window",type:"number",value:E.contextWindow??"",onChange:L=>v(R,{contextWindow:L.target.value?Number(L.target.value):void 0}),disabled:a}),t.jsx("input",{className:"input","aria-label":`Max tokens ${R+1}`,placeholder:"Max tokens",type:"number",value:E.maxTokens??"",onChange:L=>v(R,{maxTokens:L.target.value?Number(L.target.value):void 0}),disabled:a}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>j(R),disabled:a||!k,"aria-label":`Remove model ${R+1}`,children:"×"})]},`${R}-model`))}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>b(E=>[...E,kf()]),disabled:a,children:"+ Add model"})]}),C?t.jsx("div",{className:"form-error",children:C}):null,t.jsxs("div",{className:"custom-provider-form__actions",children:[s?t.jsx("button",{type:"button",className:"btn",onClick:s,disabled:a,children:"Cancel"}):null,t.jsx("button",{type:"submit",className:"btn btn-primary",disabled:a,children:a?"Saving...":"Save Provider"})]})]})}const yD=new Set(["google-antigravity","antigravity","google-gemini-cli"]);function wD(e){return!yD.has(e)}function jf(e){return e.filter(n=>wD(n.id))}const Bx={host:"web",activeProfileId:null,profiles:[]},Hx=i.createContext({shellApi:null,state:Bx,ready:!0,openConnectionManagerSignal:0});function kD({children:e}){const n=i.useMemo(()=>typeof window<"u"?window.fusionShell??null:null,[]),[s,a]=i.useState(Bx),[r,o]=i.useState(!n),[l,c]=i.useState(0);return i.useEffect(()=>{if(!n)return;let d=!1;n.getState().then(h=>{d||(a(h),o(!0))});const u=n.subscribe(h=>{a(h)}),m=()=>{c(h=>h+1)};return window.addEventListener("shell:open-connection-manager",m),()=>{d=!0,u(),window.removeEventListener("shell:open-connection-manager",m)}},[n]),t.jsx(Hx.Provider,{value:{shellApi:n,state:s,ready:r,openConnectionManagerSignal:l},children:e})}function jD(){return i.useContext(Hx)}const ND={host:"web",activeProfileId:null,profiles:[]};function SD(e){if(!e)return ND;const n=Array.isArray(e.profiles)?e.profiles.filter(a=>!!(a&&a.id&&a.serverUrl)):[],s=e.activeProfileId&&n.some(a=>a.id===e.activeProfileId)?e.activeProfileId:null;return{...e,activeProfileId:s,profiles:n}}function qu(e){return new Error(`${e} is only available in native shell mode`)}async function CD(e,n){if(!e)throw qu("Saving connection profiles");return e.saveProfile(n)}async function ED(e,n){if(!e)throw qu("Deleting connection profiles");await e.deleteProfile(n)}async function _D(e,n){if(!e)throw qu("Switching connection profiles");return e.setActiveProfile(n)}function qx(){const e=jD(),n=i.useMemo(()=>SD(e.state),[e.state]),s=i.useCallback(o=>CD(e.shellApi,o),[e.shellApi]),a=i.useCallback(o=>ED(e.shellApi,o),[e.shellApi]),r=i.useCallback(o=>_D(e.shellApi,o),[e.shellApi]);return{...e,state:n,saveProfile:s,removeProfile:a,setActiveProfile:r}}const Ma="fusion_model_onboarding_state",xr=[],vr=[],Fl=!1,Ul=!1,yr={},MD=void 0,Zi=["ai-setup","github","project-setup","first-task"],AD={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function Js(){if(typeof window>"u")return null;try{const e=localStorage.getItem(Ma);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?PD(n):null}catch{return null}}function PD(e){const n=e.postOnboardingDismissedAt??MD;return{...e,completedSteps:e.completedSteps??xr,skippedSteps:e.skippedSteps??vr,dismissed:e.dismissed??Fl,completed:e.completed??Ul,stepData:e.stepData??yr,...n?{postOnboardingDismissedAt:n}:{}}}function hl(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:xr,skippedSteps:vr,dismissed:Fl,completed:Ul,stepData:yr};try{localStorage.setItem(Ma,JSON.stringify(s))}catch{}return}try{const s=Js(),a=new Date().toISOString(),r=n.completed??Ul;let o=n.dismissed??Fl;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??xr,c=n.skippedSteps??s?.skippedSteps??vr,d={...s?.stepData??yr};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(Ma,JSON.stringify(u))}catch{}}}function RD(e){if(!(typeof window>"u"))try{const n=Js(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:xr,skippedSteps:[e],dismissed:Fl,completed:Ul,stepData:yr};localStorage.setItem(Ma,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(Ma,JSON.stringify(r))}catch{}}function Nf(){if(!(typeof window>"u"))try{const e=Js(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:xr,skippedSteps:vr,dismissed:!1,completed:!0,stepData:yr};localStorage.setItem(Ma,JSON.stringify(s))}catch{}}function wr(){const e=Js();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function ID(){if(!(typeof window>"u"))try{const e=Js(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:xr,skippedSteps:vr,dismissed:!1,completed:!1,stepData:yr,postOnboardingDismissedAt:n};localStorage.setItem(Ma,JSON.stringify(s))}catch{}}function Vx(){const e=Js();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function TD(){const e=Js();return!e||wr()?!1:e.currentStep!=="complete"}function $D(){const e=Js();if(!e||wr()||e.currentStep==="complete")return null;const n=e.currentStep,s=AD[n]??OD(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function DD(){const e=Js();return e?e.skippedSteps:vr}function LD(e){const n=Js();return!n||!n.stepData?null:n.stepData[e]??null}function OD(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const Wx="fusion_onboarding_events",Sf="fusion_onboarding_session_id",zD=200,FD=50;function ei(e,n={}){if(!(typeof window>"u"))try{const s=BD(),a=VD(n.step),r={type:e,timestamp:new Date().toISOString(),...a?{step:a}:{},metadata:n,sessionId:UD()},o=qD([...s,r]);HD(o)}catch{}}function UD(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(Sf);if(e)return e;const n=Cf();return sessionStorage.setItem(Sf,n),n}catch{return Cf()}}function Cf(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function BD(){try{const e=localStorage.getItem(Wx);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(WD):[]}catch{return[]}}function HD(e){try{localStorage.setItem(Wx,JSON.stringify(e))}catch{}}function qD(e){const n=[...e];for(;n.length>zD;)n.splice(0,FD);return n}function VD(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function WD(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 KD=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}))??[]}),GD={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"}}},Kx={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:"..."}},JD={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},Ef={anthropic:"Anthropic",openai:"OpenAI","openai-codex":"OpenAI Codex",openrouter:"OpenRouter",google:"Google",gemini:"Gemini",minimax:"MiniMax",ollama:"Ollama",zai:"Zhipu AI",kimi:"Kimi","kimi-coding":"Kimi Coding",moonshot:"Moonshot"};function eu(e){if(Ef[e])return Ef[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 bd=["anthropic","openai","google","gemini","ollama"],YD=["anthropic","claude-cli","droid-cli","cursor-cli","llama-cpp","openai-codex","gemini","minimax","kimi","zai"],QD={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"},XD={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function tu(e){return QD[e]??e}function _f(e){const n=tu(e),s=YD.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function Mf(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=_f(e.id),a=_f(n.id);if(s!==a)return s-a;const r=tu(e.id),o=tu(n.id);if(r!==o)return r.localeCompare(o);const l=XD[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 ZD(e,n){const s=n.trim();if(!s)return"API key is required";const a=Kx[e]??JD;return a.pattern.test(s)?null:`${eu(e)} keys should follow this format: ${a.hint} (e.g. ${a.example})`}const Gx={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"},eL={description:"AI provider — connect to start using AI models",apiKeyInfo:Gx};function nu(e){return GD[e]??eL}function tL(e){return nu(e.id).apiKeyInfo??Gx}function nL({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 sL({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=Kx[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(ti,{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(ti,{summary:"Advanced setup details",children:g})]})}const iL=150;function aL({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:a,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const d=Js(),u=d?.currentStep,m=u==="complete"?"ai-setup":Zi.includes(u)?u:"ai-setup",h=d?.completedSteps??[],f=d?.skippedSteps??DD(),[p,g]=i.useState(!0),[x,w]=i.useState(m),[b,y]=i.useState(h),[S,k]=i.useState(f),[C,v]=i.useState(!1),[j,P]=i.useState(""),[U,E]=i.useState(!1),[R,L]=i.useState(null),[F,M]=i.useState(null),[O,q]=i.useState([]),[te,Z]=i.useState(void 0),[K,A]=i.useState(!0),[I,$]=i.useState(null),[N,G]=i.useState({}),[ge,je]=i.useState({}),[ke,ne]=i.useState({}),[qe,ee]=i.useState(null),[le,se]=i.useState([]),[re,J]=i.useState(""),[B,ve]=i.useState(!1),[Ne,H]=i.useState({}),[be,ce]=i.useState({}),[Me,Le]=i.useState({}),[He,gt]=i.useState([]),[Ue,pe]=i.useState(!1),[Oe,ze]=i.useState(!1),[lt,Be]=i.useState(),[ye,Y]=i.useState("Remote Server"),[_e,ct]=i.useState(""),[pt,de]=i.useState(""),[Ve,Ee]=i.useState(!1),[$e,ut]=i.useState(null),ht=i.useRef({}),Se=i.useRef(null),we=i.useRef(null),Ae=i.useRef(null),[he,We]=i.useState({}),[me,nt]=i.useState(()=>Js()?.stepData?.github?.skipped===!0),Ct=i.useRef(0),wt=i.useRef(l),{shellApi:$t,state:Vt}=qx(),Mt=i.useRef(!1),Dt=d?.currentStep,Qt=!!d&&d.currentStep!=="complete";Ai(we,p,"fusion:model-onboarding-modal-size"),i.useEffect(()=>{const _=Se.current;_&&(_.scrollTop=0)},[x]);const[Kt,Bt]=i.useState(()=>Js()?.stepData?.["ai-setup"]?.skippedProviders??{}),on=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],fn=on.findIndex(_=>_.key===x),Jt=x==="complete"?on.length:fn;i.useEffect(()=>{x!=="complete"&&hl(x,{completedSteps:b,skippedSteps:S})},[x,b,S]),i.useEffect(()=>{Mt.current||(Mt.current=!0,ei("onboarding:wizard-opened",{source:Qt?"resume":"initial",resumedFromStep:Dt}))},[Qt,Dt]),i.useEffect(()=>{const _=wt.current!=null,oe=l!=null;!_&&oe&&v(!0),oe||v(!1),wt.current=l},[l]);const an=i.useRef(m);i.useEffect(()=>{if(an.current==="ai-setup"&&x!=="ai-setup"&&!O.some(oe=>oe.id!=="github"&&oe.authenticated)){const oe={};for(const D of O)D.id!=="github"&&!D.authenticated&&!Kt[D.id]&&(oe[D.id]=!0);if(Object.keys(oe).length>0){const D={...Kt,...oe};Bt(D),hl(x,{stepData:{"ai-setup":{skippedProviders:D}}})}}an.current=x},[x,O,Kt]);const zt=i.useCallback(async()=>{try{const{providers:_,ghCli:oe}=await uo(),D=jf(_);q(D),Z(oe),G(Q=>{const Ce={};for(const[Je,kt]of Object.entries(Q)){const Tt=D.find(Pt=>Pt.id===Je);Tt&&!Tt.authenticated&&Tt.loginInProgress&&(Ce[Je]=kt)}return Object.keys(Ce).length===Object.keys(Q).length?Q:Ce}),We(Q=>{let Ce=!1;const Je={...Q};for(const[kt,Tt]of Object.entries(Q)){if(Tt!=="pending")continue;D.find(ln=>ln.id===kt)?.loginInProgress||(delete Je[kt],Ce=!0)}return Ce?Je:Q}),Bt(Q=>{const Ce={...Q};for(const Je of D)Je.authenticated&&Ce[Je.id]&&delete Ce[Je.id];return Object.keys(Ce).length===Object.keys(Q).length?Q:Ce})}catch{}},[]),en=i.useCallback(async()=>{try{const _=await xj();gt((_.providers??[]).map(KD))}catch{}},[]),Zt=i.useCallback(async _=>{ze(!0),Be(void 0);try{await yj(_),await en(),await Os().then(oe=>se(oe.models??[])),pe(!1)}catch(oe){Be(Re(oe)||"Failed to create custom provider")}finally{ze(!1)}},[en]),dn=i.useRef(!1);i.useEffect(()=>{x==="ai-setup"&&en(),dn.current&&zt(),dn.current=x!=="ai-setup"},[x,zt,en]),i.useEffect(()=>{if(!O.some(D=>D.loginInProgress))return;const oe=setInterval(()=>{zt()},2e3);return()=>clearInterval(oe)},[O,zt]);const xe=O.find(_=>_.id==="github"),Fe=!!xe,Ke=xe?.authenticated??!1,et=xe?.loginInProgress??!1,Qe=te?.authenticated??!1,It=Ke||Qe,St=!Ke&&Qe,Ht=i.useCallback(_=>{if(_.authenticated)return"connected";const oe=he?.[_.id];return oe==="timeout"||oe==="failed"?"retry":Kt[_.id]?"skipped":"not-connected"},[he,Kt]);function jt({status:_}){const oe={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:D,className:Q}=oe[_];return t.jsx("span",{"data-testid":"provider-status-badge",className:Q,"data-status":_,children:D})}const ae=i.useCallback(()=>{if(It)return"connected";const _=he.github;return _==="pending"?"pending":_==="failed"||_==="timeout"?"failed":me?"skipped":"not-connected"},[It,he,me]);function De({status:_}){const oe={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:D,className:Q}=oe[_];return t.jsx("span",{"data-testid":"github-status-badge",className:Q,"data-status":_,children:D})}const At=i.useCallback(async()=>{try{const _=await Os();se(_.models)}catch{}},[]),Lt=i.useCallback(async()=>{try{const _=await Pa();if(_.defaultProvider&&_.defaultModelId){const oe=`${_.defaultProvider}/${_.defaultModelId}`;J(oe)}}catch{}},[]);i.useEffect(()=>{Promise.all([zt(),At(),Lt()]).finally(()=>A(!1))},[zt,At,Lt]),i.useEffect(()=>{const _=LD("ai-setup");if(_?.loginOutcomes){const oe=_.loginOutcomes,D={};for(const[Q,Ce]of Object.entries(oe))Ce!=="pending"&&(D[Q]=Ce);Object.keys(D).length>0&&We(D)}},[]);const Ft=i.useCallback((_,oe)=>{hl(x,{completedSteps:b,stepData:{"ai-setup":{loginOutcomes:{[_]:oe}}}})},[x,b]);i.useEffect(()=>{const _=Object.entries(he).filter(([oe,D])=>D!=="pending");for(const[oe,D]of _)Ft(oe,D)},[he,Ft]),i.useEffect(()=>()=>{Ae.current&&clearInterval(Ae.current),Object.values(ht.current).forEach(clearTimeout),ht.current={}},[]);const Pe=i.useCallback(_=>{nt(_),hl(x,{completedSteps:b,stepData:{github:{skipped:_}}})},[x,b]),dt=i.useCallback(_=>_==="complete"?-1:Zi.indexOf(_),[]),bt=i.useCallback(()=>{y(oe=>[...new Set([...oe,x])]),k(oe=>oe.filter(D=>D!==x)),ei("onboarding:step-completed",{step:x}),x==="github"&&!Ke&&Pe(!1);const _=dt(x);_>=0&&_<Zi.length-1&&w(Zi[_+1])},[x,Ke,Pe,dt]),_t=i.useCallback(()=>{k(oe=>[...new Set([...oe,x])]),RD(x),ei("onboarding:step-skipped",{step:x}),x==="github"&&!Ke&&Pe(!0);const _=dt(x);_>=0&&_<Zi.length-1&&w(Zi[_+1])},[x,Ke,Pe,dt]),Yt=i.useCallback(()=>{const _=x;y(D=>D.filter(Q=>Q!==_)),k(D=>D.filter(Q=>Q!==_)),_==="github"&&!Ke&&Pe(!1);const oe=dt(x);oe>0&&w(Zi[oe-1])},[x,Ke,Pe,dt]),Xt=i.useCallback(()=>{_t()},[_t]),Te=i.useCallback(async _=>{We(D=>{const Q=D[_];if(Q&&Q!=="pending"){const{[_]:Ce,...Je}=D;return Je}return D});const oe=()=>{G(D=>{if(!(_ in D))return D;const Q={...D};return delete Q[_],Q}),je(D=>{if(!(_ in D))return D;const Q={...D};return delete Q[_],Q}),ne(D=>{if(!(_ in D))return D;const Q={...D};return delete Q[_],Q})};oe(),We(D=>({...D,[_]:"pending"})),$(_),Ct.current=0;try{const{url:D,instructions:Q,manualCode:Ce}=await wj(_);Q?.trim()&&G(Je=>({...Je,[_]:Q})),Ce&&je(Je=>({...Je,[_]:Ce})),window.open(Mi(D),"_blank"),Ae.current=setInterval(async()=>{if(Ct.current++,Ct.current>=iL){Ae.current&&(clearInterval(Ae.current),Ae.current=null),$(null),q(Je=>Je.map(kt=>kt.id===_?{...kt,loginInProgress:!1}:kt)),We(Je=>({...Je,[_]:"timeout"})),oe(),n("Login timed out. Please try again.","warning");return}try{const{providers:Je,ghCli:kt}=await uo(),Tt=jf(Je);q(Tt),Z(kt);const Pt=Tt.find(ln=>ln.id===_);if(Pt?.authenticated){Ae.current&&(clearInterval(Ae.current),Ae.current=null),$(null),We(ln=>({...ln,[_]:"success"})),oe(),_==="github"&&Pe(!1),n("Login successful","success");return}Pt?.loginInProgress||(Ae.current&&(clearInterval(Ae.current),Ae.current=null),$(null),We(ln=>({...ln,[_]:"failed"})),oe(),n("Login did not complete. Please try again.","error"))}catch{}},2e3)}catch(D){D instanceof Error&&D.message.includes("already in progress")||D&&typeof D=="object"&&"status"in D&&D.status===409?(n("Login already in progress. Cancel it to retry.","warning"),We(Ce=>({...Ce,[_]:"pending"})),zt()):(n(D instanceof Error?D.message:"Login failed","error"),We(Ce=>({...Ce,[_]:"failed"}))),$(null),oe()}},[n,zt,Pe]),Ye=i.useCallback(async _=>{const oe=ke[_]?.trim();if(!oe){n("Paste the full redirect URL or authorization code first.","warning");return}ee(_);try{(await kj(_,oe)).submitted?(ne(Q=>{if(!(_ in Q))return Q;const Ce={...Q};return delete Ce[_],Ce}),n("Authorization code received. Finishing login…","success")):n("That authorization code was already submitted. Waiting for login…","warning")}catch(D){n(Re(D)||"Failed to submit authorization code","error")}finally{ee(null)}},[n,ke]),Nt=i.useCallback(async _=>{Ae.current&&(clearInterval(Ae.current),Ae.current=null),$(_),Ct.current=0,q(oe=>oe.map(D=>D.id===_?{...D,loginInProgress:!1}:D)),We(oe=>({...oe,[_]:"cancelled"}));try{await Nj(_),await zt().catch(()=>{}),n("Login cancelled","success")}catch(oe){n(Re(oe)||"Failed to cancel login","error")}finally{$(null),G(oe=>{if(!(_ in oe))return oe;const D={...oe};return delete D[_],D}),je(oe=>{if(!(_ in oe))return oe;const D={...oe};return delete D[_],D}),ne(oe=>{if(!(_ in oe))return oe;const D={...oe};return delete D[_],D}),ee(oe=>oe===_?null:oe)}},[n,zt]),Ut=i.useCallback((_,oe)=>{H(Q=>({...Q,[_]:oe}));const D=ht.current[_];D&&(clearTimeout(D),delete ht.current[_]),ce(Q=>{if(!Q[_])return Q;const Ce={...Q};return delete Ce[_],Ce}),Le(Q=>{if(!Q[_])return Q;const Ce={...Q};return delete Ce[_],Ce})},[]),tn=i.useCallback(()=>{const _=Se.current;if(!_)return;const oe=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof _.scrollTo=="function"){_.scrollTo({top:0,behavior:oe?"auto":"smooth"});return}}catch{}_.scrollTop=0},[]),Xn=i.useCallback(async(_,oe)=>{const D=(oe??Ne[_]??"").trim(),Q=ZD(_,D);if(Q){ce(Je=>({...Je,[_]:Q}));return}const Ce=ht.current[_];Ce&&(clearTimeout(Ce),delete ht.current[_]),$(_),ce(Je=>{const kt={...Je};return delete kt[_],kt}),Le(Je=>{if(!Je[_])return Je;const kt={...Je};return delete kt[_],kt});try{await Sj(_,D),await zt(),tn(),H(Je=>{const kt={...Je};return delete kt[_],kt}),ce(Je=>{if(!Je[_])return Je;const kt={...Je};return delete kt[_],kt}),Le(Je=>({...Je,[_]:"✓ Key saved"})),ht.current[_]=setTimeout(()=>{Le(Je=>{if(!Je[_])return Je;const kt={...Je};return delete kt[_],kt}),delete ht.current[_]},3e3),n("API key saved","success")}catch(Je){const kt=Je instanceof TypeError&&Je.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":Je instanceof Error?Je.message:"Failed to save API key";ce(Tt=>({...Tt,[_]:kt})),Le(Tt=>{if(!Tt[_])return Tt;const Pt={...Tt};return delete Pt[_],Pt}),n(kt,"error")}finally{$(null)}},[Ne,n,zt,tn]),fe=i.useCallback(async _=>{$(_);try{await Cj(_),await zt(),n("API key removed","success")}catch(oe){n(oe instanceof Error?oe.message:"Failed to clear API key","error")}finally{$(null)}},[n,zt]),at=i.useCallback(async _=>{$(_);try{await jj(_),await zt(),n("Logged out","success")}catch(oe){n(oe instanceof Error?oe.message:"Logout failed","error")}finally{$(null)}},[n,zt]),ot=i.useCallback(_=>{J(_)},[]),rt=i.useCallback(async()=>{try{const _={modelOnboardingComplete:!0};if(re){const oe=re.indexOf("/"),D=oe!==-1?re.slice(0,oe):void 0,Q=oe!==-1?re.slice(oe+1):re,Ce=le.find(Je=>Je.id===Q);Ce?(_.defaultProvider=Ce.provider,_.defaultModelId=Ce.id):D&&Q&&(_.defaultProvider=D,_.defaultModelId=Q)}await kn(_),Nf()}catch{}},[re,le,kn,Nf]),mt=i.useCallback(async()=>{const _=[...new Set([...b,"first-task"])];ve(!0);try{await rt(),ei("onboarding:completed",{completedSteps:_,skippedSteps:S}),y(_),k(oe=>oe.filter(D=>D!=="first-task")),w("complete")}finally{ve(!1)}},[rt,b,S]),vt=i.useCallback(async()=>{if(!s)return;const _=j.trim();if(!_){L("Please enter a task description.");return}L(null),E(!0);let oe=!1;try{const D=await wg({description:_,source:{sourceType:"dashboard_ui"}},s);M(D),v(!0),ei("onboarding:first-task-created",{taskId:D?.id}),n("Task created","success"),oe=!0}catch(D){const Q=D instanceof Error?D.message:"Something went wrong creating your task. Please try again.";L(Q),n(Q,"error")}finally{E(!1)}oe&&rt()},[s,j,n,rt]),ie=i.useCallback(async()=>{ve(!0);try{await rt()}finally{ve(!1)}ei("onboarding:open-new-task",{}),r?.()},[rt,r]),it=i.useCallback(async()=>{if(It){ve(!0);try{await rt()}finally{ve(!1)}g(!1),e(),ei("onboarding:open-github-import",{}),o?.()}},[rt,It,e,o]),Gt=i.useCallback(async()=>{ei("onboarding:dismissed",{currentStep:x,completedSteps:b,skippedSteps:S}),ve(!0);try{await kn({modelOnboardingComplete:!0})}catch{}g(!1),e()},[x,b,S,e]),Cn=i.useCallback(()=>{ei("onboarding:finished",{}),g(!1),e()},[e]),fs=i.useCallback(()=>{const _=l??F;_&&(rt(),c?.(_),e())},[l,F,rt,c,e]),On=i.useCallback(()=>{rt(),e()},[rt,e]),jn=ae(),zn=O.filter(_=>_.id!=="github"),hn=Vt.host!=="web"&&!Vt.activeProfileId,Et=[...zn].sort(Mf),En=Et.some(_=>!_.type||_.type==="oauth"),yn=Et.some(_=>_.type==="api_key"),ls=zn.filter(_=>_.authenticated),cs=ls.length>0,Hn=!!s,qn=x==="github"&&!cs,wn=i.useCallback(async()=>{if($t){ut(null),Ee(!0);try{const _=await $t.saveProfile({name:ye,serverUrl:_e,authToken:pt.trim()?pt:null});try{await $t.setActiveProfile(_.id)}catch(oe){ut(Re(oe)||"Saved profile but failed to activate it");return}ct(""),de(""),n("Remote server profile saved","success")}catch(_){ut(Re(_)||"Failed to save shell connection")}finally{Ee(!1)}}},[$t,ye,_e,pt,n]);if(!p)return null;const Zn=(()=>{if(!re)return"";const _=re.indexOf("/"),oe=_===-1?void 0:re.slice(0,_),D=_===-1?re:re.slice(_+1),Q=le.find(Ce=>Ce.id===D&&(!oe||Ce.provider===oe));return Q?.name?Q.name:oe?`${eu(oe)} ${D}`:re})(),_n=[];if(Hn?_n.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):_n.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),cs){const _=eu(ls[0]?.id??"");_n.push({label:"AI Provider",status:"connected",detail:`${_} connected — AI agents can work on tasks`})}else zn.length>0&&zn.some(_=>Kt[_.id])?_n.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):_n.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});It?_n.push({label:"GitHub",status:"connected",detail:St?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!Fe||me?_n.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):_n.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),Zn&&_n.push({label:"Default Model",status:"connected",detail:Zn});const ss=l??F,Ns=ss?.description?.split(`
|
|
692
|
+
`)[0]?.trim()||ss?.title||"",es=new Set(bd),ks=Et.filter(_=>es.has(_.id)).sort((_,oe)=>{const D=bd.indexOf(_.id),Q=bd.indexOf(oe.id);return D!==Q?D-Q:Mf(_,oe)}),Is=Et.filter(_=>_.authenticated&&!es.has(_.id)),Ss=Et.filter(_=>!_.authenticated&&!es.has(_.id)),X=_=>{const oe=he[_.id]==="timeout"||he[_.id]==="failed"||he[_.id]==="cancelled",D=_.loginInProgress&&!oe;if(_.id==="llama-cpp"&&_.type==="cli")return t.jsx(pD,{authenticated:_.authenticated,onToggled:()=>{zt()}},_.id);if(_.id==="claude-cli"&&_.type==="cli")return t.jsx(uD,{authenticated:_.authenticated,onToggled:()=>{zt()}},_.id);if(_.id==="cursor-cli"&&_.type==="cli")return t.jsx(hD,{authenticated:_.authenticated,onToggled:()=>{zt()}},_.id);if(_.type==="api_key"){const Q=nu(_.id),Ce=tL(_);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${_.id}`,className:`onboarding-provider-card${_.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${_.id}`,"aria-hidden":"true",children:t.jsx(Sn,{provider:_.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(pg,{size:14,className:"onboarding-provider-key-icon"}),_.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:Q.description}),t.jsx(jt,{status:Ht(_)}),_.authenticated&&_.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",_.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(sL,{provider:_,apiKeyInfo:Ce,inputValue:Ne[_.id]??"",isSaving:I===_.id,error:be[_.id],success:Me[_.id],isConnected:_.authenticated,onInputChange:Ut,onSave:Xn,onClear:fe})})]},_.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${_.id}`,className:`onboarding-provider-card${_.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${_.id}`,"aria-hidden":"true",children:t.jsx(Sn,{provider:_.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:_.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:nu(_.id).description}),t.jsx(jt,{status:Ht(_)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:I===_.id?_.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 Nt(_.id),children:"Cancel"})]}):D?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 Nt(_.id),children:"Cancel"})]}):_.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>at(_.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>Te(_.id),children:"Login"})}),(I===_.id||D)&&N[_.id]&&t.jsx(gd,{instructions:N[_.id],"data-testid":`onboarding-login-instructions-${_.id}`}),(I===_.id||D)&&ge[_.id]&&t.jsx(gD,{value:ke[_.id]??"",onChange:Q=>ne(Ce=>({...Ce,[_.id]:Q})),onSubmit:()=>void Ye(_.id),prompt:ge[_.id].prompt,placeholder:ge[_.id].placeholder,helpText:ge[_.id].helpText,disabled:qe===_.id,submitLabel:qe===_.id?"Submitting…":"Submit code","data-testid":`onboarding-manual-code-${_.id}`}),he[_.id]==="timeout"&&I!==_.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),he[_.id]==="failed"&&I!==_.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},_.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(Qn,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(Ws,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Ju,{size:24})," Set Up Your Project"]}),x==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(Ju,{size:24})," Create Your First Task"]}),x==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx($n,{size:24})," All Set!"]})]}),x!=="complete"&&t.jsx("button",{className:"modal-close",onClick:Gt,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(nn,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:on.map((_,oe)=>{const D=Jt>oe,Q=b.includes(_.key)&&D,Ce=S.includes(_.key)&&!b.includes(_.key)&&D,Je=Q||Ce;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[oe>0&&t.jsx("div",{className:`model-onboarding-step-connector ${oe<=Jt?"done":""}`}),Je?t.jsxs("button",{className:`model-onboarding-step-indicator ${x===_.key?"active":""} ${Q?"done":""} ${Ce?"skipped":""}`,onClick:()=>w(_.key),"aria-label":`Go back to ${_.label}`,title:`Review ${_.label}`,children:[t.jsx("span",{className:"step-number",children:Q?t.jsx($n,{size:14}):Ce?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):oe+1}),t.jsx("span",{className:"step-label",children:_.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${x===_.key?"active":""} ${Q?"done":""} ${Ce?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:Q?t.jsx($n,{size:14}):Ce?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):oe+1}),t.jsx("span",{className:"step-label",children:_.label})]})]},_.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:Se,children:[x==="ai-setup"&&t.jsxs("div",{className:"model-onboarding-ai-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Fusion uses AI models to plan, write, and review code for you. Connect an AI provider below to get started — you can use a hosted service or enter an API key."}),t.jsx("p",{className:"onboarding-helper-text model-onboarding-primary-helper",children:"You only need one provider to get started."}),t.jsx("p",{className:"onboarding-helper-text",children:"Research runs require provider credentials and an enabled Research View. After onboarding, verify these in Settings → Authentication and Settings → Experimental Features."}),hn&&t.jsxs("div",{className:"card",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Connect remote Fusion server"}),t.jsx("p",{className:"onboarding-helper-text",children:"Your native shell needs an active remote profile before dashboard handoff can complete."}),t.jsx("label",{htmlFor:"onboarding-shell-profile-name",className:"onboarding-apikey-field-label",children:"Profile name"}),t.jsx("input",{id:"onboarding-shell-profile-name",className:"input",value:ye,onChange:_=>Y(_.target.value)}),t.jsx("label",{htmlFor:"onboarding-shell-server-url",className:"onboarding-apikey-field-label",children:"Server URL"}),t.jsx("input",{id:"onboarding-shell-server-url",className:"input",placeholder:"https://your-fusion-host",value:_e,onChange:_=>ct(_.target.value)}),t.jsx("label",{htmlFor:"onboarding-shell-token",className:"onboarding-apikey-field-label",children:"Auth token (optional)"}),t.jsx("input",{id:"onboarding-shell-token",className:"input",type:"password",value:pt,onChange:_=>de(_.target.value)}),$e&&t.jsx("small",{className:"field-error",children:$e}),t.jsxs("div",{className:"onboarding-apikey-input-row",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void $t?.openConnectionManager(),children:"Open manager"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void wn(),disabled:!_e.trim()||Ve,children:Ve?"Saving…":"Save remote server"})]})]}),!K&&O.length>0&&(()=>{const _=O.filter(Je=>Je.id!=="github"&&Je.authenticated).length,oe=O.filter(Je=>Je.id!=="github").length,D=Object.keys(Kt).filter(Je=>!O.find(kt=>kt.id===Je)?.authenticated).length;if(oe===0)return null;let Q="onboarding-provider-summary",Ce="";return _>0?(Q+=" onboarding-provider-summary--connected",Ce=`✓ ${_} of ${oe} provider${oe!==1?"s":""} connected`):D>0?(Q+=" onboarding-provider-summary--skipped",Ce=`${D} provider${D!==1?"s":""} skipped`):(Q+=" onboarding-provider-summary--none",Ce="No providers connected yet"),t.jsx("div",{className:Q,"data-testid":"provider-summary",children:Ce})})(),t.jsx(ta,{slotId:"onboarding-recommendation-card",projectId:s}),t.jsx(ti,{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."})}),O.length>0&&!O.some(_=>_.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),K?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(xt,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):O.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(ta,{slotId:"onboarding-provider-card",projectId:s,renderPlaceholder:!1,actions:{refreshAuthProviders:()=>{zt()}}}),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"}),ks.length>0?t.jsx("div",{className:"model-onboarding-providers",children:ks.map(_=>X(_))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),Is.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:Is.map(_=>X(_))})]}),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(ti,{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."})}),le.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(ys,{models:le,value:re,onChange:ot,placeholder:"Select a default model…",label:"Default model"})}),re&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",le.find(_=>_.id===re)?.name??re]})})]}),t.jsx(ti,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsxs("div",{"data-testid":"onboarding-advanced-provider-settings",children:[Ss.length>0?t.jsx("div",{className:"model-onboarding-providers",children:Ss.map(_=>X(_))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."}),He.length>0?t.jsx("div",{className:"onboarding-custom-provider-list",children:He.map(_=>t.jsxs("div",{className:"onboarding-custom-provider-item",children:[t.jsx(Sn,{provider:_.id,size:"sm"}),t.jsx("span",{children:_.name||_.id})]},_.id))}):null,Ue?t.jsx(vD,{onSave:Zt,onCancel:()=>{pe(!1),Be(void 0)},saving:Oe,error:lt}):t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>pe(!0),children:"Add custom provider"})]})}),En&&t.jsx(ti,{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."})}),yn&&t.jsx(ti,{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(ta,{slotId:"onboarding-setup-help",projectId:s})]})]}),x==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[It?t.jsx("p",{className:"model-onboarding-description",children:St?"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."}),!It&&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"})]})}),qn&&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(ti,{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."})}),Fe?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(Ws,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(De,{status:jn})})]}),Ke&&(I==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>at("github"),children:"Disconnect"}))]}),(jn==="not-connected"||jn==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[I==="github"||et?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 Nt("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>Te("github"),children:[t.jsx(Ws,{size:16}),"Connect"]}),(I==="github"||et)&&N.github&&t.jsx(gd,{instructions:N.github,"data-testid":"onboarding-login-instructions-github"})]}),jn==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:St?"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."}),jn==="failed"&&t.jsxs("div",{className:"onboarding-github-feedback onboarding-github-feedback--error",children:[t.jsx("p",{children:"Connection failed or timed out."}),t.jsxs("div",{className:"onboarding-github-feedback-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>Te("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Xt,children:"Skip for now"})]})]}),jn==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),jn==="skipped"&&t.jsxs("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:[t.jsx("p",{children:"GitHub was skipped. You can connect anytime from Settings → Authentication."}),t.jsx("div",{className:"onboarding-github-feedback-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:()=>Te("github"),children:"Connect anyway"})})]}),jn==="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(Sn,{provider:"github",size:"lg"})}),St?t.jsx("p",{children:"GitHub CLI is already authenticated, so imports and PR tracking work now. OAuth from the dashboard is optional and only controls dashboard-managed connect/disconnect."}):t.jsx("p",{children:"GitHub OAuth isn't connected yet. You can set it up in Settings → Authentication, or continue now and connect later."}),t.jsxs("div",{className:"model-onboarding-github-optional__actions",children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>w("project-setup"),children:St?"Continue with gh CLI auth →":"Continue without GitHub →"}),St&&(I==="github"||et?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(xt,{size:14,className:"onboarding-spinner"}),"Waiting for OAuth login…"]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>Te("github"),children:[t.jsx(Sn,{provider:"github",size:"sm"}),"Connect OAuth (optional)"]}))]}),St&&(I==="github"||et)&&N.github&&t.jsx(gd,{instructions:N.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."}),Hn?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(ti,{summary:"What does project setup do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Project setup registers a workspace so Fusion knows where to read files, run commands, and track task changes."})})]}),x==="first-task"&&t.jsxs("div",{className:"model-onboarding-first-task",children:[t.jsx("p",{className:"model-onboarding-description",children:"Create your first task to start the board and launch AI execution."}),C&&ss?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx($n,{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:ss.id}),Ns&&t.jsx("p",{className:"onboarding-task-created__description",children:Ns}),t.jsx("p",{className:"onboarding-task-created__hint",children:"Your task has been created and will appear on the board."}),t.jsxs("div",{className:"onboarding-task-created__actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:fs,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:On,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[Hn?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"onboarding-first-task-form",children:[t.jsx("label",{className:"onboarding-first-task-form__label",htmlFor:"onboarding-first-task-input",children:"Describe your first task"}),t.jsx("textarea",{id:"onboarding-first-task-input",className:"input onboarding-first-task-form__input","data-testid":"onboarding-first-task-input",value:j,onChange:_=>{P(_.target.value),L(null)},placeholder:"Example: Build a login page with email and password",rows:4}),t.jsx("div",{className:"onboarding-first-task-form__actions",children:t.jsx("button",{type:"button",className:"btn btn-primary",onClick:vt,disabled:U,"data-testid":"onboarding-first-task-submit",children:U?t.jsxs(t.Fragment,{children:[t.jsx(xt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),R&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:R}),t.jsx("p",{className:"onboarding-helper-text",children:"Your text has been preserved — fix the issue and try again."})]})]}):t.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[t.jsx("p",{className:"onboarding-helper-text",children:"A project must be selected before you can create tasks or import from GitHub."}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:a,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"})]}),t.jsx(nL,{items:_n}),Hn&&t.jsxs(t.Fragment,{children:[t.jsx(ti,{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:ie,disabled:B,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(bn,{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${It?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:it,disabled:B||!It,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Ws,{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"}),!It&&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($n,{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:Gt,disabled:B,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:_t,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:bt,children:"Next →"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Yt,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:_t,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:bt,children:"Next →"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Yt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:bt,disabled:!Hn,children:"Next →"})]}),x==="first-task"&&!C&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Yt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:mt,disabled:B,children:B?t.jsxs(t.Fragment,{children:[t.jsx(xt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),x==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:Cn,children:[t.jsx($n,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function Jx({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 rL=i.lazy(()=>gn(()=>import("./SetupWizardModal-uUZk3TKT.js"),__vite__mapDeps([13,1,14,15,16,17,5,6,18])).then(e=>({default:e.SetupWizardModal}))),oL=i.lazy(()=>gn(()=>import("./SettingsModal-BeA_nQtW.js"),__vite__mapDeps([19,1,20,21,22,2,5,6,23])).then(e=>({default:e.SettingsModal})));function lL(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{gn(()=>import("./SettingsModal-BeA_nQtW.js"),__vite__mapDeps([19,1,20,21,22,2,5,6,23]))},{timeout:1500})}function cL({projectId:e,tasks:n,projects:s,currentProject:a,addToast:r,toasts:o,removeToast:l,modalManager:c,projectActions:d,taskHandlers:u,taskOperations:m,deepLink:h,settings:f,onSettingsClose:p,onReopenOnboarding:g}){const[x,w]=i.useState(null),b=c.detailTask?(()=>{const j=n.find(P=>P.id===c.detailTask?.id);return j?"prompt"in c.detailTask?{...c.detailTask,...j,prompt:c.detailTask.prompt,log:c.detailTask.log}:j:c.detailTask})():null,y=p??c.closeSettings,S=i.useCallback(()=>{c.openNewTask()},[c]),k=i.useCallback(()=>{c.openGitHubImport()},[c]),C=i.useCallback(j=>{w(null),c.closeModelOnboarding(),c.openDetailTask(j)},[c]),v=i.useCallback(async j=>{const P=await u.handleModalCreate(j);return c.modelOnboardingOpen&&w(P),P},[u.handleModalCreate,c.modelOnboardingOpen]);return i.useEffect(()=>{!c.modelOnboardingOpen&&x&&w(null)},[c.modelOnboardingOpen,x]),i.useEffect(()=>{lL()},[]),t.jsxs(t.Fragment,{children:[b&&t.jsx(ga,{children:t.jsx(AI,{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(ga,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(oL,{onClose:y,addToast:r,initialSection:c.settingsInitialSection,projectId:e,themeMode:f.themeMode,colorTheme:f.colorTheme,onThemeModeChange:f.setThemeMode,onColorThemeChange:f.setColorTheme,dashboardFontScalePct:f.dashboardFontScalePct,onDashboardFontScaleChange:f.setDashboardFontScalePct,onReopenOnboarding:g})})}),t.jsx(FT,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:u.handleGitHubImport,tasks:n,projectId:e}),t.jsx(ga,{children:t.jsx(qT,{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(ga,{children:t.jsx(e4,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:u.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(k4,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(N4,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(W4,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),c.todosOpen&&t.jsx(G4,{isOpen:!0,onClose:c.closeTodos,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan}),t.jsx(s$,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e,anchorRect:c.usageAnchorRect}),t.jsx(I$,{isOpen:c.systemStatsOpen,onClose:c.closeSystemStats,projectId:e}),c.schedulesOpen&&t.jsx(j$,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(ga,{children:t.jsx(E$,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:v,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(O$,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:a,onOpenTaskDetail:j=>{const P=n.find(U=>U.id===j);P&&c.openDetailTask(P)}}),t.jsx(ga,{children:t.jsx(F$,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(ga,{children:t.jsx(Y$,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(dD,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(i.Suspense,{fallback:null,children:t.jsx(rL,{onProjectRegistered:d.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(aL,{onComplete:d.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:d.handleAddProject,onOpenNewTask:S,onOpenGitHubImport:k,firstCreatedTask:x,onViewTask:C}),t.jsx(Jx,{toasts:o,onRemove:l})]})}function dL({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 su=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function uL(e,n){if(n==="ready")return"done";const s=su.findIndex(r=>r.id===n),a=su.findIndex(r=>r.id===e);return a<s?"done":a===s?"active":"pending"}function mL({stage:e}){const[n]=i.useState(()=>mk());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:su.map(s=>{const a=uL(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(xt,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:s.label})]},s.id)})})]})})}const hL=5e3;function pL(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function fL(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++,Rl(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 gL(e,n,s,a){const[r,o]=i.useState({globalPause:!1,enginePaused:!1,maxConcurrent:2}),[l,c]=i.useState(!0),[d,u]=i.useState(null),m=i.useRef(null),h=i.useRef(null),f=i.useCallback(async()=>{h.current&&h.current.abort(),h.current=new AbortController;try{c(!0),u(null);const w=await bS(n);o(w)}catch(w){if(w instanceof Error&&w.name==="AbortError")return;u(w instanceof Error?w.message:"Failed to fetch executor stats")}finally{c(!1)}},[n]);i.useEffect(()=>(f(),()=>{h.current&&h.current.abort()}),[f]),i.useEffect(()=>(m.current&&clearInterval(m.current),m.current=setInterval(()=>{f()},hL),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[f]);const p=fL(e,s,a),g=pL(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:g,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:d,refresh:f}}const bL={planning:_i,subtask:ja,mission_interview:vs,milestone_interview:vs,slice_interview:vs},xL={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function vL({sessions:e,generating:n,needsInput:s,onOpenSession:a,onDismissSession:r}){const{confirm:o}=ai(),[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}=_r(),g=i.useMemo(()=>Ia(),[]);if(i.useEffect(()=>{if(!l)return;const b=y=>{m.current&&!m.current.contains(y.target)&&c(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[l]),i.useEffect(()=>{const b=new Set,y=new Map;for(const S of e){const k=p.get(S.id),C=[S.status,S.updatedAt,k?.tabId??S.lockedByTab??"",k?.stale?"stale":"fresh"].join("|"),v=h.current.get(S.id);v&&v!==C&&b.add(S.id),y.set(S.id,C)}if(h.current=y,b.size!==0)return u(b),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{u(new Set),f.current=null},500),()=>{f.current&&(clearTimeout(f.current),f.current=null)}},[p,e]),e.length===0)return null;const x=e.length,w=s>0;return t.jsxs("div",{ref:m,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${w?" background-tasks-indicator__pill--attention":""}`,onClick:()=>c(b=>!b),title:`${x} background AI task${x!==1?"s":""}${s>0?` (${s} need${s!==1?"":"s"} input)`:""}`,children:[n>0&&t.jsx(xt,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(jd,{size:12}),t.jsxs("span",{children:["AI ",x]})]}),l&&t.jsxs("div",{className:"background-tasks-indicator__popover",children:[t.jsx("div",{className:"background-tasks-indicator__popover-header",children:"Background Tasks"}),t.jsx("div",{className:"background-tasks-indicator__popover-list",children:e.map(b=>{const y=bL[b.type],S=b.status==="generating",k=b.status==="awaiting_input",C=b.status==="error",v=p.get(b.id),j=v?.tabId??b.lockedByTab??null,P=!!(j&&j!==g&&!v?.stale),U=d.has(b.id);return t.jsxs("div",{className:`background-tasks-indicator__item${U?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:U?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:U?"translateY(-1px)":void 0},onClick:async()=>{P&&!await o({title:"Open Active Session",message:"This session is active in another tab. Open anyway?"})||(a(b),c(!1))},children:[C?t.jsx(Ps,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):t.jsx(y,{size:14,className:"background-tasks-indicator__session-icon"}),t.jsxs("div",{className:"background-tasks-indicator__session-content",children:[t.jsx("div",{className:"background-tasks-indicator__session-title",children:b.title}),t.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[C?"Failed":xL[b.type],S&&" — generating...",k&&!P&&" — needs input",k&&P&&" — active in another tab"]})]}),S&&t.jsx(xt,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),k&&!P&&t.jsx(jd,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),k&&P&&t.jsx(Yl,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:E=>{E.stopPropagation(),r(b.id)},title:"Dismiss",children:t.jsx(nn,{size:12})})]},b.id)})})]})]})}function yL(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 wL(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:Yn};case"paused":return{label:"Paused",color:"var(--triage)",icon:pi};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:Qn}}}function kL({tasks:e,projectId:n,taskStuckTimeoutMs:s,backgroundSessions:a,backgroundGenerating:r,backgroundNeedsInput:o,onOpenBackgroundSession:l,onDismissBackgroundSession:c,lastFetchTimeMs:d,currentProjectPath:u,onOpenProjectDirectory:m,keyboardOpen:h}){if(h)return null;const{stats:f,loading:p,error:g}=gL(e,n,s,d),[x,w]=i.useState(!1),b=i.useMemo(()=>wL(f.executorState),[f.executorState]),y=i.useMemo(()=>yL(f.lastActivityAt),[f.lastActivityAt]),S=b.icon;return g?t.jsx("div",{className:"executor-status-bar executor-status-bar--error",role:"status","aria-label":"Executor status",children:t.jsxs("span",{className:"executor-status-bar__error",children:[t.jsx(No,{size:14}),g]})}):p&&f.runningTaskCount===0?t.jsx("div",{className:"executor-status-bar executor-status-bar--loading",role:"status","aria-label":"Executor status",children:t.jsx("span",{className:"executor-status-bar__loading-text",children:"Loading..."})}):t.jsxs("div",{className:`executor-status-bar ${f.executorState==="running"?"executor-status-bar--running":""}`,role:"status","aria-label":"Executor status",children:[a&&a.length>0&&l&&c&&t.jsxs(t.Fragment,{children:[t.jsx(vL,{sessions:a,generating:r??0,needsInput:o??0,onOpenSession:l,onDismissSession:c}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--queued","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Queued"}),t.jsx("span",{className:"executor-status-bar__count",children:f.queuedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--running ${f.runningTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Running"}),t.jsx("span",{className:"executor-status-bar__count",children:f.runningTaskCount}),t.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),t.jsx("span",{className:"executor-status-bar__max",children:f.maxConcurrent})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),f.stuckTaskCount>0&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--stuck",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--stuck executor-status-bar__indicator--active","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Stuck"}),t.jsx("span",{className:"executor-status-bar__count executor-status-bar__count--error",children:f.stuckTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--blocked ${f.blockedTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Blocked"}),t.jsx("span",{className:`executor-status-bar__count ${f.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:f.blockedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--review","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"In Review"}),t.jsx("span",{className:"executor-status-bar__count",children:f.inReviewCount})]}),u&&m&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--project-directory",children:[t.jsx("button",{className:`executor-status-bar__folder-toggle${x?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>w(k=>!k),"aria-label":x?"Hide project directory":"Show project directory","aria-expanded":x,"data-testid":"executor-project-path-toggle",title:x?"Hide project directory":"Show project directory",children:t.jsx(bs,{size:12,"aria-hidden":"true"})}),x&&t.jsx("button",{className:"executor-status-bar__project-path",onClick:m,title:u,"data-testid":"executor-project-path-link",children:u})]})]}),t.jsx("div",{className:"executor-status-bar__spacer"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[t.jsx(Hi,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:y})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx(S,{size:12,style:{color:b.color},"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__state",style:{color:b.color},children:b.label})]})]})}const jL={planning:_i,subtask:ja,mission_interview:vs,milestone_interview:vs,slice_interview:vs},NL={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},Yx="fusion:session-banner-dismissed";function eo(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function SL(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(Yx);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:eo(r);s.set(a,o)}return s}catch{return new Map}}function CL(e){if(!(typeof window>"u"))try{const n={};for(const[s,a]of e)n[s]=a;window.localStorage.setItem(Yx,JSON.stringify(n))}catch{}}const zi=SL();function EL({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:a}){const[r,o]=i.useState(0),l=()=>{CL(zi),o(g=>g+1)};i.useEffect(()=>{if(zi.size===0)return;const g=new Map(e.map(w=>[w.id,w]));let x=!1;for(const[w,b]of zi){const y=g.get(w);if(!y)continue;if(!(y.status==="awaiting_input"||y.status==="error")){zi.delete(w),x=!0;continue}eo(y.updatedAt)>b&&(zi.delete(w),x=!0)}x&&l()},[e]);const c=i.useMemo(()=>e.filter(g=>{if(g.status!=="awaiting_input"&&g.status!=="error")return!1;const x=zi.get(g.id);return x===void 0?!0:eo(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=>{zi.set(g.id,Math.max(eo(g.updatedAt),Date.now())),l()},f=g=>{zi.delete(g.id),l(),n(g)},p=()=>{const g=Date.now();for(const x of c)zi.set(x.id,Math.max(eo(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(Ps,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(nn,{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=jL[g.type],w=g.status==="error";return t.jsxs("article",{className:`session-notification-banner__item${w?" session-notification-banner__item--error":""}`,"data-session-type":g.type,"data-session-status":g.status,children:[t.jsxs("div",{className:"session-notification-banner__item-main",children:[w?t.jsx(Ps,{size:16,className:"session-notification-banner__type-icon session-notification-banner__type-icon--error","aria-hidden":"true"}):t.jsx(x,{size:16,className:"session-notification-banner__type-icon","aria-hidden":"true"}),t.jsxs("div",{className:"session-notification-banner__text",children:[t.jsx("p",{className:"session-notification-banner__title",title:g.title,children:g.title}),t.jsx("p",{className:"session-notification-banner__meta",children:w?"Failed":NL[g.type]})]})]}),t.jsxs("div",{className:"session-notification-banner__actions",children:[t.jsx("button",{className:"session-notification-banner__resume",onClick:()=>f(g),children:w?"Retry":"Resume"}),t.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{h(g),s(g.id)},"aria-label":`Dismiss ${g.title}`,children:t.jsx(nn,{size:14,"aria-hidden":"true"})})]})]},g.id)})})]})}const Qx="fusion:cli-binary-banner-dismissed";function _L(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Qx)==="1"}catch{return!1}}function ML(){if(!(typeof window>"u"))try{window.localStorage.setItem(Qx,"1")}catch{}}function AL({onOpenSettings:e}){const[n,s]=i.useState(null),[a,r]=i.useState(()=>_L()),[o,l]=i.useState(!1),[c,d]=i.useState(null);i.useEffect(()=>{if(a)return;let y=!1;return cj().then(S=>{y||s(S)}).catch(()=>{}),()=>{y=!0}},[a]);const u=i.useCallback(async()=>{l(!0),d(null);try{const y=await dj();s({binary:y.binary,expectedVersion:y.expectedVersion,state:y.state,install:y.install}),y.installResult.success||d(y.installResult.permissionsHint||y.installResult.stderr||`Install failed (exit ${y.installResult.exitCode??"n/a"})`)}catch(y){d(y instanceof Error?y.message:String(y))}finally{l(!1)}},[]),m=i.useCallback(()=>{ML(),r(!0)},[]);if(a||!n||n.state==="installed"||n.state==="skipped")return null;const h=n.state==="version-mismatch",f=n.binary.version,p=n.expectedVersion,g=h?"Update the Fusion CLI":"Install the Fusion CLI",x=h?t.jsxs(t.Fragment,{children:["Your installed ",t.jsx("code",{children:"fn"}),"/",t.jsx("code",{children:"fusion"})," CLI is"," ",t.jsxs("strong",{children:["v",f??"unknown"]})," but this dashboard expects"," ",t.jsxs("strong",{children:["v",p]}),". Update to stay in sync."]}):t.jsxs(t.Fragment,{children:["Get the ",t.jsx("code",{children:"fn"})," and ",t.jsx("code",{children:"fusion"})," commands on your terminal so you can drive Fusion from anywhere. One click below or copy the command into your shell."]}),w=h?"Update with npm":"Install with npm",b=h?"Updating…":"Installing…";return t.jsxs("div",{className:"cli-binary-banner",role:"status",children:[t.jsxs("div",{className:"cli-binary-banner__body",children:[t.jsx("div",{className:"cli-binary-banner__title",children:g}),t.jsx("div",{className:"cli-binary-banner__text",children:x}),t.jsxs("div",{className:"cli-binary-banner__actions",children:[t.jsx("button",{type:"button",className:"cli-binary-banner__primary",onClick:()=>void u(),disabled:o,children:o?b:w}),t.jsx("button",{type:"button",className:"cli-binary-banner__secondary",onClick:e,children:"Open Settings"})]}),c&&t.jsx("div",{className:"cli-binary-banner__error",children:c})]}),t.jsx("button",{type:"button",className:"cli-binary-banner__dismiss","aria-label":"Dismiss",onClick:m,children:t.jsx(nn,{size:16})})]})}function PL({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(nn,{size:16,"aria-hidden":"true"})})]})}function RL({pendingCount:e,onOpenMailbox:n,onDismiss:s}){const a=e===1?"request":"requests";return t.jsx("section",{className:"approval-notification-banner",role:"region","aria-live":"polite","aria-label":"Approval requests",children:t.jsxs("div",{className:"approval-notification-banner__content",children:[t.jsxs("div",{className:"approval-notification-banner__headline",children:[t.jsx("span",{className:"status-dot","aria-hidden":"true"}),t.jsx(No,{"aria-hidden":"true"}),t.jsxs("span",{children:[e," approval ",a," need your attention"]})]}),t.jsxs("div",{className:"approval-notification-banner__actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:n,children:[t.jsx(ya,{"aria-hidden":"true"}),t.jsx("span",{children:"Open Mailbox"})]}),t.jsx("button",{type:"button",className:"btn-icon approval-notification-banner__dismiss",onClick:s,"aria-label":"Dismiss approval notification banner",children:t.jsx(nn,{"aria-hidden":"true"})})]})]})})}function IL({onResume:e}){const n=$D();if(!n)return null;const s=n.completedSteps.length,a=Zi.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(ps,{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:()=>{ei("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(Yn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function TL({onOpenSettings:e,onOpenModelOnboarding:n}){const s=wr(),a=Vx(),[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,k]=await Promise.all([uo(),Pa()]);if(b)return;const C=S.providers??[],v=C.find(R=>R.id==="github"),P=!C.some(R=>R.id!=="github"&&R.authenticated),U=!k.defaultProvider&&!k.defaultModelId,E=v?!v.authenticated:!1;h({needsAiProvider:P,needsDefaultModel:U,needsGitHub:E})}catch{b||c(!0)}finally{b||o(!1)}})(),()=>{b=!0}},[s,a]);const f=i.useCallback(()=>{ID(),u(!0)},[]),p=i.useCallback(()=>{n()},[n]),g=i.useCallback(()=>{e("global-models")},[e]),x=i.useCallback(()=>{e("authentication")},[e]),w=i.useMemo(()=>{const b=[];return m.needsAiProvider&&b.push({id:"ai-provider",title:"Connect AI Provider",description:"Connect an AI provider to enable AI agents for task planning and code generation",actionLabel:"Set Up AI",onAction:p,icon:Qn}),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:pg}),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:Ws}),b},[m.needsAiProvider,m.needsDefaultModel,m.needsGitHub,x,g,p]);return!s||a||d||r||l||w.length===0?null:t.jsxs("section",{className:"post-onboarding-recommendations",role:"region","aria-label":"Setup recommendations",children:[t.jsxs("div",{className:"post-onboarding-recommendations__main",children:[t.jsx("div",{className:"post-onboarding-recommendations__icon","aria-hidden":"true",children:t.jsx(_i,{size:18,"aria-hidden":!0})}),t.jsxs("div",{className:"post-onboarding-recommendations__content",children:[t.jsx("h2",{className:"post-onboarding-recommendations__title",children:"Recommended Next Steps"}),t.jsx("p",{className:"post-onboarding-recommendations__description",children:"Complete these setup items to get the most out of Fusion."}),t.jsx("ul",{className:"post-onboarding-recommendations__list",children:w.map(b=>{const y=b.icon;return t.jsxs("li",{className:"post-onboarding-recommendations__item",children:[t.jsx("span",{className:"post-onboarding-recommendations__item-icon","aria-hidden":"true",children:t.jsx(y,{size:14,"aria-hidden":!0})}),t.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[t.jsx("strong",{children:b.title}),t.jsx("span",{children:b.description})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:b.onAction,children:b.actionLabel})]},b.id)})}),t.jsx(ta,{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(nn,{size:16,"aria-hidden":!0})})]})}function $L({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 pl(e){return e>99?"99+":String(e)}function DL({view:e,onChangeView:n,footerVisible:s,modalOpen:a=!1,keyboardOpen:r=!1,onOpenSettings:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:d,mailboxUnreadCount:u=0,mailboxPendingApprovalCount:m=0,chatHasUnreadResponse:h=!1,onOpenGitManager:f,onOpenWorkflowSteps:p,onOpenSchedules:g,onOpenScripts:x,onToggleTerminal:w,onOpenFiles:b,onOpenTodos:y,todosOpen:S=!1,onOpenGitHubImport:k,onOpenPlanning:C,onResumePlanning:v,activePlanningSessionCount:j=0,onOpenUsage:P,onRunScript:U,projectId:E,onViewAllProjects:R,showSkillsTab:L,experimentalFeatures:F,onOpenNodes:M,pluginDashboardViews:O=[],shellConnectionControl:q}){const te=Ys(),[Z,K]=i.useState(!1),[A,I]=i.useState(!1),[$,N]=i.useState({}),[G,ge]=i.useState(!1),je=i.useMemo(()=>Object.entries($).sort(([ce],[Me])=>ce.localeCompare(Me)),[$]);i.useEffect(()=>{if(!A)return;let ce=!1;return ge(!0),mo(E).then(Me=>{ce||N(Me)}).catch(()=>{ce||N({})}).finally(()=>{ce||ge(!1)}),()=>{ce=!0}},[A,E]);const ke=i.useCallback(()=>K(!1),[]),ne=i.useCallback(ce=>{ke(),ce?.()},[ke]);if(i.useEffect(()=>{if(!Z)return;const ce=Me=>{Me.key==="Escape"&&K(!1)};return document.addEventListener("keydown",ce),()=>document.removeEventListener("keydown",ce)},[Z]),te!=="mobile"||a||r)return null;const qe=j>0&&v?v:C,ee=!!L,le=!!F?.todoView,se=ee,re=ee&&!se,ve=O.filter(ce=>ce.view.placement==="primary").sort((ce,Me)=>(ce.view.order??Number.MAX_SAFE_INTEGER)-(Me.view.order??Number.MAX_SAFE_INTEGER)).slice(0,1),Ne=new Set(ve.map(ce=>`${ce.pluginId}:${ce.view.viewId}`)),H=O.filter(ce=>!Ne.has(`${ce.pluginId}:${ce.view.viewId}`)).sort((ce,Me)=>(ce.view.order??Number.MAX_SAFE_INTEGER)-(Me.view.order??Number.MAX_SAFE_INTEGER)),be=e==="documents"||!!F?.evalsView&&e==="evals"||e==="research"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||S&&le||e==="skills"&&!se||e==="graph"||rr(e)&&!ve.some(ce=>no(ce.pluginId,ce.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(aa,{}),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(Tn,{}),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(vs,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Missions"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="chat"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-chat",role:"tab","aria-selected":e==="chat",onClick:()=>n("chat"),children:[t.jsxs("span",{className:"mobile-nav-tab-icon-wrapper",children:[t.jsx(Ui,{}),h&&e!=="chat"&&t.jsx("span",{className:"status-dot status-dot--pending mobile-nav-chat-unread-dot","aria-label":"Unread chat response"})]}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Chat"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="mailbox"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-mailbox",role:"tab","aria-selected":e==="mailbox",onClick:()=>n("mailbox"),children:[t.jsxs("span",{className:"mobile-nav-tab-icon-wrapper",children:[t.jsx(Na,{}),m>0&&e!=="mailbox"&&t.jsx("span",{className:"status-dot status-dot--pending mobile-nav-chat-unread-dot","aria-label":"Pending approvals"})]}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:pl(u)})]}),se&&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(Qn,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),ve.map(ce=>{const Me=no(ce.pluginId,ce.view.viewId),Le=Ml(ce.view.icon);return t.jsxs("button",{type:"button",className:`mobile-nav-tab${e===Me||e==="graph"&&ce.pluginId==="fusion-plugin-dependency-graph"&&ce.view.viewId==="graph"?" mobile-nav-tab--active":""}`,"data-testid":`mobile-nav-tab-plugin-${ce.pluginId}-${ce.view.viewId}`,role:"tab","aria-selected":e===Me||e==="graph"&&ce.pluginId==="fusion-plugin-dependency-graph"&&ce.view.viewId==="graph",onClick:()=>n(ce.pluginId==="fusion-plugin-dependency-graph"&&ce.view.viewId==="graph"?"graph":Me),children:[t.jsx(Le,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:ce.view.label})]},`${ce.pluginId}:${ce.view.viewId}`)}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${be?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>K(ce=>!ce),children:[t.jsx(Nd,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),Z&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:ke}),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"}),q?t.jsx("div",{className:"mobile-more-shell-connection","data-testid":"mobile-more-shell-connection",children:q}):null,t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-mailbox",onClick:()=>ne(d),children:[t.jsx(Na,{}),t.jsx("span",{children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:pl(u)}),m>0&&t.jsx("span",{className:"mobile-more-item-badge",children:pl(m)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>ne(l),children:[t.jsx(Ks,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>ne(c),children:[t.jsx(dr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>ne(f),children:[t.jsx(Us,{}),t.jsx("span",{children:"Git Manager"})]}),t.jsxs("div",{className:"mobile-more-split-row",children:[t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-split-primary","data-testid":"mobile-more-item-terminal",onClick:()=>ne(w),children:[t.jsx(Bi,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>I(ce=>!ce),"aria-expanded":A,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(Mn,{size:14,className:`mobile-more-chevron${A?" mobile-more-chevron--open":""}`})})]}),A&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:G?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(xt,{className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):je.length>0?t.jsxs(t.Fragment,{children:[je.map(([ce,Me])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${ce}`,onClick:()=>{U&&U(ce,Me),ke(),I(!1)},children:[t.jsx(Yn,{}),t.jsx("span",{children:ce})]},ce)),x&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{ke(),I(!1),x()},children:[t.jsx(hi,{}),t.jsx("span",{children:"Manage Scripts…"})]})]}):x&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":"mobile-more-scripts-manage",onClick:()=>{ke(),I(!1),x()},children:[t.jsx(hi,{}),t.jsx("span",{children:"No scripts — add one…"})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>ne(b),children:[t.jsx(bs,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>ne(qe),children:[t.jsx(_i,{}),t.jsx("span",{children:"Planning"}),j>0&&t.jsx("span",{className:"mobile-more-item-badge",children:pl(j)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>ne(p),children:[t.jsx(Sl,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>ne(g),children:[t.jsx(Hi,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>ne(k),children:[t.jsx($L,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>ne(P),children:[t.jsx(Ks,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>ne(R),children:[t.jsx(Kl,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>ne(()=>n("documents")),children:[t.jsx(ia,{}),t.jsx("span",{children:"Documents"})]}),F?.evalsView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-evals",onClick:()=>ne(()=>n("evals")),children:[t.jsx(vs,{}),t.jsx("span",{children:"Evals"})]}),re&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>ne(()=>n("skills")),children:[t.jsx(Qn,{}),t.jsx("span",{children:"Skills"})]}),F?.researchView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-research",onClick:()=>ne(()=>n("research")),children:[t.jsx(Fi,{}),t.jsx("span",{children:"Research"})]}),F?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>ne(()=>n("insights")),children:[t.jsx(ps,{}),t.jsx("span",{children:"Insights"})]}),F?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>ne(()=>n("memory")),children:[t.jsx(oo,{}),t.jsx("span",{children:"Memory"})]}),F?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{ne(()=>n("dev-server"))},children:[t.jsx(dr,{}),t.jsx("span",{children:"Dev Server"})]}),F?.nodesView&&M&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-nodes",onClick:()=>ne(M),children:[t.jsx(kw,{}),t.jsx("span",{children:"Nodes"})]}),le&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>ne(()=>y?.()),children:[t.jsx(lu,{}),t.jsx("span",{children:"Todos"})]}),H.map(ce=>{const Me=no(ce.pluginId,ce.view.viewId),Le=Ml(ce.view.icon);return t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":`mobile-more-item-plugin-${ce.pluginId}-${ce.view.viewId}`,onClick:()=>ne(()=>n(ce.pluginId==="fusion-plugin-dependency-graph"&&ce.view.viewId==="graph"?"graph":Me)),children:[t.jsx(Le,{}),t.jsx("span",{children:ce.view.label})]},`${ce.pluginId}:${ce.view.viewId}`)}),t.jsx("div",{className:"mobile-more-separator"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-settings",onClick:()=>ne(o),children:[t.jsx(to,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function Af(e){return e.trim().toLowerCase().replace(/[\s-]+/g,"_").replace(/_+/g,"_")}function Xx(e,n){const s=n.trim();if(!s)return!0;const a=Af(s);return Af(e).includes(a)||e.toLowerCase().includes(s.toLowerCase())}function LL({agents:e,filter:n,highlightedIndex:s,visible:a,onSelect:r,position:o="below"}){const l=i.useMemo(()=>e.filter(c=>Xx(c.name,n)),[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(Zd,{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 Pf(e){const{sessionId:n,tempUserMessageId:s,setStreamingText:a,setStreamingThinking:r,setStreamingToolCalls:o,cancelStreamingFlushesRef:l,addToast:c,onDone:d,onError:u,onFallbackSession:m}=e;let h="",f="",p=[],g,x=null,w=null;const b=()=>{x=null,a(h)},y=()=>{w=null,r(f)},S=()=>{x!==null&&(cancelAnimationFrame(x),x=null),w!==null&&(cancelAnimationFrame(w),w=null)};return l.current=S,{handlers:{onThinking:C=>{f+=C,w===null&&(w=requestAnimationFrame(y))},onText:C=>{h+=C,x===null&&(x=requestAnimationFrame(b))},onToolStart:C=>{p=[...p,{toolName:C.toolName,args:C.args,isError:!1,status:"running"}],o(p)},onToolEnd:C=>{const v=[...p];for(let j=v.length-1;j>=0;j--){const P=v[j];if(P?.toolName===C.toolName&&P.status==="running"){v[j]={...P,status:"completed",isError:C.isError,result:C.result},p=v,o(v);return}}p=[...v,{toolName:C.toolName,isError:C.isError,result:C.result,status:"completed"}],o(p)},onFallback:C=>{g=C,m?.(C,n),c?.(`Primary model unavailable. Switched to fallback ${C.fallbackModel}.`,"warning")},onDone:C=>{S(),d({messageId:C.messageId,message:C.message,accumulated:{text:h,thinking:f,toolCalls:p,fallbackInfo:g}})},onError:C=>{S(),u(C,s)}},cancelFlushes:S}}const OL=["load failed","failed to fetch","networkerror when attempting to fetch resource.","connection aborted","connection closed unexpectedly","network error"];function zL(e){const n=e.trim().toLowerCase();return n?OL.some(s=>n.includes(s)):!1}function FL(){const e=i.useRef(null),n=i.useRef(null);i.useEffect(()=>{if(typeof document>"u")return;const r=()=>{const o=Date.now();if(document.visibilityState==="hidden"){e.current=o;return}document.visibilityState==="visible"&&(n.current=o)};return r(),document.addEventListener("visibilitychange",r),()=>document.removeEventListener("visibilitychange",r)},[]);const s=i.useCallback(()=>typeof document<"u"&&document.visibilityState==="hidden",[]),a=i.useCallback((r=5e3)=>{const o=e.current;if(o===null)return!1;const l=Date.now();if(s())return l-o<=r;const c=n.current;return c===null||c<o?!1:l-c<=r},[s]);return i.useMemo(()=>({isHiddenNow:s,wasRecentlyHidden:a}),[s,a])}const ar="__fn_agent__";function Zx(e,n){const s=typeof e=="string"?e.trim():"",a=typeof n=="string"?n.trim():"";return!s||!a?{}:{modelProvider:s,modelId:a}}function fl(e,n,s){const a=typeof e=="string"?e.trim():"",r=Zx(n,s),o=a||(r.modelProvider&&r.modelId?ar:"");return o?{agentId:o,...r}:null}function gl(e,n,s){const a=Zx(n,s),r=a.modelProvider??"",o=a.modelId??"";return`${e}::${r}/${o}`}function Rf(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 UL(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 BL(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 er(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:UL(e.metadata),fallbackInfo:BL(e.metadata),createdAt:e.createdAt}}function HL(e,n){const[s,a]=i.useState(null),[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState([]),[m,h]=i.useState(!1),[f,p]=i.useState(!1),[g,x]=i.useState(""),[w,b]=i.useState(""),[y,S]=i.useState([]),[k,C]=i.useState(""),v=i.useRef(null),j=i.useRef(!1),P=i.useRef(null),U=i.useRef(""),E=i.useRef(f);E.current=f;const R=i.useRef(null),L=i.useRef(""),F=i.useRef(null),M=i.useRef(s);M.current=s;const O=i.useRef(0),q=3,te=i.useRef(!1);i.useEffect(()=>{U.current=k},[k]);const Z=i.useCallback(async()=>{c(!0);try{const J=await Nm(e);o(J.sessions)}catch(J){console.error("[useQuickChat] Failed to refresh sessions:",J)}finally{c(!1)}},[e]),K=i.useCallback(async J=>{const B={agentId:J.agentId};return J.modelProvider&&J.modelId&&(B.modelProvider=J.modelProvider,B.modelId=J.modelId),(await O1(B,e)).session},[e]),A=i.useCallback(J=>{if(v.current||!J)return!0;j.current=!1,p(!0);const{handlers:B}=Pf({sessionId:J,tempUserMessageId:"",setStreamingText:x,setStreamingThinking:b,setStreamingToolCalls:S,cancelStreamingFlushesRef:P,addToast:n,onFallbackSession:(ve,Ne)=>{const H=Rf(ve.fallbackModel);o(be=>be.map(ce=>ce.id===Ne?{...ce,...H}:ce)),a(be=>be&&be.id===Ne?{...be,...H}:be)},onDone:()=>{x(""),b(""),S([]),p(!1),E.current=!1,v.current=null,Pr(J,{limit:50},e).then(ve=>{u(ve.messages.map(er))}).catch(()=>{})},onError:ve=>{x(""),b(""),S([]),p(!1),E.current=!1,v.current=null;const Ne=typeof ve=="string"&&ve.trim()?ve:"Failed to get response";n?.(Ne,"error"),Pr(J,{limit:50},e).then(H=>{u(H.messages.map(er))}).catch(()=>{})}});return v.current=B1(J,B,e),!0},[n,e]),I=i.useCallback(async(J,B,ve)=>{const Ne=fl(J,B,ve);if(!Ne)return;const H=gl(Ne.agentId,Ne.modelProvider,Ne.modelId);c(!0);try{const{session:be}=await L1({agentId:Ne.agentId,modelProvider:Ne.modelProvider,modelId:Ne.modelId},e);if(be)a(be),L.current=H,be.isGenerating&&(x(""),A(be.id));else{const ce=await K(Ne);a(ce),L.current=H}O.current=0}catch(be){console.error("[useQuickChat] Failed to initialize session:",be),O.current+=1,O.current<=q&&n?.("Failed to initialize chat","error")}finally{c(!1)}},[A,e,n,K]),$=i.useCallback(async()=>{if(s){h(!0);try{const J=await Pr(s.id,{limit:50},e);u(J.messages.map(er))}catch(J){console.error("[useQuickChat] Failed to load messages:",J)}finally{h(!1)}}},[s,e]);i.useEffect(()=>{s?$():u([])},[s,$]),i.useEffect(()=>{if(!s?.isGenerating||(v.current||A(s.id),!E.current||v.current||!s))return;const J=setInterval(async()=>{if(!E.current||v.current||!s){clearInterval(J);return}try{if(!(await z1(s.id,e)).session.isGenerating){clearInterval(J);const ve=await Pr(s.id,{limit:50},e);u(ve.messages.map(er)),x(""),b(""),S([]),p(!1)}}catch{}},3e3);return()=>clearInterval(J)},[s,A,e]);const N=i.useCallback(async()=>{if(s){h(!0);try{const J=await Pr(s.id,{limit:50},e);u(J.messages.map(er))}catch(J){console.error("[useQuickChat] Failed to reload messages:",J)}finally{h(!1)}}},[s,e]),G=i.useCallback(()=>{P.current?.(),P.current=null,U.current="",C(""),x(""),b(""),S([]),p(!1)},[]),ge=i.useCallback(async(J,B,ve)=>{const Ne=fl(J,B,ve);if(!Ne)return;const H=gl(Ne.agentId,Ne.modelProvider,Ne.modelId);F.current=Ne;const be=H===L.current&&M.current;if(be||(v.current&&(v.current.close(),v.current=null),G()),be){await N();return}a(null),u([]),L.current=H,await I(Ne.agentId,Ne.modelProvider,Ne.modelId)},[I,N,G]),je=i.useCallback(async J=>{const B=fl(J.agentId,J.modelProvider??void 0,J.modelId??void 0);B&&(F.current=B,L.current=gl(B.agentId,B.modelProvider,B.modelId),v.current&&(v.current.close(),v.current=null),G(),a(J),J.isGenerating&&(x(""),A(J.id)))},[A,G]),ke=i.useCallback(async(J,B)=>{await ge(ar,J,B)},[ge]),ne=i.useCallback(async(J,B,ve)=>{const H=fl(J??"",B,ve)??F.current;if(!H)return;F.current=H;const be=gl(H.agentId,H.modelProvider,H.modelId);te.current=!0,O.current=0,v.current&&(v.current.close(),v.current=null),G(),u([]),a(null),c(!0);try{const ce=await K(H);a(ce),L.current=be;const Me=await Nm(e);o(Me.sessions)}catch(ce){console.error("[useQuickChat] Failed to start a fresh session:",ce),n?.("Failed to start a new chat","error")}finally{te.current=!1,c(!1)}},[n,K,e,G]),qe=i.useCallback(()=>{s&&(j.current=!0,P.current?.(),P.current=null,v.current?.close(),v.current=null,F1(s.id,e).catch(()=>{}),p(!1),x(""),b(""),S([]))},[s,e]),ee=i.useCallback(()=>{U.current="",C("")},[]),le=i.useRef(()=>Promise.resolve()),se=FL(),re=i.useCallback((J,B)=>{if(!s||!J.trim()&&(!B||B.length===0))return Promise.resolve();if(E.current)return B&&B.length>0?Promise.reject(new Error("Cannot send attachments while a response is streaming")):(U.current=J,C(J),n?.("Still waiting for previous response — message queued","warning"),Promise.resolve());const ve=new Promise((Ne,H)=>{R.current={resolve:Ne,reject:H},j.current=!1,v.current&&(v.current.close(),v.current=null);const be=`temp-${Date.now()}`,ce={id:be,sessionId:s.id,role:"user",content:J,createdAt:new Date().toISOString()};u(Le=>[...Le,ce]),x(""),b(""),S([]),p(!0);const{handlers:Me}=Pf({sessionId:s.id,tempUserMessageId:be,setStreamingText:x,setStreamingThinking:b,setStreamingToolCalls:S,cancelStreamingFlushesRef:P,addToast:n,onFallbackSession:(Le,He)=>{const gt=Rf(Le.fallbackModel);o(Ue=>Ue.map(pe=>pe.id===He?{...pe,...gt}:pe)),a(Ue=>Ue&&Ue.id===He?{...Ue,...gt}:Ue)},onDone:({messageId:Le,message:He,accumulated:gt})=>{const Ue=He?er(He):{id:Le||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:gt.text,thinkingOutput:gt.thinking||void 0,toolCalls:gt.toolCalls.length>0?gt.toolCalls:void 0,fallbackInfo:gt.fallbackInfo,createdAt:new Date().toISOString()};u(Oe=>[...Oe,Ue]),x(""),b(""),S([]),p(!1),E.current=!1,v.current=null,R.current?.resolve(),R.current=null;const pe=U.current.trim();pe&&(U.current="",C(""),le.current(pe))},onError:Le=>{x(""),b(""),S([]),p(!1),E.current=!1,v.current=null,console.error("[useQuickChat] Stream error:",Le);const He=typeof Le=="string"&&Le.trim()?Le:"Failed to get response";if(typeof Le=="string"&&zL(Le)&&(se.isHiddenNow()||se.wasRecentlyHidden(5e3))?(console.info("[useQuickChat] Suppressed tab-suspension stream error:",Le),R.current?.resolve()):(n?.(He,"error"),R.current?.reject(new Error(He))),R.current=null,!j.current){const Ue=U.current.trim();Ue&&(U.current="",C(""),le.current(Ue))}N()}});v.current=U1(s.id,J,Me,B,e)});return ve.catch(()=>{}),ve},[s,e,n,N,se]);return le.current=re,i.useEffect(()=>()=>{v.current&&(v.current.close(),v.current=null)},[]),i.useMemo(()=>({activeSession:s,sessions:r,sessionsLoading:l,messages:d,messagesLoading:m,isStreaming:f,streamingText:g,streamingThinking:w,streamingToolCalls:y,pendingMessage:k,sendMessage:re,stopStreaming:qe,clearPendingMessage:ee,switchSession:ge,selectSession:je,startModelChat:ke,startFreshSession:ne,refreshSessions:Z,loadMessages:$,reloadMessages:N,skipNextSessionInitRef:te}),[s,r,l,d,m,f,g,w,y,k,re,qe,ee,ge,je,ke,ne,Z,$,N])}function qL(e,n){const[s,a]=i.useState([]),[r,o]=i.useState(null),[l,c]=i.useState(!1),d=i.useCallback(async p=>{c(!0);try{const g=n?.filterState,x=g&&g!=="all"?{state:g}:void 0,w=n?.showSystemAgents??!1,b=await Nr({...x,...p,includeEphemeral:p?.includeEphemeral??w},e),y=Array.from(new Map(b.map(S=>[S.id,S])).values());a(y)}catch(g){console.error("Failed to load agents:",g)}finally{c(!1)}},[e,n?.filterState,n?.showSystemAgents]),u=i.useCallback(async()=>{try{const p=await sS(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 ii(`/api/events${p}`,{events:{"agent:created":g,"agent:updated":g,"agent:deleted":g,"agent:stateChanged":g,"approval:requested":g,"approval:updated":g,"approval:decided":g}})},[e,d,u]);const m=i.useCallback(async()=>{await Promise.all([d(),u()])},[d,u]),h=n?.showSystemAgents??!1,f=s.filter(p=>p.state!=="active"&&p.state!=="running"?!1:h||!D0(p));return{agents:s,activeAgents:f,stats:r,isLoading:l,loadAgents:d,loadStats:u,refreshAgents:m}}function VL({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=g0(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(mg,{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 WL=200;function KL(e={}){const{projectId:n,workspace:s="project"}=e,[a,r]=i.useState(!1),[o,l]=i.useState(""),[c,d]=i.useState(-1),[u,m]=i.useState([]),[h,f]=i.useState(!1),[p,g]=i.useState(0),x=i.useRef(null),w=i.useRef(null);i.useEffect(()=>()=>{x.current&&clearTimeout(x.current),w.current?.abort()},[]);const b=i.useCallback((v,j)=>{if(j<0||j>v.length){r(!1);return}const P=U=>/[a-zA-Z0-9/_.-]/.test(U);for(let U=j-1;U>=0;U--){if(v[U]==="#")if(U===0){const E=v.slice(U+1,j);d(U),l(E),g(0),r(!0);return}else{const E=v[U-1];if(/[\s,.;:!?'"()[\]{}]/.test(E)){const R=v.slice(U+1,j);d(U),l(R),g(0),r(!0);return}r(!1);return}if(!P(v[U])){r(!1);return}}r(!1)},[]),y=i.useCallback(()=>{r(!1),l(""),d(-1),m([]),g(0),f(!1)},[]),S=i.useCallback(async v=>{if(!v.trim()){m([]),f(!1);return}w.current?.abort(),w.current=new AbortController;try{f(!0);const j=await lN(v,s,n);m(j.files),g(0)}catch(j){j.name!=="AbortError"&&m([])}finally{f(!1)}},[s,n]);i.useEffect(()=>{if(a)return x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{S(o)},WL),()=>{x.current&&clearTimeout(x.current)}},[o,a,S]);const k=i.useCallback((v,j)=>{if(!a||c<0)return j;const P=j.slice(0,c),U=j.slice(c+1),E=U.match(/[\s]|$/),R=E?E.index:U.length,L=U.slice(R);return`${P}#${v.path}${L}`},[a,c]),C=i.useCallback((v,j)=>{if(!a||u.length===0)return!1;switch(v.key){case"ArrowDown":return v.preventDefault(),g(P=>Math.min(P+1,u.length-1)),!0;case"ArrowUp":return v.preventDefault(),g(P=>Math.max(P-1,0)),!0;case"Enter":case"Tab":return u[p]?(v.preventDefault(),!0):!1;case"Escape":return v.preventDefault(),y(),!0;default:return!1}},[a,u,p,y]);return{mentionActive:a,files:u,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:g,detectMention:b,selectFile:k,dismissMention:y,handleKeyDown:C}}function GL(e){return`${e.name?.trim()||e.id} (${e.role})`}function qr(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 JL(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 wl(e,n){return e.length<=n?e:`${e.slice(0,n)}…`}function YL(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}=${wl(r,50)}`}).join(", ")}function QL(e){if(e===void 0)return null;if(typeof e=="string")return wl(e,200);try{return wl(JSON.stringify(e),200)}catch{return wl(String(e),200)}}function ev(e,n=!1){if(!e||e.length===0)return null;const s=(f,p)=>{const g=f.status==="running",x=f.status==="completed"&&f.isError,w=YL(f.args),b=QL(f.result),y=g?w:b?`result: ${b}`:w?`args: ${w}`:null,S=n?null:y,k=g?"running":x?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${g?" chat-tool-call--running":""}${x?" chat-tool-call--error":""}`,open:g,children:[t.jsxs("summary",{children:[t.jsx("span",{className:"chat-tool-call-status-dot","aria-hidden":"true"}),t.jsx("span",{className:"chat-tool-call-name",title:f.toolName,children:f.toolName}),S&&t.jsx("span",{className:"chat-tool-call-preview",title:S,children:S}),t.jsx("span",{className:"chat-tool-call-status-text",children:k})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[w&&t.jsxs("div",{className:"chat-tool-call-row",children:[t.jsx("span",{className:"chat-tool-call-label",children:"args"}),t.jsx("span",{className:"chat-tool-call-value",children:w})]}),b&&t.jsxs("div",{className:`chat-tool-call-row${x?" chat-tool-call-row--error":""}`,children:[t.jsx("span",{className:"chat-tool-call-label",children:"result"}),t.jsx("span",{className:"chat-tool-call-value",children:b})]})]})]},`${f.toolName}-${p}`)},a=`chat-tool-calls${n?" chat-tool-calls--compact":""}`;if(e.length===1)return t.jsxs("div",{className:a,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(Qu,{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(Qu,{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 tv={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 If(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 XL(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 bl={width:320,height:400},ZL=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"]),eO=[".png",".jpg",".jpeg",".gif",".webp",".txt",".json",".yaml",".yml",".log",".csv",".xml",".md"];function tO(e){return e.type.startsWith("image/")}function nO(e){if(ZL.has(e.type))return!0;const n=e.name.toLowerCase();return eO.some(s=>n.endsWith(s))}const tr={width:280,height:260},Ms=768,nr=8;function sO(e,n){const s=i.useCallback(()=>{if(typeof window>"u")return 0;const k=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return k&&parseFloat(k)||0},[]),a=i.useCallback(()=>typeof window<"u"&&window.innerWidth<=768?{x:4,y:4+s()}:{x:24,y:24+s()},[s]),[r,o]=i.useState(()=>{if(typeof window>"u")return a();const k=`fusion-quick-chat-position-${e||"default"}`;try{const C=localStorage.getItem(k);if(C){const v=JSON.parse(C);if(typeof v.x=="number"&&typeof v.y=="number"&&!isNaN(v.x)&&!isNaN(v.y))return v}}catch{}return a()}),[l,c]=i.useState(!1),d=i.useRef(null),u=i.useRef(r),m=i.useRef(null),h=i.useRef(null),f=n??i.useRef(!1);i.useEffect(()=>{u.current=r},[r]);const p=i.useCallback(k=>{if(typeof window>"u")return k;const C=48,v=window.innerWidth<=768?4:8,j=window.innerWidth<=768?44:0,P=window.innerWidth>768?s():0,U=window.innerWidth-C-v,E=window.innerHeight-C-v-j-P;return{x:Math.max(v,Math.min(U,k.x)),y:Math.max(v,Math.min(E,k.y))}},[s]),g=i.useCallback(k=>{if(typeof window>"u")return;const C=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(C,JSON.stringify(k))}catch{}},[e]),x=i.useCallback(()=>{if(!d.current)return;const k=h.current,C=m.current;k&&C!==null&&typeof k.releasePointerCapture=="function"&&k.releasePointerCapture(C),d.current=null,m.current=null,h.current=null,c(!1),document.body.style.userSelect="",f.current&&g(u.current),document.removeEventListener("pointermove",w),document.removeEventListener("pointerup",b),document.removeEventListener("pointercancel",y)},[g]),w=i.useCallback(k=>{if(!d.current||m.current!==null&&k.pointerId!==m.current)return;const C=k.clientX-d.current.pointerX,v=k.clientY-d.current.pointerY;if((Math.abs(C)>=5||Math.abs(v)>=5)&&(f.current=!0),!f.current)return;const j=d.current.x-C,P=d.current.y-v,U=p({x:j,y:P});u.current=U,o(U)},[p]),b=i.useCallback(k=>{m.current!==null&&k.pointerId!==m.current||x()},[x]),y=i.useCallback(k=>{m.current!==null&&k.pointerId!==m.current||x()},[x]),S=i.useCallback(k=>{if(k.button!==0&&k.pointerType==="mouse")return;const C=k.currentTarget;k.preventDefault(),typeof C.setPointerCapture=="function"&&C.setPointerCapture(k.pointerId);const v=u.current;d.current={x:v.x,y:v.y,pointerX:k.clientX,pointerY:k.clientY},m.current=k.pointerId,h.current=C,f.current=!1,c(!0),document.body.style.userSelect="none",document.addEventListener("pointermove",w,{passive:!0}),document.addEventListener("pointerup",b),document.addEventListener("pointercancel",y)},[y,w,b]);return i.useEffect(()=>()=>{document.removeEventListener("pointermove",w),document.removeEventListener("pointerup",b),document.removeEventListener("pointercancel",y),document.body.style.userSelect=""},[y,w,b]),{position:r,isDragging:l,handlePointerDown:S}}function iO(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(tr.width,window.innerWidth-p-nr),w=Math.max(tr.height,window.innerHeight-g-nr);return{width:Math.max(tr.width,Math.min(x,f.width)),height:Math.max(tr.height,Math.min(w,f.height))}},[]),l=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=Ms)return bl;try{const f=localStorage.getItem(a);if(!f)return bl;const p=JSON.parse(f);return typeof p.width!="number"||typeof p.height!="number"?bl:{width:p.width,height:p.height}}catch{return bl}},[a]),[c,d]=i.useState(l),[u,m]=i.useState({right:0,bottom:0});i.useEffect(()=>{if(!r())return;const f={right:n+u.right,bottom:s+u.bottom};d(p=>o(p,f.right,f.bottom))},[o,r,n,s,u]),i.useEffect(()=>{if(r())try{localStorage.setItem(a,JSON.stringify(c))}catch{}},[r,c,a]);const h=i.useCallback(f=>{if(!r())return;const p=f.currentTarget.dataset.resizeDirection;if(!p)return;f.preventDefault(),f.stopPropagation();const g=f.currentTarget;typeof g.setPointerCapture=="function"&&g.setPointerCapture(f.pointerId);const x={pointerX:f.clientX,pointerY:f.clientY,width:c.width,height:c.height,anchorRight:u.right,anchorBottom:u.bottom};document.body.style.userSelect="none";const w=y=>{const S=y.clientX-x.pointerX,k=y.clientY-x.pointerY;let C=x.width,v=x.height,j=x.anchorRight,P=x.anchorBottom;if(p.includes("w")&&(C=x.width-S),p.includes("e")){const M=S;C=x.width+M,j=x.anchorRight-M}if(p.includes("n")&&(v=x.height-k),p.includes("s")){const M=k;v=x.height+M,P=x.anchorBottom-M}const U=n+j,E=s+P,R=o({width:C,height:v},U,E),L=Math.max(nr-n,Math.min(window.innerWidth-n-tr.width-nr,j)),F=Math.max(nr-s,Math.min(window.innerHeight-s-tr.height-nr,P));d(R),m({right:L,bottom:F})},b=y=>{typeof g.releasePointerCapture=="function"&&g.releasePointerCapture(y.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",w),document.removeEventListener("pointerup",b);try{localStorage.setItem(a,JSON.stringify({width:c.width,height:c.height}))}catch{}};document.addEventListener("pointermove",w),document.addEventListener("pointerup",b)},[u.bottom,u.right,o,s,n,r,c.height,c.width,a]);return{panelSize:c,anchorOffset:u,handleResizeStart:h}}const 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 w=g.replace(/_/g," ").toLowerCase(),b=a.get(w);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(bi,{remarkPlugins:[xi],components:tv,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(ou,{size:14}):t.jsx(kr,{size:14})})]}),ev(n.toolCalls,!0)]})});function aO({projectId:e,addToast:n,showFAB:s=!0,open:a,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:d}){const{agents:u}=qL(e),[m,h]=i.useState(!1),f=a!==void 0,p=f?a:m,g=f?D=>{r?.(typeof D=="function"?D(p):D)}:h;Wi({enabled:p});const x=Ys(),[w,b]=i.useState("agent"),[y,S]=i.useState(""),[k,C]=i.useState(!1),[v,j]=i.useState("model"),[P,U]=i.useState(""),[E,R]=i.useState(""),[L,F]=i.useState([]),[M,O]=i.useState(!1),[q,te]=i.useState(""),[Z,K]=i.useState(""),[A,I]=i.useState(""),[$,N]=i.useState([]),[G,ge]=i.useState(!1),[je,ke]=i.useState(!1),[ne,qe]=i.useState(""),[ee,le]=i.useState(0),[se,re]=i.useState(""),[J,B]=i.useState(!1),[ve,Ne]=i.useState(0),[H,be]=i.useState(-1),[ce,Me]=i.useState(()=>new Set),[Le,He]=i.useState(!1),[gt,Ue]=i.useState([]),[pe,Oe]=i.useState(!1),[ze,lt]=i.useState(!1),[,Be]=i.useState(!1),[ye,Y]=i.useState({top:0,left:0}),_e=KL({projectId:e}),ct=i.useCallback(D=>{if(!D||!_e.mentionActive)return;const Q=D.getBoundingClientRect();Y({top:Q.top-260,left:Q.left+8})},[_e.mentionActive]),pt=i.useRef(!1),de=i.useRef(!1),Ve=i.useRef(""),Ee=i.useRef(0),$e=i.useRef(null),ut=i.useRef(null),ht=i.useRef(0),{position:Se,isDragging:we,handlePointerDown:Ae}=sO(e,pt),he=Se.y+60,{panelSize:We,anchorOffset:me,handleResizeStart:nt}=iO(e,Se.x,he),Ct=typeof window<"u"&&window.innerWidth>Ms,{activeSession:wt,messages:$t,isStreaming:Vt,streamingText:Mt,streamingThinking:Dt,streamingToolCalls:Qt,sessions:Kt,sessionsLoading:Bt,messagesLoading:on,sendMessage:fn,stopStreaming:Jt,pendingMessage:an,clearPendingMessage:zt,switchSession:en,selectSession:Zt,startModelChat:dn,startFreshSession:xe,refreshSessions:Fe,skipNextSessionInitRef:Ke}=HL(e,n),et=i.useRef(null),Qe=i.useRef(null),It=i.useRef(null),St=i.useRef(null),Ht=i.useRef(null),jt=i.useRef([]),ae=i.useRef(!1),De=i.useRef(!1),At=i.useRef(!1),Lt=i.useRef(null),Ft=i.useRef(!1),Pe=i.useRef(!1),dt=i.useRef({isOpen:!1,sessionId:null});i.useEffect(()=>{if(!p||typeof window>"u"||typeof document>"u"||window.innerWidth>Ms)return;const D=window.scrollY,Q=document.documentElement,Ce=document.body,Je={htmlOverflow:Q.style.overflow,bodyOverflow:Ce.style.overflow};return window.scrollTo(0,0),Q.style.overflow="hidden",Ce.style.overflow="hidden",()=>{Q.style.overflow=Je.htmlOverflow,Ce.style.overflow=Je.bodyOverflow,window.scrollTo(0,D)}},[p]),i.useLayoutEffect(()=>{if(!p||typeof window>"u"||!window.visualViewport)return;const D=et.current;if(!D)return;const Q=window.visualViewport,Ce=()=>{Ft.current||(D.style.setProperty("--vv-height",`${Q.height}px`),D.style.setProperty("--vv-offset-top",`${Q.offsetTop||0}px`))};return Ce(),Q.addEventListener("resize",Ce),Q.addEventListener("scroll",Ce),()=>{Q.removeEventListener("resize",Ce),Q.removeEventListener("scroll",Ce)}},[p]);const bt=q||Z,_t=i.useMemo(()=>qr(bt),[bt]),Yt=i.useMemo(()=>w==="model"&&wt?.modelProvider&&wt?.modelId?`${wt.modelProvider}/${wt.modelId}`:bt,[wt?.modelId,wt?.modelProvider,w,bt]),Xt=i.useMemo(()=>qr(Yt),[Yt]),Te=i.useMemo(()=>L.find(D=>`${D.provider}/${D.id}`===Yt)??null,[Yt,L]),Ye=i.useMemo(()=>JL(Te,Xt),[Te,Xt]),Nt=i.useMemo(()=>w==="model"?_t?`${ar}::${_t.modelProvider}/${_t.modelId}`:"":y?`${y}::`:"",[w,y,_t]),tn=!(w==="agent"?!!y:!!_t)||!wt;i.useEffect(()=>{if(u.length===0){S(""),b("model");return}u.some(Q=>Q.id===y)||S(u[0]?.id??"")},[u,y]),i.useEffect(()=>{!p||de.current||(de.current=!0,O(!0),Os().then(D=>{const Q=D.models??[];if(F(Q),q||Q.length===0)return;const Ce=D.defaultProvider,Je=D.defaultModelId;if(Ce&&Je){const Tt=`${Ce}/${Je}`;if(Q.some(ln=>`${ln.provider}/${ln.id}`===Tt)){K(Tt),te(Tt),b("model");return}}K("");const kt=Q[0];kt&&te(`${kt.provider}/${kt.id}`)}).catch(D=>{console.error("[QuickChatFAB] Failed to load models:",D),F([]),K("")}).finally(()=>{O(!1)}))},[p,u.length,q]),i.useEffect(()=>{!p||!e||(ge(!0),D1(e).then(D=>{N(D)}).catch(()=>{N([])}).finally(()=>{ge(!1)}))},[p,e]),i.useEffect(()=>{p&&Fe()},[p,Fe]),i.useEffect(()=>{if(!p){Ve.current="";return}if(!Nt){Ve.current="";return}if(Ke.current){Ve.current=Nt;return}const D=Nt===Ve.current&&!wt&&!Bt;if(!(Nt===Ve.current&&!D)){if(Ve.current=Nt,w==="model"&&_t){dn(_t.modelProvider,_t.modelId);return}w==="agent"&&y&&en(y)}},[p,w,_t,y,Nt,wt,Bt,dn,en,Ke]),i.useEffect(()=>{p||(B(!1),re(""),be(-1),ke(!1),qe(""),le(0),jt.current.forEach(D=>{D.previewUrl&&URL.revokeObjectURL(D.previewUrl)}),Ue([]))},[p]),i.useEffect(()=>{jt.current=gt},[gt]),i.useEffect(()=>{if(!p){ae.current=!1;return}typeof window>"u"||(ae.current=window.innerWidth<=Ms)},[p]),i.useEffect(()=>{if(!p||tn||!ae.current)return;const D=St.current;if(!D)return;const Q=document.activeElement,Ce=Q?et.current?.contains(Q):!1,Je=Q===document.body,kt=Q===Lt.current;if(!Ce&&!Je&&!kt){ae.current=!1;return}if(kt){D.focus({preventScroll:!0}),ae.current=!1;return}const Tt=requestAnimationFrame(()=>{D.focus(),ae.current=!1});return()=>cancelAnimationFrame(Tt)},[p,tn]),i.useEffect(()=>()=>{jt.current.forEach(D=>{D.previewUrl&&URL.revokeObjectURL(D.previewUrl)})},[]);const Xn=i.useCallback(()=>{C(!0),j("model"),U(u[0]?.id??""),R(q||Z||"")},[u,Z,q]),fe=i.useMemo(()=>u.find(D=>D.id===y)??null,[u,y]),at=i.useMemo(()=>{const D=ne.trim().toLowerCase();return(D?$.filter(Ce=>Ce.name.toLowerCase().includes(D)):$).slice(0,10)},[$,ne]),ot=i.useMemo(()=>u.filter(D=>Xx(D.name,se)),[u,se]),rt=i.useMemo(()=>{const D=new Map;for(const Q of u)D.set(Q.name.toLowerCase(),Q);return D},[u]);i.useEffect(()=>{le(0)},[at]),i.useEffect(()=>{Ne(0)},[se,J]),i.useEffect(()=>()=>{$e.current!==null&&(window.clearTimeout($e.current),$e.current=null),ut.current!==null&&(window.clearTimeout(ut.current),ut.current=null)},[]),i.useEffect(()=>{if(!p)return;const D=Ce=>{const Je=Ce.target;et.current?.contains(Je)||Qe.current?.contains(Je)||Je.closest(".model-combobox-dropdown--portal")||g(!1)},Q=Ce=>{Ce.key==="Escape"&&g(!1)};return document.addEventListener("mousedown",D),document.addEventListener("keydown",Q),()=>{document.removeEventListener("mousedown",D),document.removeEventListener("keydown",Q)}},[p,g]);const mt=i.useCallback(()=>{const D=It.current;if(!D)return;const Ce=D.scrollTop+D.clientHeight>=D.scrollHeight-50;lt(!Ce),Pe.current=!Ce},[]),vt=i.useCallback(D=>{if(!D.isConnected)return;let Q=0,Ce=0,Je=-1;const kt=6,Tt=()=>{if(D.isConnected){if(D.scrollTop=D.scrollHeight,D.scrollHeight===Je?Ce+=1:(Ce=0,Je=D.scrollHeight),Q+=1,Q>=kt||Ce>=2){lt(!1),Pe.current=!1;return}window.requestAnimationFrame(Tt)}};Tt()},[]),ie=i.useCallback(()=>{const D=It.current;D&&vt(D)},[vt]);i.useLayoutEffect(()=>{const D=wt?.id??null,Q=dt.current;if(dt.current={isOpen:p,sessionId:D},!p||!D)return;const Ce=!Q.isOpen&&p,Je=Q.isOpen&&Q.sessionId!==D;if(!Ce&&!Je)return;const kt=It.current;kt&&vt(kt)},[p,wt?.id,vt]),i.useEffect(()=>{p&&(Pe.current||ie())},[$t,Mt,Dt,Vt,p,ie]);const it=i.useMemo(()=>{const D=new Map(u.map(Ce=>[Ce.id,Ce.name?.trim()||Ce.id])),Q=new Map(L.map(Ce=>[`${Ce.provider}/${Ce.id}`,Ce.name?.trim()||""]));return Kt.map((Ce,Je)=>{const kt=Ce.title?.trim()||`Session ${Je+1}`;let Tt=null;if(Ce.agentId&&Ce.agentId!==ar)Tt=D.get(Ce.agentId)||Ce.agentId;else if(Ce.modelProvider&&Ce.modelId){const Pt=`${Ce.modelProvider}/${Ce.modelId}`,ln=Q.get(Pt);Tt=ln?`${ln} [${Pt}]`:Pt}return{id:Ce.id,label:Tt?`${kt} — ${Tt}`:kt}})},[u,L,Kt]),Gt=i.useMemo(()=>w==="agent"?fe?`Message ${fe.name||fe.id}`:"Select an agent to start chatting":Ye?`Message ${Ye}`:"Select a model to start chatting",[w,fe,Ye]),Cn=i.useCallback(D=>{const Q=Kt.find(Ce=>Ce.id===D);Q&&(Q.modelProvider&&Q.modelId?(b("model"),te(`${Q.modelProvider}/${Q.modelId}`)):(b("agent"),S(Q.agentId)),Zt(Q))},[Zt,Kt]),fs=i.useCallback(async()=>{if(!Bt){if(v==="agent"){if(!P)return;b("agent"),S(P),await xe(P)}else{const D=qr(E||q||Z);if(!D)return;b("model"),te(`${D.modelProvider}/${D.modelId}`),await xe(ar,D.modelProvider,D.modelId)}await Fe(),C(!1),j("model")}},[Z,P,v,E,Fe,q,Bt,xe]),On=an.length>50?`${an.slice(0,50)}…`:an,jn=i.useCallback(D=>{if(!D||D.length===0)return;const Q=[];for(let Ce=0;Ce<D.length;Ce+=1){const Je=D[Ce];nO(Je)&&Q.push({file:Je,previewUrl:tO(Je)?URL.createObjectURL(Je):""})}Q.length>0&&Ue(Ce=>[...Ce,...Q])},[]),zn=i.useCallback(D=>{Ue(Q=>{const Ce=Q[D];return Ce?.previewUrl&&URL.revokeObjectURL(Ce.previewUrl),Q.filter((Je,kt)=>kt!==D)})},[]),hn=i.useCallback(D=>{jn(D.clipboardData?.files)},[jn]),Et=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth>Ms)return;const D=St.current;!D||D.disabled||D.focus({preventScroll:!0})},[]),En=i.useCallback(()=>{typeof window>"u"||window.innerWidth>Ms||(At.current=!0)},[]),yn=i.useCallback(async()=>{const D=A.trim(),Q=jt.current;if(!(!D&&Q.length===0)&&!tn){if(I(""),B(!1),re(""),be(-1),D==="/help"){He(!0),Et(),At.current=!1;return}if(D==="/clear"){Jt(),zt(),Q.forEach(Ce=>{Ce.previewUrl&&URL.revokeObjectURL(Ce.previewUrl)}),Ue(Ce=>Ce.filter(Je=>!Q.includes(Je)));try{if(w==="model"){const Ce=qr(bt);if(!Ce)return;await xe(ar,Ce.modelProvider,Ce.modelId)}else y&&await xe(y)}catch{n("Failed to clear conversation","error")}finally{Et(),At.current=!1}return}try{He(!1),await fn(D,Q.map(Ce=>Ce.file)),Q.forEach(Ce=>{Ce.previewUrl&&URL.revokeObjectURL(Ce.previewUrl)}),Ue(Ce=>Ce.filter(Je=>!Q.includes(Je)))}catch{}finally{Et(),At.current=!1}}},[n,w,zt,Et,tn,A,bt,y,fn,xe,Jt]),ls=i.useCallback(D=>{D.preventDefault(),ht.current+=1,Oe(!0)},[]),cs=i.useCallback(D=>{D.preventDefault(),D.dataTransfer.dropEffect="copy",Oe(!0)},[]),Hn=i.useCallback(D=>{D.preventDefault(),ht.current=Math.max(0,ht.current-1),ht.current===0&&Oe(!1)},[]),qn=i.useCallback(D=>{D.preventDefault(),ht.current=0,Oe(!1),jn(D.dataTransfer?.files)},[jn]),wn=i.useCallback((D,Q)=>{const Ce=XL(D,Q);if(Ce){B(!0),re(Ce.filter),be(Ce.start);return}B(!1),re(""),be(-1)},[]),Zn=i.useCallback(D=>{I(Q=>{const Ce=If(Q);if(!Ce)return Q;const Je=`/skill:${D.name} `,kt=Q.slice(0,Ce.start)+Je+Q.slice(Ce.end);return window.requestAnimationFrame(()=>{St.current&&St.current.focus()}),kt}),ke(!1),qe(""),le(0)},[]),_n=i.useCallback(D=>{const Q=St.current;if(!Q||H<0)return;const Ce=Q.selectionStart??Ee.current,Je=Q.selectionEnd??Ce,kt=Math.max(Ce,Je),Tt=Math.min(H,kt),ln=`${`@${D.name.replace(/\s+/g,"_")}`} `,ts=A.slice(0,Tt)+ln+A.slice(kt),Pn=Tt+ln.length;I(ts),B(!1),re(""),Ne(0),be(-1),window.requestAnimationFrame(()=>{St.current&&(St.current.focus(),St.current.setSelectionRange(Pn,Pn))})},[H,A]),ss=i.useCallback(D=>{const Q=D.target.value,Ce=D.target.selectionStart??Q.length;Ee.current=Ce,I(Q),Le&&Q.trim().length>0&&He(!1),wn(Q,Ce);const Je=If(Q);Je?(ke(!0),qe(Je.filter)):(ke(!1),qe("")),_e.detectMention(Q,Ce),Be(_e.mentionActive),_e.mentionActive&&ct(D.target)},[Le,wn,_e,ct]),Ns=i.useCallback(()=>{if(At.current){window.requestAnimationFrame(()=>{Et()});return}typeof window<"u"&&window.innerWidth<=Ms&&et.current&&(Ft.current=!0,et.current.style.removeProperty("--vv-height"),et.current.style.removeProperty("--vv-offset-top"),window.setTimeout(()=>{Ft.current=!1},450)),$e.current!==null&&window.clearTimeout($e.current),$e.current=window.setTimeout(()=>{B(!1),re(""),be(-1),Be(!1),_e.dismissMention(),$e.current=null},120),ut.current!==null&&window.clearTimeout(ut.current),ut.current=window.setTimeout(()=>{ke(!1),ut.current=null},120)},[_e,Et]),es=i.useCallback(()=>{Ft.current=!1,$e.current!==null&&(window.clearTimeout($e.current),$e.current=null),ut.current!==null&&(window.clearTimeout(ut.current),ut.current=null)},[]),ks=i.useCallback(D=>{const Q=D.currentTarget,Ce=Q.selectionStart??Q.value.length;Ee.current=Ce,wn(Q.value,Ce),_e.detectMention(Q.value,Ce),Be(_e.mentionActive),_e.mentionActive&&ct(Q)},[wn,_e,ct]),Is=i.useCallback(D=>{D.key!=="Escape"&&ks(D)},[ks]),Ss=i.useCallback(D=>{Me(Q=>{const Ce=new Set(Q);return Ce.has(D)?Ce.delete(D):Ce.add(D),Ce})},[]),X=i.useCallback((D,Q=!1)=>Q?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:D}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(bi,{remarkPlugins:[xi],components:tv,children:D})}),[]),_=i.useCallback(D=>{if(Ee.current=D.currentTarget.selectionStart??Ee.current,_e.mentionActive&&_e.files.length>0){if(_e.handleKeyDown(D,A),D.key==="Enter"||D.key==="Tab"){const Q=_e.files[_e.selectedIndex];if(Q){const Ce=_e.selectFile(Q,A);I(Ce),_e.dismissMention(),Be(!1)}}return}if(J&&D.key==="ArrowDown"){D.preventDefault(),ot.length>0&&Ne(Q=>(Q+1)%ot.length);return}if(J&&D.key==="ArrowUp"){D.preventDefault(),ot.length>0&&Ne(Q=>Q===0?ot.length-1:Q-1);return}if(J&&D.key==="Enter"){D.preventDefault();const Q=ot[ve]??ot[0];Q&&_n(Q);return}if(J&&D.key==="Escape"){D.preventDefault(),D.stopPropagation(),B(!1),re(""),be(-1);return}if(je&&at.length>0&&D.key==="ArrowDown"){D.preventDefault(),le(Q=>(Q+1)%at.length);return}if(je&&at.length>0&&D.key==="ArrowUp"){D.preventDefault(),le(Q=>Q===0?at.length-1:Q-1);return}if(je&&(D.key==="Enter"||D.key==="Tab")){D.preventDefault();const Q=at[ee]??at[0];Q&&Zn(Q);return}if(je&&D.key==="Escape"){D.preventDefault(),ke(!1),qe("");return}D.key!=="Enter"||D.shiftKey||(D.preventDefault(),yn())},[J,ot,ve,_n,yn,_e,A,je,at,ee,Zn]),oe=i.useCallback(()=>{if(pt.current){pt.current=!1;return}if(p){g(!1);return}typeof window<"u"&&window.innerWidth<=Ms&&Lt.current?.focus({preventScroll:!0}),g(!0)},[p,g]);return t.jsxs(t.Fragment,{children:[t.jsx("input",{ref:Lt,type:"text",className:"quick-chat-stealth-input","aria-hidden":"true",tabIndex:-1}),s&&t.jsx("button",{ref:Qe,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":we?"true":"false",style:{right:Se.x,bottom:Se.y},onPointerDown:Ae,onClick:oe,children:t.jsx(Ui,{size:24})}),p&&t.jsxs("div",{className:"quick-chat-panel",ref:et,"data-testid":"quick-chat-panel",style:{...Ct?{right:Se.x+me.right,bottom:he+me.bottom,width:We.width,height:We.height}:{}},children:[Ct&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:nt,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:nt,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:nt,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:nt,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:nt,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:nt,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:nt,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:nt,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"}),w==="model"&&Ye&&(()=>{const D=Te?.provider??Xt?.modelProvider??"";return x==="mobile"&&Ye.length>12&&D?t.jsx("span",{className:"quick-chat-model-tag quick-chat-model-tag--icon","data-testid":"quick-chat-model-tag",title:Ye,"aria-label":Ye,children:t.jsx(Sn,{provider:D,size:"sm"})}):t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:Ye,children:Ye})})()]}),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:Xn,disabled:Bt,children:t.jsx(bn,{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(nn,{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:wt?.id??"",onChange:D=>Cn(D.target.value),"data-testid":"quick-chat-session-dropdown",children:[t.jsx("option",{value:"",disabled:!0,children:Bt?"Loading sessions…":"Select a session"}),it.map(D=>t.jsx("option",{value:D.id,children:D.label},D.id))]})]}),k&&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${v==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-model",onClick:()=>j("model"),children:"Model"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${v==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-agent",onClick:()=>j("agent"),children:"Agent"})]}),v==="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:P,onChange:D=>U(D.target.value),"data-testid":"quick-chat-new-agent-select",children:u.map(D=>t.jsx("option",{value:D.id,children:GL(D)},D.id))})]}):t.jsx("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-new-model-select",children:t.jsx(ys,{id:"quick-chat-new-model-select",models:L,value:E,onChange:R,label:"Select model override",placeholder:M?"Loading models…":"Select a model",disabled:M||L.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:()=>{C(!1),j("model")},children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary","data-testid":"quick-chat-new-session-submit",onClick:()=>void fs(),disabled:Bt||(v==="agent"?!P:!qr(E||q||Z)),children:"Create"})]})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:It,"data-testid":"quick-chat-messages",onScroll:mt,children:Bt?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):Vt?t.jsxs(t.Fragment,{children:[$t.map(D=>t.jsx(Tf,{message:D,forcePlain:D.role!=="user"&&ce.has(D.id),mentionAgentsByName:rt,onToggleRender:Ss},D.id)),Le&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:X("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:[Mt?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:X(Mt,ce.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${ce.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":ce.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>Ss("__streaming__"),children:ce.has("__streaming__")?t.jsx(ou,{size:14}):t.jsx(kr,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:Dt?"Thinking…":"Connecting…"}),ev(Qt,!0),Dt&&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:Dt})]})]})]}):on?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):$t.length===0&&!Mt&&!Dt&&!Vt&&!Le?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[$t.map(D=>t.jsx(Tf,{message:D,forcePlain:D.role!=="user"&&ce.has(D.id),mentionAgentsByName:rt,onToggleRender:Ss},D.id)),Le&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:X("Available commands:\n- `/clear` — Clear conversation and start fresh\n- `/skill:{name}` — Use a specific skill\n- `/help` — Show this help")})]})}),ze&&t.jsxs("button",{type:"button",className:"btn btn-sm quick-chat-jump-to-latest","data-testid":"quick-chat-jump-to-latest",onClick:ie,children:[t.jsx(rn,{size:14}),"Latest"]}),gt.length>0&&t.jsx("div",{className:"quick-chat-attachment-previews","data-testid":"quick-chat-attachment-previews",children:gt.map((D,Q)=>t.jsxs("div",{className:"quick-chat-attachment-preview","data-testid":`quick-chat-attachment-preview-${Q}`,children:[D.previewUrl?t.jsx("img",{src:D.previewUrl,alt:D.file.name}):t.jsx("span",{className:"quick-chat-attachment-preview-name",children:D.file.name}),t.jsx("button",{type:"button",className:"quick-chat-attachment-remove","data-testid":`quick-chat-attachment-remove-${Q}`,"aria-label":`Remove ${D.file.name}`,onClick:()=>zn(Q),children:"×"})]},`${D.file.name}-${Q}`))}),t.jsx("div",{className:"quick-chat-panel-input",children:t.jsxs("div",{className:`quick-chat-input-wrapper${pe?" quick-chat-input-wrapper--dragover":""}`,onDragEnter:ls,onDragOver:cs,onDragLeave:Hn,onDrop:qn,children:[t.jsx("input",{ref:Ht,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:D=>{jn(D.target.files),D.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:()=>Ht.current?.click(),children:t.jsx(fg,{size:16})}),t.jsx("input",{ref:St,type:"text",value:A,onChange:ss,onKeyDown:_,onKeyUp:Is,onClick:ks,onBlur:Ns,onFocus:es,onPaste:hn,onTouchStart:D=>{typeof window>"u"||window.innerWidth>Ms||document.activeElement!==D.currentTarget&&(D.preventDefault(),D.currentTarget.focus({preventScroll:!0}))},placeholder:Gt,disabled:tn,"data-testid":"quick-chat-input"}),Vt?t.jsx("button",{type:"button",className:"chat-input-stop quick-chat-send-btn",onPointerDown:D=>{typeof window>"u"||window.innerWidth>Ms||(D.preventDefault(),D.pointerType&&D.pointerType!=="mouse"&&(De.current=!0,Jt()))},onTouchStart:D=>{typeof window>"u"||window.innerWidth>Ms||(D.preventDefault(),De.current=!0,Jt())},onMouseDown:D=>{typeof window>"u"||window.innerWidth>Ms||D.preventDefault()},onClick:()=>{if(De.current){De.current=!1;return}Jt()},"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:D=>{typeof window>"u"||window.innerWidth>Ms||(D.preventDefault(),D.pointerType&&D.pointerType!=="mouse"&&(De.current=!0,En(),Et(),yn()))},onTouchStart:D=>{typeof window>"u"||window.innerWidth>Ms||(D.preventDefault(),De.current=!0,En(),Et(),yn())},onMouseDown:D=>{typeof window>"u"||window.innerWidth>Ms||D.preventDefault()},onClick:()=>{if(De.current){De.current=!1;return}yn()},disabled:tn||A.trim().length===0&>.length===0,"data-testid":"quick-chat-send",children:t.jsx(wa,{size:16})})]}),t.jsx(LL,{agents:u,filter:se,highlightedIndex:ve,visible:J,onSelect:_n,position:"above"}),t.jsx(VL,{visible:_e.mentionActive&&!J,position:ye,files:_e.files,selectedIndex:_e.selectedIndex,onSelect:D=>{const Q=_e.selectFile(D,A);I(Q),_e.dismissMention(),Be(!1),St.current?.focus()},loading:_e.loading}),je&&t.jsx("div",{className:"chat-skill-menu","data-testid":"quick-chat-skill-menu",role:"listbox","aria-label":"Skill suggestions",children:G?t.jsx("div",{className:"chat-skill-menu-empty",children:"Loading skills…"}):at.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:ne?"No skills found":"No skills available"}):at.map((D,Q)=>t.jsxs("button",{type:"button",role:"option","aria-selected":Q===ee,className:`chat-skill-menu-item${Q===ee?" chat-skill-menu-item--highlighted":""}`,onMouseDown:Ce=>Ce.preventDefault(),onMouseEnter:()=>le(Q),onClick:()=>Zn(D),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:D.name}),t.jsx("span",{className:"chat-skill-menu-item-description",title:D.relativePath,children:D.relativePath})]},D.id))}),an&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${On}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:zt,children:"×"})]})]})})]})]})}function Vr(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function $f(e){return e.status==="generating"||e.status==="awaiting_input"}function Wr(e){return e==="complete"||e==="error"}function rO(e){const[n,s]=i.useState([]),a=i.useRef(new Map),r=i.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:d}=_r(),u=i.useCallback(()=>{hu(e).then(p=>{const g=p.filter(w=>{const b=Vr(w.updatedAt),y=r.current.get(w.id);return y===void 0?!0:b<=y?!1:(r.current.delete(w.id),!0)}),x=new Map;for(const w of g)x.set(w.id,Vr(w.updatedAt));a.current=x,s(g)}).catch(p=>{console.warn("[useBackgroundSessions] Failed to fetch AI sessions:",p)})},[e]);i.useEffect(()=>{d(),u()},[u,d]),i.useEffect(()=>{s(p=>{if(o.size===0)return p;let g=!1;const x=new Map(p.map(w=>[w.id,w]));for(const w of o.values()){if(e&&w.projectId&&w.projectId!==e)continue;const b=w.lastEventTimestamp,y=a.current.get(w.sessionId)??0;if(b<y)continue;const S=r.current.get(w.sessionId);if(S!==void 0&&b<=S)continue;if(S!==void 0&&b>S&&!Wr(w.status)&&r.current.delete(w.sessionId),Wr(w.status)){x.delete(w.sessionId)&&(g=!0),a.current.set(w.sessionId,b);continue}const k=x.get(w.sessionId),C=w.type??k?.type,v=w.title??k?.title;if(!k&&(!C||!v))continue;const j={id:w.sessionId,type:C??"planning",status:w.status,title:v??"AI Session",projectId:w.projectId??k?.projectId??e??null,lockedByTab:w.owningTabId??k?.lockedByTab??null,updatedAt:w.updatedAt??k?.updatedAt??new Date(b).toISOString()},P=x.get(w.sessionId);(!P||P.status!==j.status||P.title!==j.title||P.type!==j.type||P.projectId!==j.projectId||P.lockedByTab!==j.lockedByTab||P.updatedAt!==j.updatedAt)&&(x.set(w.sessionId,j),a.current.set(w.sessionId,b),g=!0)}return g?[...x.values()].sort((w,b)=>Vr(b.updatedAt)-Vr(w.updatedAt)):p})},[e,o]),i.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",g=w=>{try{const b=JSON.parse(w.data),y=Vr(b.updatedAt)||Date.now();s(S=>{const k=a.current.get(b.id)??0;if(y<k)return S;const C=r.current.get(b.id);if(C!==void 0&&y<=C)return S;if(C!==void 0&&y>C&&!Wr(b.status)&&r.current.delete(b.id),a.current.set(b.id,y),Wr(b.status))return S.filter(j=>j.id!==b.id);const v=S.findIndex(j=>j.id===b.id);if(v>=0){const j=[...S];return j[v]=b,j}return $f(b)?[b,...S]:S}),l({sessionId:b.id,status:b.status,needsInput:b.status==="awaiting_input",type:b.type,title:b.title,projectId:b.projectId,owningTabId:b.lockedByTab,updatedAt:b.updatedAt,timestamp:y}),Wr(b.status)&&c({sessionId:b.id,status:b.status,timestamp:y})}catch{}},x=w=>{try{const b=JSON.parse(w.data),y=Date.now();r.current.set(b,y),a.current.set(b,Math.max(a.current.get(b)??0,y)),c({sessionId:b,status:"complete",timestamp:y}),s(S=>S.filter(k=>k.id!==b))}catch{}};return ii(`/api/events${p}`,{events:{"ai_session:updated":g,"ai_session:deleted":x},onReconnect:()=>{u()}})},[c,l,e,u]);const m=i.useCallback(async p=>{const x=n.find(S=>S.id===p)?.type,w=Ia();let b=!1;if(x==="planning")try{await Sg(p,e,w)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of planning session ${p} despite lock by another tab`)}else if(x==="subtask")try{await _g(p,e,w)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of subtask session ${p} despite lock by another tab`)}else if(x==="mission_interview")try{await Ig(p,e,w)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of mission interview session ${p} despite lock by another tab`)}b&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${p}, attempting delete anyway`);const y=Date.now();r.current.set(p,y),a.current.set(p,Math.max(a.current.get(p)??0,y)),c({sessionId:p,status:"complete",timestamp:y});try{await Tg(p)}catch{}s(S=>S.filter(k=>k.id!==p))},[c,e,n]),h=i.useMemo(()=>n.filter(p=>$f(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 Bl="fusion:hide-session-banners",iu="fusion:session-banner-pref-changed";function oO(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Bl)==="1"}catch{return!1}}function lO(e){if(typeof window>"u")return()=>{};const n=a=>{a.key===Bl&&e()},s=()=>e();return window.addEventListener("storage",n),window.addEventListener(iu,s),()=>{window.removeEventListener("storage",n),window.removeEventListener(iu,s)}}function J6(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(Bl,"1"):window.localStorage.removeItem(Bl),window.dispatchEvent(new Event(iu))}catch{}}function cO(){return i.useSyncExternalStore(lO,oO,()=>!1)}function xs(e){return{...e,column:Vg(e.column),dependencies:Array.isArray(e.dependencies)?e.dependencies:[],steps:Array.isArray(e.steps)?e.steps:[],log:Array.isArray(e.log)?e.log:[]}}function Df(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function dO(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 xd(e,n){if(Df(n.updatedAt,e.updatedAt)<0)return e;if(e.column===n.column)return dO(e,n);const a=Df(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 uO(e){const n=e?.projectId,s=e?.searchQuery,a=e?.sseEnabled??!0,[r,o]=i.useState([]),[l,c]=i.useState(!1),d=i.useRef(l);d.current=l;const u=i.useRef(r),m=i.useRef(0),h=i.useRef(0),f=i.useRef(s),p=i.useRef(null),g=i.useRef(void 0),x=i.useRef(0),w=i.useRef(n);u.current=r,f.current=s,w.current!==n&&(w.current=n,x.current++);const b=1e3,y=i.useCallback(async Z=>{const K=++m.current,A=n,I=Z?.searchQueryOverride??f.current,$=Z?.includeArchivedOverride??d.current;try{const N=await $k(void 0,void 0,A,I,$);if(m.current!==K||n!==A)return;o(N.map(xs)),g.current=Date.now()}catch{if(m.current!==K||n!==A)return;if(Z?.clearOnError){o([]);return}o(N=>N)}},[n]);p.current=y;const S=i.useCallback(async()=>{d.current||(c(!0),d.current=!0,await p.current({includeArchivedOverride:!0}))},[]),k=i.useRef(s);i.useEffect(()=>{if(s===void 0&&k.current===void 0)return;k.current=s;const Z=setTimeout(()=>{y({searchQueryOverride:s})},300);return()=>clearTimeout(Z)},[s]),i.useEffect(()=>{y({clearOnError:!0});const Z=()=>{if(document.visibilityState!=="visible")return;const K=Date.now();K-h.current<b||(h.current=K,y())};return document.addEventListener("visibilitychange",Z),()=>{document.removeEventListener("visibilitychange",Z)}},[y]),i.useEffect(()=>{if(a===!1)return;const Z=x.current,K=n?`?projectId=${encodeURIComponent(n)}`:"",A=()=>x.current!==Z;let I=!0;const $=ne=>{if(A())return;const qe=xs(JSON.parse(ne.data));if(f.current){p.current({searchQueryOverride:f.current});return}o(ee=>{const le=ee.findIndex(B=>B.id===qe.id);if(le===-1)return[...ee,qe];const se=ee[le],re=xd(se,qe);if(re===se)return ee;const J=[...ee];return J[le]=re,J}),g.current=Date.now()},N=ne=>{if(A())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:qe,to:ee}=JSON.parse(ne.data),le=xs(qe),se={...le,column:Vg(ee,le.column)};o(re=>{const J=re.findIndex(ve=>ve.id===se.id);if(J===-1)return[...re,se];const B=[...re];return B[J]=se,B}),g.current=Date.now()},G=ne=>{if(A())return;if(f.current){p.current({searchQueryOverride:f.current});return}const qe=xs(JSON.parse(ne.data));o(ee=>{const le=ee.findIndex(B=>B.id===qe.id);if(le===-1)return[...ee,qe];const se=ee[le],re=xd(se,qe);if(re===se)return ee;const J=[...ee];return J[le]=re,J}),g.current=Date.now()},ge=ne=>{if(A())return;if(f.current){p.current({searchQueryOverride:f.current});return}const qe=xs(JSON.parse(ne.data));o(ee=>ee.filter(le=>le.id!==qe.id))},je=ne=>{if(A())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:qe}=JSON.parse(ne.data),le={...xs(qe),column:"done"};o(se=>{const re=se.findIndex(B=>B.id===le.id);if(re===-1)return[...se,le];const J=[...se];return J[re]=le,J})},ke=ii(`/api/events${K}`,{events:{"task:created":$,"task:moved":N,"task:updated":G,"task:deleted":ge,"task:merged":je},onReconnect:()=>{I&&(A()||p.current())}});return()=>{I=!1,ke()}},[n,a]);const C=i.useCallback(async Z=>{const K=xs(await wg(Z,n));return o(A=>A.some(I=>I.id===K.id)?A:[...A,K]),K},[n]),v=i.useCallback(async(Z,K,A)=>xs(await Lk(Z,K,n,A)),[n]),j=i.useCallback(async Z=>xs(await kg(Z,n)),[n]),P=i.useCallback(async(Z,K)=>xs(await Ok(Z,n,K)),[n]),U=i.useCallback(async Z=>zk(Z,n),[n]),E=i.useCallback(async Z=>xs(await Fk(Z,n)),[n]),R=i.useCallback(async Z=>xs(await Uk(Z,n)),[n]),L=i.useCallback(async Z=>{const K=xs(await Bk(Z,n));return o(A=>A.some(I=>I.id===K.id)?A:[...A,K]),K},[n]),F=i.useCallback(async(Z,K)=>{const A=u.current.find($=>$.id===Z),I=A?{...A,...K,updatedAt:new Date().toISOString()}:void 0;I&&o($=>$.map(N=>N.id===Z?I:N));try{const $=xs(await mi(Z,K,n));return o(N=>N.map(G=>G.id===Z?$:G)),$}catch($){throw A&&o(N=>N.map(G=>G.id===Z?A:G)),$}},[n]),M=i.useCallback(async Z=>{const K=xs(await qk(Z,n));return o(A=>A.map(I=>I.id===Z?K:I)),K},[n]),O=i.useCallback(async Z=>{const K=xs(await Vk(Z,n));return o(A=>A.map(I=>I.id===Z?K:I)),K},[n]),q=i.useCallback(async()=>{const K=(await Wk(n)).map(xs);return o(A=>A.map(I=>K.find(N=>N.id===I.id)||I)),K},[n]),te=i.useCallback(Z=>{if(Z.length===0)return;if(f.current){p.current({searchQueryOverride:f.current});return}const K=Z.map(xs);o(A=>{let I=A;for(const $ of K){const N=I.findIndex(je=>je.id===$.id);if(N===-1){I===A&&(I=[...A]),I.push($);continue}const G=I[N],ge=xd(G,$);ge!==G&&(I===A&&(I=[...A]),I[N]=ge)}return I}),g.current=Date.now()},[]);return{tasks:r,createTask:C,moveTask:v,pauseTask:j,deleteTask:P,mergeTask:U,retryTask:E,resetTask:R,duplicateTask:L,updateTask:F,archiveTask:M,unarchiveTask:O,archiveAllDone:q,loadArchivedTasks:S,includeArchived:l,ingestCreatedTasks:te,lastFetchTimeMs:g.current}}const mO=5e3,hO=1e3;function pO(e){const s=(oS(e)?e.nodeMappings??e.projectNodeMappings??e.pathMappings??[]:[]).filter(a=>!!a?.nodeId&&!!a?.path).map(a=>({nodeId:a.nodeId,nodeName:a.nodeName,path:a.path,available:a.available!==!1}));return s.length>0?s:e.nodeId&&e.path?[{nodeId:e.nodeId,nodeName:e._sourceNodeName,path:e.path,available:!0}]:[]}function Lf(e){return e.map(n=>({...n,nodeMappings:pO(n)}))}function fO(){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 bm();n(Lf(f))}catch(f){o(f instanceof Error?f.message:"Failed to fetch projects")}},[]);i.useEffect(()=>{let f=!1;async function p(){a(!0);const x=performance.now();try{const w=await bm(),b=Lf(w),y=Math.round(performance.now()-x);console.log(`[useProjects] initial fetchProjectsAcrossNodes took ${y}ms (${b.length} projects)`),f||(n(b),o(null))}catch(w){const b=Math.round(performance.now()-x);console.warn(`[useProjects] initial fetch failed after ${b}ms: ${w instanceof Error?w.message:String(w)}`),f||o(w instanceof Error?w.message:"Failed to fetch projects")}finally{f||a(!1)}}p();const g=()=>{if(document.visibilityState!=="visible")return;const x=Date.now();x-c.current<hO||(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()},mO),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,d]);const u=i.useCallback(async f=>{const p=await fS(f);return n(g=>[...g,p]),p},[]),m=i.useCallback(async(f,p)=>{const g=await kS(f,p);return n(x=>x.map(w=>w.id===f?g:w)),g},[]),h=i.useCallback(async f=>{await Ag(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 gO="kb-dashboard-current-project";function bO(e){return e??"local"}function xO(e,n={}){const{nodeId:s=null}=n,[a,r]=i.useState(null),[o,l]=i.useState(!0),c=i.useRef(!1),d=i.useRef(!1),u=i.useRef(null),m=bO(s);i.useEffect(()=>{let p=!1;async function g(){try{const x=await Pa();if(p)return;u.current=x.dashboardCurrentProjectIdByNode??{};const w=u.current[m];if(w){const b=e.find(y=>y.id===w);b&&(r(b),c.current=!0)}if(!w)try{const b=localStorage.getItem(gO);if(b){const y=JSON.parse(b);y?.id&&e.some(k=>k.id===y.id)&&(r(y),c.current=!0,u.current={...u.current,[m]:y.id},await kn({dashboardCurrentProjectIdByNode:u.current}).catch(()=>{}))}}catch{}}catch{}finally{p||l(!1)}}return g(),()=>{p=!0}},[m,e]),i.useEffect(()=>{if(!o){if(a){if(!e.some(x=>x.id===a.id)&&e.length>0){const x=e.find(w=>w.status==="active");r(x||e[0]||null);return}const g={...u.current,[m]:a.id};u.current=g,kn({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,kn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}},[m]),f=i.useCallback(()=>{d.current=!0,r(null);const p={...u.current};delete p[m],u.current=p,kn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:a,setCurrentProject:h,clearCurrentProject:f,loading:o}}const nv=i.createContext(null);function vO({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()},[]),kl.createElement(nv.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function yO(){const e=i.useContext(nv);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const sv="kb-dashboard-theme-mode",iv="kb-dashboard-color-theme",av="kb-dashboard-font-scale-pct",au=100,wO=85,kO=125,rv=[...T0],ru="theme-data",Kr="theme-data.css";function jO(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.startsWith("http://")||e.startsWith("https://")?new URL(`/${Kr}`,e).toString():e.startsWith("file://")?e.endsWith("/")?e.slice(0,-1)+`/${Kr}`:e.replace(/\/[^/]+$/,`/${Kr}`):`/${Kr}`:`/${Kr}`}const Fs=typeof window<"u",NO=Fs?i.useLayoutEffect:i.useEffect;function ov(e){return e==="dark"||e==="light"||e==="system"}function Of(){if(!Fs)return"dark";try{const e=localStorage.getItem(sv);if(ov(e))return e}catch{}return"dark"}function zf(){if(!Fs)return"default";try{const e=localStorage.getItem(iv);if(e&&rv.includes(e))return e}catch{}return"default"}function Ff(e){if(Fs)try{localStorage.setItem(sv,e)}catch{}}function Uf(e){if(Fs)try{localStorage.setItem(iv,e)}catch{}}function bo(e){return typeof e!="number"||!Number.isFinite(e)?au:Math.min(kO,Math.max(wO,Math.round(e)))}function Bf(){if(!Fs)return au;try{const e=Number(localStorage.getItem(av));return bo(e)}catch{return au}}function Hf(e){if(Fs)try{localStorage.setItem(av,String(bo(e)))}catch{}}function SO(e,n){return e==="system"?n?"dark":"light":e}function CO(e,n,s,a){if(!Fs)return;const r=SO(e,a);document.documentElement.setAttribute("data-theme",r),document.documentElement.setAttribute("data-color-theme",n),document.documentElement.style.fontSize=`${bo(s)}%`}function qf(){if(!Fs)return;const e=jO(),n=document.getElementById(ru);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=ru,document.head.appendChild(s)}function Vf(){if(!Fs)return;const e=document.getElementById(ru);e&&e.remove()}function EO(){const[e,n]=i.useState(()=>Of()),[s,a]=i.useState(()=>zf()),[r,o]=i.useState(()=>Bf()),[l,c]=i.useState(!0),[d,u]=i.useState(()=>Fs?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(!Fs||!l)return;let S=!1;return Pa().then(k=>{if(!S&&(ov(k.themeMode)&&!p.current&&(m.current!==k.themeMode&&(m.current=k.themeMode,n(k.themeMode)),Of()!==k.themeMode&&Ff(k.themeMode)),k.colorTheme&&rv.includes(k.colorTheme)&&!g.current&&(h.current!==k.colorTheme&&(h.current=k.colorTheme,a(k.colorTheme)),zf()!==k.colorTheme&&Uf(k.colorTheme)),!x.current)){const C=bo(k.dashboardFontScalePct);f.current!==C&&(f.current=C,o(C)),Bf()!==C&&Hf(C)}}).catch(k=>{console.warn("[useTheme] Failed to hydrate theme from global settings",k)}).finally(()=>{S||c(!1)}),()=>{S=!0}},[l]),i.useEffect(()=>{if(!Fs)return;const S=window.matchMedia("(prefers-color-scheme: dark)"),k=C=>{u(C.matches)};return S.addEventListener("change",k),()=>S.removeEventListener("change",k)},[]),NO(()=>{CO(e,s,r,d)},[e,s,r,d]),i.useEffect(()=>{!Fs||l||(s!=="default"?qf():Vf())},[s,l]);const w=i.useCallback(S=>{p.current=!0,m.current=S,n(S),Ff(S),kn({themeMode:S}).catch(k=>{console.warn("[useTheme] Failed to persist themeMode to global settings",k)})},[]),b=i.useCallback(S=>{g.current=!0,h.current=S,a(S),Uf(S),S!=="default"?qf():Vf(),kn({colorTheme:S}).catch(k=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",k)})},[]),y=i.useCallback(S=>{const k=bo(S);x.current=!0,f.current=k,o(k),Hf(k),kn({dashboardFontScalePct:k}).catch(C=>{console.warn("[useTheme] Failed to persist dashboardFontScalePct to global settings",C)})},[]);return{themeMode:e,colorTheme:s,dashboardFontScalePct:r,setThemeMode:w,setColorTheme:b,setDashboardFontScalePct:y,isSystemDark:d}}function _O(e){const{planningSessions:n}=e,[s,a]=i.useState(!1),[r,o]=i.useState(!1),[l,c]=i.useState(null),[d,u]=i.useState(void 0),[m,h]=i.useState(!1),[f,p]=i.useState(null),[g,x]=i.useState(void 0),[w,b]=i.useState(null),[y,S]=i.useState("definition"),[k,C]=i.useState(null),[v,j]=i.useState(!1),[P,U]=i.useState(void 0),[E,R]=i.useState(!1),[L,F]=i.useState(!1),[M,O]=i.useState(!1),[q,te]=i.useState(null),[Z,K]=i.useState(!1),[A,I]=i.useState(!1),[$,N]=i.useState(void 0),[G,ge]=i.useState(!1),[je,ke]=i.useState(!1),[ne,qe]=i.useState("project"),[ee,le]=i.useState(!1),[se,re]=i.useState(!1),[J,B]=i.useState(!1),[ve,Ne]=i.useState(!1),[H,be]=i.useState(!1),[ce,Me]=i.useState(!1),[Le,He]=i.useState(!1),gt=!!(w||v||s||r||m||A||G||je||ee||se||J||H||ve||M||Z||E||L||ce||Le),Ue=i.useCallback(()=>a(!0),[]),pe=i.useCallback(()=>a(!1),[]),Oe=i.useCallback(()=>o(!0),[]),ze=i.useCallback(jt=>{c(jt),o(!0)},[]),lt=i.useCallback(()=>{const jt=n[0];jt&&(u(jt.id),o(!0))},[n]),Be=i.useCallback(jt=>{u(jt),o(!0)},[]),ye=i.useCallback(()=>{o(!1),c(null),u(void 0)},[]),Y=i.useCallback(jt=>{p(jt),h(!0)},[]),_e=i.useCallback(jt=>{x(jt),h(!0)},[]),ct=i.useCallback(()=>{h(!1),p(null),x(void 0)},[]),pt=i.useCallback((jt,ae="definition",De)=>{b(jt),S(ae),C(De?.origin??null)},[]),de=i.useCallback(jt=>{b(jt),S("changes"),C(null)},[]),Ve=i.useCallback(jt=>{b(ae=>ae&&{...ae,...jt})},[]),Ee=i.useCallback(()=>{b(null),C(null)},[]),$e=i.useCallback(jt=>{U(jt),j(!0)},[]),ut=i.useCallback(()=>{j(!1),U(void 0)},[]),ht=i.useCallback(()=>R(!0),[]),Se=i.useCallback(()=>R(!1),[]),we=i.useCallback(()=>F(!0),[]),Ae=i.useCallback(()=>F(!1),[]),he=i.useCallback(jt=>{te(jt??null),O(!0)},[]),We=i.useCallback(()=>{O(!1),te(null)},[]),me=i.useCallback(()=>K(!0),[]),nt=i.useCallback(()=>K(!1),[]),Ct=i.useCallback(()=>{I(jt=>!jt)},[]),wt=i.useCallback(()=>{I(!1),N(void 0)},[]),$t=i.useCallback(()=>ge(!0),[]),Vt=i.useCallback(()=>ge(!1),[]),Mt=i.useCallback(()=>ke(!0),[]),Dt=i.useCallback(()=>ke(!1),[]),Qt=i.useCallback(jt=>{qe(jt)},[]),Kt=i.useCallback(()=>le(!0),[]),Bt=i.useCallback(()=>le(!1),[]),on=i.useCallback(()=>re(!0),[]),fn=i.useCallback(()=>re(!1),[]),Jt=i.useCallback(()=>B(!0),[]),an=i.useCallback(()=>B(!1),[]),zt=i.useCallback(()=>Ne(!0),[]),en=i.useCallback(()=>Ne(!1),[]),Zt=i.useCallback(()=>be(!0),[]),dn=i.useCallback(()=>be(!1),[]),xe=i.useCallback(async(jt,ae)=>{be(!1),N(ae),I(!0)},[]),Fe=i.useCallback(()=>Me(!0),[]),Ke=i.useCallback(()=>Me(!1),[]),et=i.useCallback(()=>He(!0),[]),Qe=i.useCallback(()=>He(!1),[]),It=i.useCallback((jt,ae)=>{ae(`Created ${jt.id} from planning mode`,"success"),o(!1),c(null)},[]),St=i.useCallback((jt,ae)=>{const De=jt.map(At=>At.id).join(", ");ae(`Created ${De} from planning mode`,"success"),o(!1),c(null)},[]),Ht=i.useCallback((jt,ae)=>{const De=jt.map(At=>At.id).join(", ");ae(`Created ${De} from subtask breakdown`,"success"),h(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:l,planningResumeSessionId:d,isSubtaskOpen:m,subtaskInitialDescription:f,subtaskResumeSessionId:g,detailTask:w,detailTaskInitialTab:y,detailTaskOrigin:k,settingsOpen:v,settingsInitialSection:P,schedulesOpen:E,githubImportOpen:L,usageOpen:M,usageAnchorRect:q,systemStatsOpen:Z,terminalOpen:A,terminalInitialCommand:$,filesOpen:G,todosOpen:je,fileBrowserWorkspace:ne,activityLogOpen:ee,gitManagerOpen:se,workflowStepsOpen:J,agentsOpen:ve,scriptsOpen:H,setupWizardOpen:ce,modelOnboardingOpen:Le,anyModalOpen:gt,openNewTask:Ue,closeNewTask:pe,openPlanning:Oe,openPlanningWithInitialPlan:ze,resumePlanning:lt,openPlanningWithSession:Be,closePlanning:ye,openSubtaskBreakdown:Y,openSubtaskWithSession:_e,closeSubtask:ct,openDetailTask:pt,openDetailWithChangesTab:de,updateDetailTask:Ve,closeDetailTask:Ee,openSettings:$e,closeSettings:ut,openSchedules:ht,closeSchedules:Se,openGitHubImport:we,closeGitHubImport:Ae,openUsage:he,closeUsage:We,openSystemStats:me,closeSystemStats:nt,toggleTerminal:Ct,closeTerminal:wt,openFiles:$t,closeFiles:Vt,openTodos:Mt,closeTodos:Dt,setFileWorkspace:Qt,openActivityLog:Kt,closeActivityLog:Bt,openGitManager:on,closeGitManager:fn,openWorkflowSteps:Jt,closeWorkflowSteps:an,openAgents:zt,closeAgents:en,openScripts:Zt,closeScripts:dn,runScript:xe,openSetupWizard:Fe,closeSetupWizard:Ke,openModelOnboarding:et,closeModelOnboarding:Qe,onPlanningTaskCreated:It,onPlanningTasksCreated:St,onSubtaskTasksCreated:Ht}}function MO(e){const[n,s]=i.useState(2),[a,r]=i.useState("."),[o,l]=i.useState(!0),[c,d]=i.useState(!1),[u,m]=i.useState(!1),[h,f]=i.useState(void 0),[p,g]=i.useState(!1),[x,w]=i.useState(!1),[b,y]=i.useState(!1),[S,k]=i.useState({}),[C,v]=i.useState(!1),[j,P]=i.useState(!1),[U,E]=i.useState(!1),[R,L]=i.useState(!1),[F,M]=i.useState(!0),O=i.useCallback(async()=>{const[I,$]=await Promise.allSettled([Jk(e),Xl(e)]);if(I.status==="fulfilled"&&(s(I.value.maxConcurrent),r(I.value.rootDir)),$.status==="fulfilled"){const N=$.value;l(!!N.autoMerge),d(!!N.globalPause),m(!!N.enginePaused),w(!!N.prAuthAvailable),f(N.taskStuckTimeoutMs),g(N.showQuickChatFAB===!0),k(N.experimentalFeatures??{});const G=N.experimentalFeatures??{};v(G.insights===!0),P(G.memoryView===!0),E(G.devServerView===!0||G.devServer===!0),L(G.todoView===!0);const ge=N.autoReloadOnVersionChange!==!1;M(ge),uc(ge)}y(!0)},[e]);i.useEffect(()=>{y(!1),k({}),v(!1),P(!1),E(!1),L(!1),O()},[O]);const q=i.useCallback(async()=>{const I=!o;l(I);try{await Do({autoMerge:I},e)}catch{l(!I)}},[o,e]),te=i.useCallback(async()=>{const I=!c;d(I);try{await Do({globalPause:I,globalPauseReason:I?"manual":void 0},e)}catch{d(!I)}},[c,e]),Z=i.useCallback(async()=>{const I=!u;m(I);try{await Do({enginePaused:I},e)}catch{m(!I)}},[u,e]),K=i.useCallback(async()=>{const I=!p;g(I);try{await Do({showQuickChatFAB:I},e)}catch{g(!I)}},[p,e]),A=i.useCallback(async()=>{const I=!F;M(I),uc(I);try{await kn({autoReloadOnVersionChange:I})}catch{M(!I),uc(!I)}},[F]);return{maxConcurrent:n,rootDir:a,autoMerge:o,globalPaused:c,enginePaused:u,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:x,settingsLoaded:b,experimentalFeatures:S,insightsEnabled:C,memoryEnabled:j,devServerEnabled:U,todosEnabled:R,autoReloadOnVersionChange:F,toggleAutoMerge:q,toggleGlobalPause:te,toggleEnginePause:Z,toggleShowQuickChatFAB:K,toggleAutoReloadOnVersionChange:A,refresh:O}}function AO(e){const{projectId:n,projects:s,projectsLoading:a,currentProject:r,setCurrentProject:o,addToast:l,openTaskDetail:c,closeTaskDetail:d}=e,u=i.useRef(!1),m=i.useRef(!1),h=i.useRef(null);return i.useEffect(()=>{if(!m.current){const b=window.location.pathname.match(/^\/tasks\/([A-Z]+-\d+)\/?$/);if(b){const y=b[1];if(/^[A-Z]+-\d+$/.test(y)){const S=new URLSearchParams(window.location.search);S.set("task",y);const k=S.toString(),C=window.history.state??{};window.history.replaceState(C,"",k?`/?${k}`:"/"),m.current=!0}}}const p=new URLSearchParams(window.location.search),g=p.get("project"),x=p.get("task");if(!x||a)return;if(g){const b=s.find(y=>y.id===g);if(!b){l(`Project '${g}' not found`,"error");return}r?.id!==b.id&&o(b)}if(u.current)return;u.current=!0,Sa(x,g??n).then(b=>{c(b),h.current=x}).catch(()=>{l(`Task ${x} not found`,"error")})},[n,s,a,r,o,l,c]),{handleDetailClose:i.useCallback(()=>{if(h.current){const p=new URLSearchParams(window.location.search);p.delete("task");const g=p.toString(),x=window.history.state??{};window.history.replaceState(x,"",g?`${window.location.pathname}?${g}`:window.location.pathname),h.current=null}d()},[d])}}function PO(){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 kn({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 kn({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 RO({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;uo().then(({providers:d})=>{const u=d.some(h=>h.authenticated);if(d.length>0&&!u||d.length>0&&u)return Pa().then(h=>{const f=!!(h.defaultProvider&&h.defaultModelId);(h.modelOnboardingComplete===!1||h.modelOnboardingComplete===void 0)&&(!u||!f)&&!wr()?l=!0:!u&&!wr()&&(c=!0)})}).then(()=>{if(o.current){r.current=!1;return}l?(ei("onboarding:auto-triggered",{trigger:"first-run"}),s()):c&&(ei("onboarding:auto-triggered",{trigger:"missing-provider"}),a("authentication"))}).catch(()=>{})},[e,n,s,a])}const Wf="kb-update-banner-dismissed";function IO(){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(Wf)==="true";u(h);let f=!1;return Yk().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(Wf,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:d,dismiss:m}}const TO=["board","list","graph","agents","missions","chat","documents","research","evals","skills","mailbox","insights","memory","devserver","dev-server"];function $O(e){return e!==null&&TO.includes(e)}function vd(e){return e!==null&&($O(e)||rr(e))}const DO=Ro("roadmap-planner","roadmaps");function Kf(e){return e==="devserver"?"dev-server":e}function Gf(e){return e!=="roadmaps"?"board":y0("roadmap-planner","roadmaps")?DO:"board"}function LO(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=Dn("kb-dashboard-task-view");return b==="roadmaps"?Gf(b):vd(b)?b:"board"}),g=i.useRef(!1);i.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),i.useEffect(()=>{const b=Dn("kb-dashboard-task-view",r?.id);if(b==="roadmaps")p(Gf(b));else if(vd(b)){const y=!g.current&&b==="devserver";p(y?"devserver":Kf(b))}else p("board");r?.id&&(g.current=!0)},[r?.id]),i.useEffect(()=>{os("kb-dashboard-task-view",f,r?.id)},[r?.id,f]),i.useEffect(()=>{if(typeof window>"u")return;const b=new URLSearchParams(window.location.search).get("view");b&&vd(b)&&p(Kf(b))},[]),i.useEffect(()=>{n||a||r&&m==="overview"&&h("project")},[n,a,r,m]),i.useEffect(()=>{if(n||a||l||s||o>0||r)return;const b=window.setTimeout(()=>{c()},500);return()=>window.clearTimeout(b)},[n,s,o,a,r,l,c]);const x=i.useCallback(b=>{p(b)},[]),w=i.useCallback(()=>{const b=["dark","light","system"],y=b.indexOf(d),S=b[(y+1)%b.length];u(S)},[d,u]);return{viewMode:m,setViewMode:h,taskView:f,setTaskView:p,handleChangeTaskView:x,handleToggleTheme:w}}function OO(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 yd=new Map,zO=6e4;function FO(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";yd.delete(h),d(f=>f+1)},[e]);return i.useEffect(()=>{const h=e??"default";let f=!1;async function p(){const g=yd.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;yd.set(h,{views:x,expiresAt:Date.now()+zO}),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 UO({taskView:e,context:n}){return t.jsx(w0,{viewId:e,context:n})}let Jf=!1;function lv(){Jf||(Jf=!0,Bm("fusion-plugin-dependency-graph","graph",i.lazy(async()=>({default:(await gn(()=>import("./dashboard-view-lR7YYmSC.js"),__vite__mapDeps([24,1,25,5,6,26]))).DependencyGraphDashboardView}))),Bm("roadmap-planner","roadmaps",i.lazy(async()=>({default:(await gn(()=>import("./dashboard-view-CyWN-d02.js"),__vite__mapDeps([27,1,25,28]))).RoadmapDashboardView}))))}function BO(e){const{setCurrentProject:n,clearCurrentProject:s,setViewMode:a,currentProject:r,refreshProjects:o,toggleFavoriteProvider:l,toggleFavoriteModel:c,addToast:d,openSettings:u,openSetupWizard:m,closeSetupWizard:h,closeModelOnboarding:f}=e,p=i.useCallback(P=>{n(P),a("project")},[n,a]),g=i.useCallback(()=>{s(),a("overview")},[s,a]),x=i.useCallback(()=>{u()},[u]),w=i.useCallback(()=>{m()},[m]),b=i.useCallback(P=>{h(),n(P),a("project"),d(`Project ${P.name} registered successfully`,"success"),o()},[h,n,a,d,o]),y=i.useCallback(()=>{f()},[f]),S=i.useCallback(async P=>{try{await yS(P.id),d(`Project ${P.name} paused`,"success"),await o()}catch{d(`Failed to pause project ${P.name}`,"error")}},[d,o]),k=i.useCallback(async P=>{try{await wS(P.id),d(`Project ${P.name} resumed`,"success"),await o()}catch{d(`Failed to resume project ${P.name}`,"error")}},[d,o]),C=i.useCallback(async P=>{try{await Ag(P.id),d(`Project ${P.name} removed`,"success"),r?.id===P.id&&(s(),a("overview")),await o()}catch{d(`Failed to remove project ${P.name}`,"error")}},[r,s,a,d,o]),v=i.useCallback(async P=>{try{await l(P)}catch{d("Failed to update favorites","error")}},[l,d]),j=i.useCallback(async P=>{try{await c(P)}catch{d("Failed to update model favorites","error")}},[c,d]);return{handleSelectProject:p,handleViewAllProjects:g,handleOpenSettings:x,handleAddProject:w,handleSetupComplete:b,handleModelOnboardingComplete:y,handlePauseProject:S,handleResumeProject:k,handleRemoveProject:C,handleToggleFavorite:v,handleToggleModelFavorite:j}}function HO(e){const{createTask:n,ingestCreatedTasks:s,onPlanningTaskCreated:a,onPlanningTasksCreated:r,onSubtaskTasksCreated:o,addToast:l}=e,c=i.useCallback(async p=>n({...p,column:"triage",source:{sourceType:"dashboard_ui"}}),[n]),d=i.useCallback(async p=>await n({...p,column:"triage",source:{sourceType:"dashboard_ui"}}),[n]),u=i.useCallback(p=>{s([p]),a(p,l)},[l,s,a]),m=i.useCallback(p=>{s(p),r(p,l)},[l,s,r]),h=i.useCallback(p=>{s(p),o(p,l)},[l,s,o]),f=i.useCallback(p=>{l(`Imported ${p.id} from GitHub`,"success")},[l]);return{handleBoardQuickCreate:c,handleModalCreate:d,handlePlanningTaskCreated:u,handlePlanningTasksCreated:m,handleSubtaskTasksCreated:h,handleGitHubImport:f}}function qO(e,n){const{projectId:s,searchQuery:a}=n??{},[r,o]=i.useState([]),[l,c]=i.useState([]),[d,u]=i.useState(null),[m,h]=i.useState(!1),[f,p]=i.useState(null),g=i.useRef(null),x=i.useCallback(async()=>{if(!e){o([]),c([]),u(null),h(!1),p(null);return}g.current?.abort();const b=new AbortController;g.current=b,h(!0),p(null);try{const y=[H1(e),q1(e)];s&&(y.push(V1(e,s,a)),y.push(W1(e,s)));const S=await Promise.allSettled(y);if(b.signal.aborted)return;const k=S[0],C=S[1];if(k.status==="rejected"){p(`Failed to fetch node health: ${k.reason}`),h(!1);return}if(u(k.value),C.status==="rejected"){p(`Failed to fetch projects: ${C.reason}`),h(!1);return}if(o(C.value),s&&S[2]){const v=S[2];if(v.status==="rejected"){p(`Failed to fetch tasks: ${v.reason}`),h(!1);return}v.status==="fulfilled"&&c(v.value)}h(!1)}catch(y){b.signal.aborted||(p(y instanceof Error?y.message:"Unknown error"),h(!1))}},[e,s,a]);i.useEffect(()=>(x(),()=>{g.current?.abort()}),[x]);const w=i.useCallback(()=>{x()},[x]);return{projects:r,tasks:l,health:d,loading:m,error:f,refresh:w}}function VO(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 ii(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 WO="fusion-dashboard-current-node",cv=i.createContext(null);function KO({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 Pa();if(m)return;l.current=f.dashboardCurrentNodeId;const p=f.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const g=localStorage.getItem(WO);if(g){const x=JSON.parse(g);x?.id&&x?.type==="remote"&&(l.current=x.id,await kn({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,kn({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,kn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,a]);const c=i.useCallback(m=>{s(m)},[]),d=i.useCallback(()=>{s(null),l.current=void 0,kn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),u={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:d};return t.jsx(cv.Provider,{value:u,children:e})}function GO(){const e=i.useContext(cv);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}const JO=["shellKind","shellMode","profileId","serverBaseUrl","serverLabel","shellCanOpenConnectionManager","hostKind","mode","connectionId","serverUrl","canOpenConnectionManager"],YO=["__FUSION_SHELL_HOST_CONTEXT__","__fusionShellHostContext","__FUSION_SHELL_CONTEXT__"];let Hl=null,Yf=!1;function QO(e){if(typeof e=="boolean")return e;if(typeof e=="string"){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1}}function XO(e){if(!(typeof e!="string"||e.trim().length===0))try{const n=new URL(e);return n.protocol!=="http:"&&n.protocol!=="https:"?void 0:n.toString().replace(/\/$/,"")}catch{return}}function dv(e){if(e==="browser"||e==="desktop-shell"||e==="mobile-shell")return e;if(e==="desktop")return"desktop-shell";if(e==="mobile")return"mobile-shell"}function ZO(e){return e==="local"||e==="remote"?e:void 0}function uv(e){const n=ZO(e.mode),s=typeof e.connectionId=="string"&&e.connectionId.trim()?e.connectionId:void 0,a=XO(e.serverUrl),r=QO(e.canOpenConnectionManager);return{kind:e.kind,...n?{mode:n}:{},...s?{connectionId:s}:{},...a?{serverUrl:a}:{},...r!==void 0?{canOpenConnectionManager:r}:{}}}function ez(e){for(const n of YO){const s=e[n];if(!s||typeof s!="object")continue;const a=s,r=dv(a.kind??a.shellKind??a.hostKind);if(r)return r==="browser"?{kind:r}:uv({kind:r,mode:a.mode??a.shellMode,connectionId:a.connectionId??a.profileId,serverUrl:a.serverUrl??a.serverBaseUrl,canOpenConnectionManager:a.canOpenConnectionManager??a.shellCanOpenConnectionManager})}return null}function tz(e){let n;try{n=new URL(e.location.href)}catch{return null}const s=n.searchParams,a=dv(s.get("hostKind")??s.get("kind")??s.get("shellKind"));return a?a==="browser"?{kind:a}:uv({kind:a,mode:s.get("mode")??s.get("shellMode"),connectionId:s.get("connectionId")??s.get("profileId"),serverUrl:s.get("serverUrl")??s.get("serverBaseUrl"),canOpenConnectionManager:s.get("canOpenConnectionManager")??s.get("shellCanOpenConnectionManager")}):null}function nz(e){try{const n=new URL(e.location.href);let s=!1;for(const r of JO)n.searchParams.has(r)&&(n.searchParams.delete(r),s=!0);if(!s)return;const a=n.pathname+(n.search?n.search:"")+n.hash;e.history.replaceState(e.history.state,"",a)}catch{}}function sz(e=window){const n=ez(e);if(n)return n;const s=tz(e);return s||(typeof e.fusionAPI<"u"?{kind:"desktop-shell"}:{kind:"browser"})}function mv(e=window){return!Yf&&typeof window<"u"&&(Hl=sz(e),nz(e),Yf=!0),Hl??{kind:"browser"}}function iz(){return Hl||(typeof window>"u"?{kind:"browser"}:mv(window))}const az={kind:"browser"},hv=i.createContext({host:az,isNativeShell:!1,kind:"browser"});function rz(e){const n=e.kind!=="browser";return{host:e,isNativeShell:n,kind:e.kind,...n?{mode:e.mode,connectionId:e.connectionId,serverUrl:e.serverUrl,canOpenConnectionManager:e.canOpenConnectionManager}:{}}}function oz({children:e}){const n=i.useMemo(()=>rz(iz()),[]);return t.jsx(hv.Provider,{value:n,children:e})}function lz(){return i.useContext(hv)}function cz(e,n){const s=new URL(e);return n&&s.searchParams.set("rt",n),s.toString()}function dz({open:e,shellApi:n,shellState:s,onComplete:a}){const[r,o]=i.useState(s.desktopMode??"remote"),[l,c]=i.useState("Remote Server"),[d,u]=i.useState(""),[m,h]=i.useState(""),[f,p]=i.useState(null),[g,x]=i.useState(!1),[w,b]=i.useState(!1),y=s.host==="desktop-shell";i.useEffect(()=>{y&&o(s.desktopMode??"remote")},[y,s.desktopMode]);const S=i.useMemo(()=>y&&r==="local"?!0:d.trim().length>0,[y,r,d]);return e?t.jsx("div",{className:"modal-overlay open",children:t.jsxs("div",{className:"modal native-shell-onboarding-modal",children:[t.jsx("div",{className:"modal-header",children:t.jsx("h2",{children:"Welcome to Fusion"})}),t.jsxs("div",{className:"native-shell-onboarding-body",children:[t.jsx("p",{children:"Fusion helps you plan, run, and review AI-assisted engineering work."}),y&&t.jsxs("div",{className:"native-shell-onboarding-mode-row",children:[t.jsx("button",{type:"button",className:`btn ${r==="local"?"btn-primary":""}`,onClick:()=>o("local"),children:"Local Fusion"}),t.jsx("button",{type:"button",className:`btn ${r==="remote"?"btn-primary":""}`,onClick:()=>o("remote"),children:"Remote Server"})]}),(!y||r==="remote")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn",onClick:async()=>{p(null),x(!0);try{const k=await n.startQrScan();u(k.serverUrl),h(k.authToken??"")}catch(k){p(k.message)}finally{x(!1)}},disabled:g,children:g?"Scanning…":"Scan QR"}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-profile-name",children:"Profile name"}),t.jsx("input",{id:"native-shell-onboarding-profile-name",className:"input",value:l,onChange:k=>c(k.target.value)}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-server-url",children:"Server URL"}),t.jsx("input",{id:"native-shell-onboarding-server-url",className:"input",value:d,onChange:k=>u(k.target.value),placeholder:"https://your-fusion-host"}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-auth-token",children:"Auth token (optional)"}),t.jsx("input",{id:"native-shell-onboarding-auth-token",className:"input",type:"password",value:m,onChange:k=>h(k.target.value)})]}),f&&t.jsx("p",{className:"form-error",role:"alert",children:f})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{type:"button",className:"btn btn-primary",disabled:!S||w,onClick:async()=>{p(null),b(!0);try{if(y&&r==="local"){await n.setDesktopMode("local"),a();return}const k=await n.saveProfile({name:l.trim()||"Remote Server",serverUrl:d,authToken:m||null});if(y&&await n.setDesktopMode("remote"),await n.setActiveProfile(k.id),typeof window<"u"&&s.host!=="web"){window.location.href=cz(k.serverUrl,k.authToken??null);return}a()}catch(k){p(k.message)}finally{b(!1)}},children:w?"Saving…":"Continue"})})]})}):null}function uz({open:e,shellApi:n,shellState:s,onClose:a}){const r=i.useMemo(()=>s.profiles.find(v=>v.id===s.activeProfileId)??null,[s.activeProfileId,s.profiles]),[o,l]=i.useState(null),[c,d]=i.useState({}),[u,m]=i.useState(null),[h,f]=i.useState(null);if(!e)return null;const p=o==="__new__",g=p?null:s.profiles.find(v=>v.id===o)??r,x=c.name??g?.name??"",w=c.serverUrl??g?.serverUrl??"",b=c.authToken??g?.authToken??"",y=()=>{l(null),d({}),f(null)},S=async()=>{f(null);try{const v=new URL(w.trim());if(!/^https?:$/.test(v.protocol))throw new Error("Server URL must use http or https");const j=await n.saveProfile({id:p?void 0:o??g?.id,name:x||"Remote Server",serverUrl:w,authToken:b||null});await n.setActiveProfile(j.id),l(j.id),d({})}catch(v){f(v.message)}},k=async()=>{f(null);try{const v=await n.startQrScan();l("__new__"),d({name:"",serverUrl:v.serverUrl,authToken:v.authToken??""})}catch(v){f(v.message)}},C=async()=>{u&&(await n.deleteProfile(u.id),m(null),y())};return t.jsx("div",{className:"modal-overlay open",children:t.jsxs("div",{className:"modal native-shell-connection-manager",role:"dialog","aria-label":"Connection Manager",children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h2",{children:"Connection Manager"}),t.jsx("button",{type:"button",className:"modal-close",onClick:a,"aria-label":"Close",children:"×"})]}),s.host==="desktop-shell"&&t.jsxs("div",{className:"native-shell-connection-manager__mode-row",children:[t.jsx("button",{type:"button",className:`btn ${s.desktopMode==="local"?"btn-primary":""}`,onClick:()=>void n.setDesktopMode("local"),children:"Local"}),t.jsx("button",{type:"button",className:`btn ${s.desktopMode!=="local"?"btn-primary":""}`,onClick:()=>void n.setDesktopMode("remote"),children:"Remote"})]}),t.jsx("div",{className:"native-shell-connection-manager__profiles",children:s.profiles.length===0?t.jsxs("div",{className:"card native-shell-connection-manager__empty-state",children:[t.jsx("p",{className:"settings-muted",children:"No remote servers saved yet."}),t.jsxs("div",{className:"native-shell-connection-manager__profile-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{l("__new__"),d({name:"",serverUrl:"",authToken:""}),f(null)},children:"Add server"}),s.host==="mobile-shell"&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void k(),children:"Scan QR"})]})]}):s.profiles.map(v=>t.jsxs("div",{className:"card native-shell-connection-manager__profile",children:[t.jsxs("div",{children:[t.jsx("strong",{children:v.name}),t.jsx("div",{className:"settings-muted",children:v.serverUrl}),v.id===s.activeProfileId&&t.jsx("span",{className:"native-shell-connection-manager__active-pill",children:"Active"})]}),t.jsxs("div",{className:"native-shell-connection-manager__profile-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm","aria-label":`Edit ${v.name}`,onClick:()=>{l(v.id),d(v)},children:"Edit"}),t.jsx("button",{type:"button",className:"btn btn-sm","aria-label":`Use ${v.name}`,onClick:()=>void n.setActiveProfile(v.id),children:"Use"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-danger","aria-label":`Delete ${v.name}`,onClick:()=>m(v),children:"Delete"})]})]},v.id))}),t.jsxs("div",{className:"native-shell-connection-manager__mode-row",children:[t.jsx("button",{type:"button",className:"btn",onClick:()=>{l("__new__"),d({name:"",serverUrl:"",authToken:""}),f(null)},children:"Add connection"}),s.host==="mobile-shell"&&t.jsx("button",{type:"button",className:"btn",onClick:()=>void k(),children:"Scan QR"})]}),t.jsxs("div",{className:"form-group native-shell-connection-manager__editor",children:[t.jsx("label",{htmlFor:"native-shell-connection-manager-name",children:"Name"}),t.jsx("input",{id:"native-shell-connection-manager-name",className:"input",value:x,onChange:v=>d(j=>({...j,name:v.target.value}))}),t.jsx("label",{htmlFor:"native-shell-connection-manager-url",children:"Server URL"}),t.jsx("input",{id:"native-shell-connection-manager-url",className:"input",value:w,onChange:v=>d(j=>({...j,serverUrl:v.target.value}))}),t.jsx("label",{htmlFor:"native-shell-connection-manager-token",children:"Auth token (optional)"}),t.jsx("input",{id:"native-shell-connection-manager-token",className:"input",type:"password",value:b??"",onChange:v=>d(j=>({...j,authToken:v.target.value}))}),h&&t.jsx("p",{className:"form-error",role:"alert",children:h})]}),u&&t.jsxs("div",{className:"native-shell-connection-manager__delete-confirm",role:"alertdialog","aria-label":"Delete server confirmation",children:[t.jsxs("p",{children:["Delete ",t.jsx("strong",{children:u.name}),"? This removes the saved profile."]}),t.jsxs("div",{className:"native-shell-connection-manager__profile-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>m(null),children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>void C(),children:"Delete"})]})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:a,children:"Close"}),t.jsx("button",{type:"button",className:"btn",onClick:y,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void S(),disabled:!w.trim(),children:"Save"})]})]})})}function mz(e){if(e.hostKind==="desktop-shell"&&e.mode==="local")return{title:"Desktop local mode",actionLabel:"Switch server",dotClassName:"status-dot status-dot--online"};const n=e.profileLabel??e.profileId,s=e.serverOrigin,a=n&&s?`${n} · ${s}`:n??s;return e.mode==="remote"?{title:a??"Connection info unavailable",actionLabel:e.hostKind==="desktop-shell"?"Switch server":"Manage connections",dotClassName:a?"status-dot status-dot--online":"status-dot status-dot--pending"}:{title:a??"Connection info unavailable",actionLabel:"Manage connections",dotClassName:a?"status-dot status-dot--online":"status-dot status-dot--pending"}}function Qf({status:e,onError:n}){if(e.hostKind==="browser"||!e.available)return null;const s=mz(e),a=i.useCallback(async()=>{const r=await e.openConnectionManager();!r.ok&&r.reason==="failed"&&n?.(r.error??"Failed to open connection manager")},[n,e]);return t.jsxs("button",{type:"button",className:"btn shell-connection-status",onClick:()=>void a(),"data-testid":"shell-connection-status-button",children:[t.jsx("span",{className:s.dotClassName,"aria-hidden":"true"}),t.jsx("span",{className:"shell-connection-status__kind",children:e.hostKind==="desktop-shell"?"Desktop":"Mobile"}),t.jsx("span",{className:"shell-connection-status__summary",title:s.title,children:s.title}),t.jsx("span",{className:"shell-connection-status__action",children:s.actionLabel})]})}function hz(e){if(e)try{return new URL(e).origin}catch{return}}function pz(e,n){const s=e.profiles.find(a=>a.id===e.activeProfileId)??null;return s||(n.kind==="browser"||!n.connectionId?null:e.profiles.find(a=>a.id===n.connectionId)??null)}async function fz(e){if(!e?.getState)return null;try{return await e.getState()}catch{return null}}async function gz(e,n=window){const s=n.fusionAPI,a=n.fusionShell,r=await fz(a),o=r?pz(r,e):null,l=e.kind==="browser"?void 0:e.mode??r?.desktopMode,c=o?.id??(e.kind==="browser"?void 0:e.connectionId),d=o?.name,u=hz(o?.serverUrl??(e.kind==="browser"?void 0:e.serverUrl)),m=e.kind==="desktop-shell"&&typeof s?.openConnectionManager=="function",h=e.kind==="mobile-shell"&&typeof a?.openConnectionManager=="function",f=m||h;return{hostKind:e.kind,available:f,...l?{mode:l}:{},...c?{profileId:c}:{},...d?{profileLabel:d}:{},...u?{serverOrigin:u}:{},openConnectionManager:async()=>{try{return m?(await s.openConnectionManager?.(),{ok:!0}):h?(await a.openConnectionManager(),{ok:!0}):{ok:!1,reason:"unsupported"}}catch(p){return{ok:!1,reason:"failed",error:p instanceof Error?p.message:String(p)}}}}}function bz({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&&(Sk(l),window.location.reload())},[n]),o=i.useCallback(()=>{Ck(),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 xz=200,vz=i.lazy(()=>gn(()=>import("./AgentsView-BkB9FiMT.js"),__vite__mapDeps([29,1,3,4,30,15,5,6,31])).then(e=>({default:e.AgentsView}))),yz=i.lazy(()=>gn(()=>import("./DocumentsView-BEg1CQAk.js"),__vite__mapDeps([32,1,5,6,33])).then(e=>({default:e.DocumentsView}))),wz=i.lazy(()=>gn(()=>import("./InsightsView-BX5bSF1J.js"),__vite__mapDeps([34,1,22,5,6,35])).then(e=>({default:e.InsightsView}))),kz=i.lazy(()=>gn(()=>import("./ResearchView-B256Lr8I.js"),__vite__mapDeps([36,1,5,6,37])).then(e=>({default:e.ResearchView}))),jz=i.lazy(()=>gn(()=>import("./EvalsView-Berf9bQm.js"),__vite__mapDeps([38,1,5,6,39])).then(e=>({default:e.EvalsView}))),Nz=i.lazy(()=>gn(()=>import("./NodesView-DLUOBLf6.js"),__vite__mapDeps([40,1,17,30,5,6,41])).then(e=>({default:e.NodesView}))),Sz=i.lazy(()=>gn(()=>import("./ChatView-B_-B8fqu.js"),__vite__mapDeps([42,1,5,6,43])).then(e=>({default:e.ChatView}))),Cz=i.lazy(()=>gn(()=>import("./SkillsView-CP8JX0P_.js"),__vite__mapDeps([44,1,5,6,45])).then(e=>({default:e.SkillsView}))),Ez=i.lazy(()=>gn(()=>import("./MemoryView-CKElJY_3.js"),__vite__mapDeps([46,1,20,21,5,6,47])).then(e=>({default:e.MemoryView}))),_z=i.lazy(()=>gn(()=>import("./DevServerView-BkvtjZBa.js"),__vite__mapDeps([48,1,5,6,49])).then(e=>({default:e.DevServerView})));i.lazy(()=>gn(()=>import("./TodoView-DCRIkDZ-.js"),__vite__mapDeps([11,1,5,6,12])).then(e=>({default:e.TodoView})));function Mz(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{gn(()=>import("./AgentsView-BkB9FiMT.js"),__vite__mapDeps([29,1,3,4,30,15,5,6,31])),gn(()=>import("./DocumentsView-BEg1CQAk.js"),__vite__mapDeps([32,1,5,6,33])),gn(()=>import("./InsightsView-BX5bSF1J.js"),__vite__mapDeps([34,1,22,5,6,35])),gn(()=>import("./ResearchView-B256Lr8I.js"),__vite__mapDeps([36,1,5,6,37])),gn(()=>import("./EvalsView-Berf9bQm.js"),__vite__mapDeps([38,1,5,6,39])),gn(()=>import("./NodesView-DLUOBLf6.js"),__vite__mapDeps([40,1,17,30,5,6,41])),gn(()=>import("./ChatView-B_-B8fqu.js"),__vite__mapDeps([42,1,5,6,43])),gn(()=>import("./SkillsView-CP8JX0P_.js"),__vite__mapDeps([44,1,5,6,45])),gn(()=>import("./MemoryView-CKElJY_3.js"),__vite__mapDeps([46,1,20,21,5,6,47])),gn(()=>import("./DevServerView-BkvtjZBa.js"),__vite__mapDeps([48,1,5,6,49])),gn(()=>import("./TodoView-DCRIkDZ-.js"),__vite__mapDeps([11,1,5,6,12]))})}lv();const wd="kb-setup-warning-dismissed",Az="kb-chat-active-session",Xf="kb-dashboard-working-branch-filter",Zf="kb-dashboard-base-branch-filter",eg="__fusion:no-branch__",pv="fusion:approval-banner-dismissed";function Pz(e,n){return e==="awaiting-approval"&&n!=="awaiting-approval"}function tg(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Rz(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(pv);if(!e)return new Map;const n=JSON.parse(e),s=new Map;for(const[a,r]of Object.entries(n))typeof r=="number"&&Number.isFinite(r)&&s.set(a,r);return s}catch{return new Map}}function ng(e){if(!(typeof window>"u"))try{const n={};for(const[s,a]of e)n[s]=a;window.localStorage.setItem(pv,JSON.stringify(n))}catch{}}function Iz(e,n){const s=new URL(e);return n&&s.searchParams.set("rt",n),s.toString()}function Tz(e,n,s){return!n||s||e.host==="web"?!1:e.host==="mobile-shell"?!e.activeProfileId:e.desktopMode==="local"?!1:!e.activeProfileId}function $z(){const{toasts:e,addToast:n,removeToast:s}=yO(),{shellApi:a,state:r,ready:o,openConnectionManagerSignal:l}=qx(),c=lz();i.useEffect(()=>{Mz()},[]);const{projects:d,loading:u,error:m,refresh:h}=fO(),{nodes:f}=tc(),{currentNode:p,currentNodeId:g,isRemote:x,setCurrentNode:w,clearCurrentNode:b}=GO(),{currentProject:y,setCurrentProject:S,clearCurrentProject:k,loading:C}=xO(d,{nodeId:g}),{hasAiProvider:v,hasGithub:j,loading:P,hasWarnings:U}=Fx(y?.id),{updateAvailable:E,latestVersion:R,currentVersion:L,dismissed:F,dismiss:M}=IO();i.useEffect(()=>{if(g&&!p&&f.length>0){const Ge=f.find(Rt=>Rt.id===g);if(Ge){w(Ge);return}}g&&f.length>0&&(f.some(Rt=>Rt.id===g)||b())},[g,p,f,w,b]);const[O,q]=i.useState(""),[te,Z]=i.useState(""),[K,A]=i.useState("");i.useEffect(()=>{Z(Dn(Xf,y?.id)??""),A(Dn(Zf,y?.id)??"")},[y?.id]);const I=i.useCallback(Ge=>{Z(Ge),os(Xf,Ge,y?.id)},[y?.id]),$=i.useCallback(Ge=>{A(Ge),os(Zf,Ge,y?.id)},[y?.id]),N=qO(g,{projectId:y?.id,searchQuery:O||void 0});VO(g);const G=x&&N.projects.length>0?N.projects:d,{themeMode:ge,colorTheme:je,dashboardFontScalePct:ke,setThemeMode:ne,setColorTheme:qe,setDashboardFontScalePct:ee}=EO(),{sessions:le,generating:se,needsInput:re,planningSessions:J,dismissSession:B}=rO(y?.id),ve=le.filter(Ge=>Ge.status==="awaiting_input"||Ge.status==="error"),Ne=cO(),H=_O({projectId:y?.id,planningSessions:J}),ce=Ys()==="mobile",{pushNav:Me,replaceCurrent:Le}=OO({enabled:!0}),{viewMode:He,setViewMode:gt,taskView:Ue,handleChangeTaskView:pe}=LO({projectsLoading:u,projectsError:m,currentProjectLoading:C,currentProject:y,projectsLength:d.length,setupWizardOpen:H.setupWizardOpen,openSetupWizard:H.openSetupWizard,themeMode:ge,setThemeMode:ne}),{views:Oe}=FO(y?.id),ze=i.useMemo(()=>{const Ge=Oe.find(Rt=>Rt.pluginId==="fusion-plugin-dependency-graph"&&Rt.view.viewId==="graph");return Ge?`plugin:${Ge.pluginId}:${Ge.view.viewId}`:null},[Oe]),lt=i.useCallback(Ge=>{Ge==="missions"&&(Lt(void 0),Pe(void 0),bt(void 0));const Rt=Ue;pe(Ge),Rt!==Ge&&Me({type:"view",revert:()=>pe(Rt)})},[pe,Ue,Me]),Be=Ue==="board"||Ue==="list",{tasks:ye,createTask:Y,moveTask:_e,pauseTask:ct,deleteTask:pt,mergeTask:de,retryTask:Ve,resetTask:Ee,updateTask:$e,duplicateTask:ut,archiveTask:ht,unarchiveTask:Se,archiveAllDone:we,loadArchivedTasks:Ae,ingestCreatedTasks:he,lastFetchTimeMs:We}=uO({...y?{projectId:y.id}:{},searchQuery:O||void 0,sseEnabled:Be}),me=x&&N.tasks.length>0?N.tasks:ye,[nt,Ct]=i.useState(!1),[wt,$t]=i.useState(0),Vt=i.useRef(performance.now()),Mt=i.useRef(!1),Dt=i.useRef(!1),Qt=i.useMemo(()=>u?"projects":C?"project":"tasks",[u,C]);i.useEffect(()=>{if(!u&&!Mt.current){Mt.current=!0;const Ge=`projects loaded at ${Math.round(performance.now()-Vt.current)}ms from mount`;console.log(`[App] ${Ge}`)}if(!C&&!Dt.current){Dt.current=!0;const Ge=`current-project resolved at ${Math.round(performance.now()-Vt.current)}ms from mount`;console.log(`[App] ${Ge}`)}},[u,C]),i.useEffect(()=>{if(nt||u||C)return;const Ge=performance.now(),Rt=window.setTimeout(()=>{const cn=`dashboard ready at ${Math.round(performance.now()-Vt.current)}ms from mount (settle delay=${Math.round(performance.now()-Ge)}ms)`;console.log(`[App] ${cn}`),Ct(!0)},xz);return()=>{window.clearTimeout(Rt)}},[nt,u,C]);const{keyboardOpen:Kt}=Wi({enabled:ce}),Bt=ce&&Kt&&!H.anyModalOpen;vi(Bt);const[on,fn]=i.useState(0),[Jt,an]=i.useState(0),[zt,en]=i.useState(!1),[Zt,dn]=i.useState(null),xe=i.useRef(new Map),Fe=i.useRef(new Set),Ke=i.useRef(Rz()),et=i.useCallback(()=>{$g(y?.id).then(Ge=>{fn(Ge.unreadCount),an(Ge.pendingApprovalCount??0)}).catch(Ge=>{console.warn("[App] Failed to fetch mailbox unread count:",Ge)})},[y?.id]);i.useEffect(()=>{const Ge=new Map,Rt=new Set;for(const cn of ye)Ge.set(cn.id,cn.status),cn.status==="awaiting-approval"&&Rt.add(`task:${cn.id}`);xe.current=Ge,Fe.current=Rt},[ye]),i.useEffect(()=>{et();const Ge=new URLSearchParams;y?.id&&Ge.set("projectId",y.id);const Rt=Ge.size>0?`?${Ge.toString()}`:"",cn=is=>{const Rn=Ke.current.get(is.dedupeKey);Rn!==void 0&&is.updatedAtMs<=Rn||dn(is)};return ii(`/api/events${Rt}`,{onReconnect:et,events:{"message:sent":et,"message:received":et,"message:read":et,"message:deleted":et,"approval:requested":is=>{et();try{const Rn=JSON.parse(is.data),$s=Rn.id?`approval:${Rn.id}`:Rn.taskId?`task:${Rn.taskId}`:void 0;if(!$s||Fe.current.has($s))return;Fe.current.add($s),cn({dedupeKey:$s,updatedAtMs:tg(Rn.updatedAt??Rn.createdAt)})}catch{}},"approval:updated":et,"approval:decided":et,"task:updated":is=>{try{const Rn=JSON.parse(is.data);if(!Rn?.id)return;const $s=`task:${Rn.id}`,V=xe.current.get(Rn.id);if(xe.current.set(Rn.id,Rn.status),Rn.status!=="awaiting-approval"){Fe.current.delete($s),Ke.current.delete($s),ng(Ke.current);return}if(Fe.current.has($s))return;Pz(Rn.status,V)&&(Fe.current.add($s),cn({dedupeKey:$s,updatedAtMs:tg(Rn.updatedAt)}),et())}catch{}}}})},[y?.id,et]),i.useEffect(()=>{Ue==="chat"&&en(!1)},[Ue]),i.useEffect(()=>{const Ge=new URLSearchParams;y?.id&&Ge.set("projectId",y.id);const Rt=Ge.size>0?`?${Ge.toString()}`:"";return ii(`/api/events${Rt}`,{events:{"chat:message:added":cn=>{try{const is=JSON.parse(cn.data),Rn=Dn(Az,y?.id);if(!Rn||is.role!=="assistant"||Ue==="chat"||is.sessionId!==Rn||is.projectId&&y?.id&&is.projectId!==y.id)return;en(!0)}catch{}}}})},[y?.id,Ue]);const Qe=i.useMemo(()=>Array.from(new Set(me.map(Ge=>Ge.branch?.trim()).filter(Ge=>!!(Ge&&Ge.length>0)))).sort((Ge,Rt)=>Ge.localeCompare(Rt)),[me]),It=i.useMemo(()=>Array.from(new Set(me.map(Ge=>Ge.baseBranch?.trim()).filter(Ge=>!!(Ge&&Ge.length>0)))).sort((Ge,Rt)=>Ge.localeCompare(Rt)),[me]),St=i.useMemo(()=>me.filter(Ge=>{const Rt=Ge.branch?.trim()??"",cn=Ge.baseBranch?.trim()??"";if(te===eg){if(Rt.length>0)return!1}else if(te.length>0&&Rt!==te)return!1;if(K===eg){if(cn.length>0)return!1}else if(K.length>0&&cn!==K)return!1;return!0}),[me,te,K]),[Ht,jt]=i.useState(!1),[ae,De]=i.useState(!1),[At,Lt]=i.useState(void 0),[Ft,Pe]=i.useState(void 0),[dt,bt]=i.useState(void 0),[_t,Yt]=i.useState(!1),[Xt,Te]=i.useState(!1),[Ye,Nt]=i.useState(()=>Dn(wd,y?.id)==="true");i.useEffect(()=>{Nt(Dn(wd,y?.id)==="true")},[y?.id]),i.useEffect(()=>{const Ge=()=>{Te(!0)};return window.addEventListener(Pd,Ge),()=>{window.removeEventListener(Pd,Ge)}},[]);const Ut=i.useCallback(()=>{os(wd,"true",y?.id),Nt(!0)},[y?.id]),{maxConcurrent:tn,autoMerge:Xn,globalPaused:fe,enginePaused:at,taskStuckTimeoutMs:ot,showQuickChatFAB:rt,prAuthAvailable:mt,settingsLoaded:vt,experimentalFeatures:ie,insightsEnabled:it,memoryEnabled:Gt,devServerEnabled:Cn,todosEnabled:fs,toggleAutoMerge:On,toggleGlobalPause:jn,toggleEnginePause:zn,refresh:hn}=MO(y?.id),Et=ie.skillsView===!0,En=ie.nodesView===!0,yn=ie.researchView===!0,ls=ie.evalsView===!0,cs=ie.agentOnboarding===!0,Hn=!0,qn=i.useCallback(()=>{H.closeSettings(),$t(Ge=>Ge+1),hn()},[H,hn]);i.useEffect(()=>{if(vt&&!rr(Ue)){if(Ue==="graph"&&!ze){pe("board");return}Ue==="skills"&&!Et&&pe("board"),Ue==="insights"&&!it&&pe("board"),Ue==="memory"&&!Gt&&pe("board"),(Ue==="devserver"||Ue==="dev-server")&&!Cn&&pe("board"),Ue==="research"&&!yn&&pe("board"),Ue==="evals"&&!ls&&pe("board")}},[Ue,vt,Et,it,pe,Hn,Gt,Cn,yn,ls,ze]),i.useEffect(()=>{Ht&&!En&&jt(!1)},[Ht,En]);const{availableModels:wn,favoriteProviders:Zn,favoriteModels:_n,toggleFavoriteProvider:ss,toggleFavoriteModel:Ns}=PO();RO({projectId:y?.id,setupWizardOpen:H.setupWizardOpen,openModelOnboarding:H.openModelOnboarding,openSettings:H.openSettings});const{handleSelectProject:es,handleViewAllProjects:ks,handleAddProject:Is,handleSetupComplete:Ss,handleModelOnboardingComplete:X,handlePauseProject:_,handleResumeProject:oe,handleRemoveProject:D,handleToggleFavorite:Q,handleToggleModelFavorite:Ce}=BO({setCurrentProject:S,clearCurrentProject:k,setViewMode:gt,currentProject:y,refreshProjects:h,toggleFavoriteProvider:ss,toggleFavoriteModel:Ns,addToast:n,openSettings:H.openSettings,openSetupWizard:H.openSetupWizard,closeSetupWizard:H.closeSetupWizard,closeModelOnboarding:H.closeModelOnboarding}),{handleDetailClose:Je}=AO({projectId:y?.id,projects:d,projectsLoading:u,currentProject:y,setCurrentProject:S,addToast:n,openTaskDetail:H.openDetailTask,closeTaskDetail:H.closeDetailTask}),kt=i.useCallback(async({insightId:Ge,title:Rt,description:cn})=>{await Y({title:Rt,description:cn,column:"triage",source:{sourceType:"dashboard_ui",sourceMetadata:{origin:"insights",insightId:Ge}}})},[Y]),{handleBoardQuickCreate:Tt,handleModalCreate:Pt,handlePlanningTaskCreated:ln,handlePlanningTasksCreated:ts,handleSubtaskTasksCreated:Pn,handleGitHubImport:Fn}=HO({createTask:Y,ingestCreatedTasks:he,onPlanningTaskCreated:H.onPlanningTaskCreated,onPlanningTasksCreated:H.onPlanningTasksCreated,onSubtaskTasksCreated:H.onSubtaskTasksCreated,addToast:n}),Un=i.useCallback((Ge,Rt)=>{Rt==="changes"?H.openDetailWithChangesTab(Ge):H.openDetailTask(Ge,Rt),Me({type:"modal",close:H.closeDetailTask})},[H,Me]),gs=i.useCallback(async Ge=>{try{const Rt=await Sa(Ge,y?.id);H.openDetailTask(Rt,"logs"),Me({type:"modal",close:H.closeDetailTask})}catch(Rt){n(`Failed to open task logs: ${Rt.message}`,"error")}},[H,y?.id,n,Me]),[Ln,Vn]=i.useState([]);i.useEffect(()=>{let Ge=!1;return _o(y?.id).then(Rt=>{Ge||Vn(Rt)}).catch(()=>{Ge||Vn([])}),()=>{Ge=!0}},[y?.id]);const Wn=i.useMemo(()=>new Map(Ln.map(Ge=>[Ge.id,Ge.name])),[Ln]);i.useCallback(()=>{En&&jt(Ge=>!Ge)},[En]);const Kn=i.useCallback(()=>{En&&(Ht?jt(!1):(jt(!0),Me({type:"view",revert:()=>jt(!1)})))},[En,Ht,Me]),Bn=i.useCallback((Ge,Rt,cn)=>{H.openDetailTask(Ge,Rt,cn),Me({type:"modal",close:H.closeDetailTask})},[H,Me]),Nn=i.useCallback(Ge=>{H.openSettings(Ge),Me({type:"modal",close:qn})},[H,Me,qn]),Gn=i.useCallback(()=>{H.openNewTask(),Me({type:"modal",close:H.closeNewTask})},[H,Me]),ds=i.useCallback(()=>{H.openPlanning(),Me({type:"modal",close:H.closePlanning})},[H,Me]),Ts=i.useCallback(Ge=>{H.openPlanningWithInitialPlan(Ge),Me({type:"modal",close:H.closePlanning})},[H,Me]),Ri=i.useCallback(()=>{H.resumePlanning(),Me({type:"modal",close:H.closePlanning})},[H,Me]),ca=i.useCallback(Ge=>{H.openSubtaskBreakdown(Ge),Me({type:"modal",close:H.closeSubtask})},[H,Me]),ri=i.useCallback(()=>{H.openGitHubImport(),Me({type:"modal",close:H.closeGitHubImport})},[H,Me]),Ta=i.useCallback(()=>{H.terminalOpen?H.toggleTerminal():(H.toggleTerminal(),Me({type:"modal",close:H.closeTerminal}))},[H,Me]),$a=i.useCallback(()=>{H.openFiles(),Me({type:"modal",close:H.closeFiles})},[H,Me]),Qs=i.useCallback(()=>{H.openTodos(),Me({type:"modal",close:H.closeTodos})},[H,Me]),oi=i.useCallback(()=>{H.openActivityLog(),Me({type:"modal",close:H.closeActivityLog})},[H,Me]),Ii=i.useCallback(()=>{H.openGitManager(),Me({type:"modal",close:H.closeGitManager})},[H,Me]),da=i.useCallback(()=>{H.openSystemStats(),Me({type:"modal",close:H.closeSystemStats})},[H,Me]),Da=i.useCallback(()=>{H.openSchedules(),Me({type:"modal",close:H.closeSchedules})},[H,Me]),La=i.useCallback(()=>{H.openScripts(),Me({type:"modal",close:H.closeScripts})},[H,Me]),ua=i.useCallback(()=>{H.openWorkflowSteps(),Me({type:"modal",close:H.closeWorkflowSteps})},[H,Me]),ma=i.useCallback(Ge=>{H.openUsage(Ge),Me({type:"modal",close:H.closeUsage})},[H,Me]),Ti=i.useCallback(async(Ge,Rt)=>{await H.runScript(Ge,Rt),Le({type:"modal",close:H.closeTerminal})},[H,Le]),Oa=i.useCallback(()=>{H.closeSettings(),H.openModelOnboarding(),Le({type:"modal",close:H.closeModelOnboarding})},[H,Le]),ha=i.useCallback(()=>{H.setFileWorkspace("project"),H.openFiles()},[H]),Mr=i.useCallback(async()=>{De(!0);try{await h()}finally{De(!1)}},[h]),li=i.useCallback(Ge=>{Pe(Ge),Lt(void 0),pe("missions")},[pe]),Hs=i.useCallback(Ge=>{Ge.type==="planning"?H.openPlanningWithSession(Ge.id):Ge.type==="subtask"?H.openSubtaskWithSession(Ge.id):Ge.type==="mission_interview"?(Pe(void 0),Lt(Ge.id),bt(void 0),pe("missions")):(Ge.type==="milestone_interview"||Ge.type==="slice_interview")&&(Lt(void 0),Pe(void 0),bt(Ge.id),pe("missions"))},[pe,H]),za=i.useCallback(()=>{},[]),Fa=i.useCallback(()=>{},[]),[$i,Ua]=i.useState(!1),[Ba,Ha]=i.useState(!1),[yi,pa]=i.useState(null),us=Tz(r,o,$i);i.useEffect(()=>{!a||l===0||Ha(!0)},[a,l]),i.useEffect(()=>{let Ge=!1;return gz(c.host).then(Rt=>{Ge||pa(Rt)}),()=>{Ge=!0}},[c.host,r.activeProfileId,r.desktopMode,r.host,r.profiles]),i.useEffect(()=>{r.host==="desktop-shell"&&r.desktopMode==="local"&&(r.localServer?.status!=="ready"||!r.localServer.port||window.location.port!==String(r.localServer.port)&&(window.location.href=`http://localhost:${r.localServer.port}`))},[r]),i.useEffect(()=>{if(r.host!=="desktop-shell"||r.desktopMode!=="remote")return;const Ge=r.profiles.find(cn=>cn.id===r.activeProfileId);if(!Ge||typeof window>"u")return;const Rt=Iz(Ge.serverUrl,Ge.authToken??null);window.location.href!==Rt&&(window.location.href=Rt)},[r]);const Ki=!u&&!C&&d.length===0&&!y&&!!m,Cs=()=>{if(Ki)return t.jsx(dL,{errorMessage:m??"Failed to fetch projects",isRetrying:ae,onRetry:Mr,onManageConnection:a?()=>{a.openConnectionManager()}:void 0});if(Ht)return t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Nz,{addToast:n,onClose:()=>jt(!1)})})})});if(He==="overview")return t.jsx(_s,{children:t.jsx(KI,{projects:d,loading:u,onSelectProject:es,onAddProject:Is,onPauseProject:_,onResumeProject:oe,onRemoveProject:D,nodes:f})});const Ge=Ue==="graph"?ze:rr(Ue)?Ue:null;return Ge?t.jsx(_s,{children:t.jsx(UO,{taskView:Ge,context:{projectId:y?.id,tasks:x&&N.tasks.length>0?N.tasks:ye,workflowSteps:Ln,openTaskDetail:(Rt,cn)=>Bn(Rt,cn),renderTaskCard:Rt=>t.jsx(ho,{task:Rt,projectId:y?.id,onOpenDetail:cn=>Bn(cn),addToast:n,workflowStepNameLookup:Wn,disableDrag:!0}),addToast:n}})}):Ue==="skills"?!vt||!Et?null:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Cz,{addToast:n,projectId:y?.id,onClose:()=>pe("board")})})}):Ue==="chat"?t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Sz,{addToast:n,projectId:y?.id})})}):Ue==="mailbox"?t.jsx(_s,{children:t.jsx(OT,{projectId:y?.id,addToast:n,onUnreadCountChange:fn})}):Ue==="missions"?t.jsx(_s,{children:t.jsx(IT,{isInline:!0,isOpen:!0,onClose:()=>{Pe(void 0),Lt(void 0),bt(void 0),pe("board")},addToast:n,projectId:y?.id,onSelectTask:Rt=>{const cn=ye.find(is=>is.id===Rt);cn&&Bn(cn)},availableTasks:ye.map(Rt=>({id:Rt.id,title:Rt.title})),resumeSessionId:At,targetMissionId:Ft,milestoneSliceResumeSessionId:dt,onMilestoneSliceResumeFetchError:()=>bt(void 0)})}):Ue==="agents"&&Hn?t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(vz,{addToast:n,projectId:y?.id,onOpenTaskLogs:gs,agentOnboardingEnabled:cs})})}):Ue==="documents"?t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(yz,{projectId:y?.id,addToast:n,onOpenDetail:Bn})})}):Ue==="insights"?!vt||!it?null:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(wz,{projectId:y?.id,addToast:n,onClose:()=>pe("board"),onCreateTask:kt})})}):Ue==="research"?!vt||!yn?null:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(kz,{projectId:y?.id,addToast:n,onOpenSettings:Rt=>H.openSettings(Rt),readinessVersion:wt})})}):Ue==="evals"?!vt||!ls?null:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(jz,{projectId:y?.id,onOpenSettings:Rt=>H.openSettings(Rt),onOpenTaskDetail:Rt=>{Sa(Rt,y?.id).then(cn=>Bn(cn)).catch(cn=>n(cn instanceof Error?cn.message:"Failed to open task detail","error"))}})})}):Ue==="memory"?!vt||!Gt?null:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Ez,{addToast:n,projectId:y?.id})})}):Ue==="devserver"||Ue==="dev-server"?!vt||!Cn?null:t.jsx(_s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(_z,{addToast:n,projectId:y?.id})})}):Ue==="board"?t.jsx(_s,{children:t.jsx(qC,{tasks:St,projectId:y?.id,maxConcurrent:tn,onMoveTask:_e,onPauseTask:ct,onOpenDetail:Bn,addToast:n,onQuickCreate:Tt,onNewTask:Gn,onPlanningMode:Ts,onSubtaskBreakdown:ca,autoMerge:Xn,onToggleAutoMerge:On,globalPaused:fe,onUpdateTask:$e,onRetryTask:Ve,onArchiveTask:ht,onUnarchiveTask:Se,onDeleteTask:pt,onArchiveAllDone:we,onLoadArchivedTasks:Ae,searchQuery:O,availableModels:wn,onOpenDetailWithTab:Un,favoriteProviders:Zn,favoriteModels:_n,onToggleFavorite:Q,onToggleModelFavorite:Ce,taskStuckTimeoutMs:ot,onOpenMission:li,lastFetchTimeMs:We})}):t.jsx(_s,{children:t.jsx($I,{tasks:x&&N.tasks.length>0?N.tasks:ye,projectId:y?.id,onMoveTask:_e,onRetryTask:Ve,onDeleteTask:pt,onMergeTask:de,onResetTask:Ee,onDuplicateTask:ut,onOpenDetail:(Rt,cn)=>Bn(Rt,void 0,cn),addToast:n,globalPaused:fe,onNewTask:Gn,onQuickCreate:Tt,onPlanningMode:Ts,onSubtaskBreakdown:ca,availableModels:wn,favoriteProviders:Zn,favoriteModels:_n,onToggleFavorite:Q,onToggleModelFavorite:Ce,taskStuckTimeoutMs:ot,searchQuery:O,lastFetchTimeMs:We,prAuthAvailable:mt})})};if(!nt)return t.jsxs(t.Fragment,{children:[t.jsx(mL,{stage:Qt}),t.jsx(Jx,{toasts:e,onRemove:s})]});const Gi=!H.modelOnboardingOpen&&TD(),qa=!H.modelOnboardingOpen&&!Gi&&wr()&&!Vx();return t.jsxs(t.Fragment,{children:[t.jsx(S0,{shellHost:c.host,onOpenSettings:Nn,onOpenGitHubImport:ri,onOpenPlanning:ds,onResumePlanning:Ri,activePlanningSessionCount:J.length,onOpenUsage:ma,onOpenActivityLog:oi,onOpenSystemStats:da,onOpenMailbox:()=>lt("mailbox"),mailboxUnreadCount:on,mailboxPendingApprovalCount:Jt,chatHasUnreadResponse:zt,onOpenSchedules:Da,onOpenGitManager:Ii,onOpenNodes:Kn,showNodesButton:En,onOpenWorkflowSteps:ua,onOpenScripts:La,onRunScript:Ti,onToggleTerminal:Ta,onOpenFiles:$a,filesOpen:H.filesOpen,onOpenTodos:Qs,todosOpen:H.todosOpen,todosEnabled:fs,globalPaused:fe,enginePaused:at,onToggleGlobalPause:jn,onToggleEnginePause:zn,view:Ue,onChangeView:He==="project"&&y?lt:void 0,showSkillsTab:Et,showAgentsTab:Hn,searchQuery:O,onSearchChange:q,branchFilter:te,baseBranchFilter:K,branchOptions:Qe,baseBranchOptions:It,onBranchFilterChange:I,onBaseBranchFilterChange:$,projects:G,currentProject:y,onSelectProject:es,onViewAllProjects:ks,projectId:y?.id,mobileNavEnabled:ce,availableNodes:f,currentNode:p,onSelectNode:Ge=>{Ge===null?b():w(Ge)},isRemote:x,experimentalFeatures:{insights:it,memoryView:Gt,devServer:Cn,devServerView:Cn,researchView:yn,evalsView:ls},pluginDashboardViews:Oe,shellConnectionControl:!ce&&yi?t.jsx(Qf,{status:yi,onError:Ge=>n(Ge,"error")}):void 0}),He==="project"&&y&&!Ht&&Ue!=="missions"&&!H.isPlanningOpen&&!Ne&&t.jsx(EL,{sessions:ve,onResumeSession:Hs,onDismissSession:za,onDismissAll:Fa}),He==="project"&&y&&t.jsx(AL,{onOpenSettings:()=>H.openSettings("general")}),He==="project"&&y&&Gi&&t.jsx(IL,{onResume:H.openModelOnboarding}),He==="project"&&y&&qa&&t.jsx(TL,{onOpenModelOnboarding:H.openModelOnboarding,onOpenSettings:Ge=>H.openSettings(Ge)}),He==="project"&&y&&E&&R&&L&&!F&&t.jsx(PL,{latestVersion:R,currentVersion:L,onDismiss:M}),He==="project"&&y&&!P&&U&&!Ye&&t.jsx(Ux,{hasAiProvider:v,hasGithub:j,onDismiss:Ut}),He==="project"&&y&&Zt&&t.jsx(RL,{pendingCount:Math.max(Jt,1),onOpenMailbox:()=>lt("mailbox"),onDismiss:()=>{Ke.current.set(Zt.dedupeKey,Math.max(Date.now(),Zt.updatedAtMs)),ng(Ke.current),dn(null)}}),t.jsx("div",{className:`project-content${He==="project"&&y?" project-content--with-footer":""}${ce&&!Bt?" project-content--with-mobile-nav":""}`,children:Cs()}),He==="project"&&y&&!Ht&&t.jsx(kL,{tasks:x&&N.tasks.length>0?N.tasks:ye,projectId:y.id,taskStuckTimeoutMs:ot,backgroundSessions:le,backgroundGenerating:se,backgroundNeedsInput:re,onOpenBackgroundSession:Hs,onDismissBackgroundSession:B,lastFetchTimeMs:We,currentProjectPath:y.path,onOpenProjectDirectory:ha,keyboardOpen:Bt}),t.jsx(DL,{view:Ue,onChangeView:He==="project"&&y?lt:()=>{},footerVisible:He==="project"&&!!y,modalOpen:H.anyModalOpen,keyboardOpen:Bt,onOpenSettings:Nn,onOpenActivityLog:oi,onOpenSystemStats:da,onOpenMailbox:()=>lt("mailbox"),onOpenNodes:Kn,mailboxUnreadCount:on,mailboxPendingApprovalCount:Jt,chatHasUnreadResponse:zt,onOpenGitManager:Ii,onOpenWorkflowSteps:ua,onOpenSchedules:Da,onOpenScripts:La,onToggleTerminal:Ta,onOpenFiles:$a,onOpenTodos:Qs,todosOpen:H.todosOpen,onOpenGitHubImport:ri,onOpenPlanning:ds,onResumePlanning:Ri,activePlanningSessionCount:J.length,onOpenUsage:()=>ma(null),onViewAllProjects:ks,onRunScript:Ti,projectId:y?.id,showSkillsTab:Et,experimentalFeatures:{insights:it,memoryView:Gt,devServer:Cn,devServerView:Cn,todoView:fs,researchView:yn,evalsView:ls,nodesView:En},pluginDashboardViews:Oe,shellConnectionControl:ce&&yi?t.jsx(Qf,{status:yi,onError:Ge=>n(Ge,"error")}):void 0}),He==="project"&&y&&Ue!=="chat"&&Ue!=="mailbox"&&Ue!=="insights"&&Ue!=="evals"&&Ue!=="devserver"&&Ue!=="dev-server"&&Ue!=="graph"&&!rr(Ue)&&t.jsx(aO,{projectId:y.id,addToast:n,showFAB:rt,open:_t,onOpenChange:Yt,favoriteProviders:Zn,favoriteModels:_n,onToggleFavorite:Q,onToggleModelFavorite:Ce}),t.jsx(cL,{projectId:y?.id,tasks:ye,projects:d,currentProject:y,addToast:n,toasts:e,removeToast:s,modalManager:H,projectActions:{handleAddProject:Is,handleSetupComplete:Ss,handleModelOnboardingComplete:X},taskHandlers:{handleModalCreate:Pt,handlePlanningTaskCreated:ln,handlePlanningTasksCreated:ts,handleSubtaskTasksCreated:Pn,handleGitHubImport:Fn},taskOperations:{moveTask:_e,deleteTask:pt,mergeTask:de,retryTask:Ve,resetTask:Ee,duplicateTask:ut},deepLink:{handleDetailClose:Je},settings:{prAuthAvailable:mt,themeMode:ge,colorTheme:je,dashboardFontScalePct:ke,setThemeMode:ne,setColorTheme:qe,setDashboardFontScalePct:ee},onSettingsClose:qn,onReopenOnboarding:Oa}),t.jsx(bz,{open:Xt}),a&&t.jsxs(t.Fragment,{children:[t.jsx(dz,{open:us,shellApi:a,shellState:r,onComplete:()=>Ua(!0)}),t.jsx(uz,{open:Ba,shellApi:a,shellState:r,onClose:()=>Ha(!1)})]})]})}function Dz(){return t.jsx(vO,{children:t.jsx(oz,{children:t.jsx(kD,{children:t.jsx(KO,{children:t.jsx(z0,{children:t.jsx($z,{})})})})})})}function fv(e){e.postMessage({type:"SKIP_WAITING"})}function sg(e){e.addEventListener("statechange",()=>{e.state==="installed"&&navigator.serviceWorker.controller&&fv(e)})}function Lz(){if(!("serviceWorker"in navigator))return;const e=!!navigator.serviceWorker.controller;let n=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{n||!e||(n=!0,du("service worker activated new version"))}),navigator.serviceWorker.register("/sw.js").then(s=>{console.log("SW registered:",s.scope),s.waiting&&navigator.serviceWorker.controller&&fv(s.waiting),s.installing&&sg(s.installing),s.addEventListener("updatefound",()=>{const a=s.installing;a&&sg(a)})}).catch(s=>{console.log("SW registration failed:",s)})}Ik();xk();mv();lv();bv.createRoot(document.getElementById("root")).render(t.jsx(i.StrictMode,{children:t.jsx(vk,{children:t.jsx(Dz,{})})}));Lz();export{eS as $,Ks as A,Tn as B,$n as C,D0 as D,p3 as E,ia as F,Wl as G,Ed as H,bn as I,jl as J,G6 as K,xt as L,jo as M,kw as N,cD as O,Sn as P,fd as Q,rs as R,Fi as S,No as T,Yn as U,pi as V,vn as W,nn as X,aD as Y,Qn as Z,gn as _,rn as a,tc as a$,X$ as a0,Z$ as a1,tS as a2,u3 as a3,nS as a4,NF as a5,SF as a6,rN as a7,ou as a8,kr as a9,R6 as aA,A6 as aB,yg as aC,$k as aD,uo as aE,C6 as aF,_6 as aG,E6 as aH,z6 as aI,L6 as aJ,O6 as aK,F6 as aL,K6 as aM,co as aN,kd as aO,Ww as aP,Si as aQ,Lw as aR,ry as aS,HI as aT,Ds as aU,bg as aV,$w as aW,S3 as aX,C3 as aY,E3 as aZ,_3 as a_,Aa as aa,bi as ab,xi as ac,Ei as ad,v6 as ae,N6 as af,j6 as ag,y6 as ah,S6 as ai,w6 as aj,k6 as ak,ps as al,xo as am,to as an,Ps as ao,sk as ap,_i as aq,dg as ar,Hi as as,Cv as at,M6 as au,P6 as av,D6 as aw,$6 as ax,T6 as ay,I6 as az,Mn as b,_N as b$,fO as b0,Nm as b1,Pr as b2,Pf as b3,B1 as b4,pr as b5,O1 as b6,u6 as b7,m6 as b8,F1 as b9,iF as bA,sF as bB,nF as bC,aF as bD,pF as bE,fF as bF,uF as bG,lF as bH,cF as bI,dF as bJ,oF as bK,rF as bL,tF as bM,mF as bN,z4 as bO,VF as bP,qF as bQ,QF as bR,HF as bS,WF as bT,KF as bU,GF as bV,JF as bW,AN as bX,YF as bY,mu as bZ,EN as b_,FL as ba,U1 as bb,zL as bc,g6 as bd,b6 as be,h6 as bf,p6 as bg,f6 as bh,x6 as bi,KL as bj,Wi as bk,Xx as bl,D1 as bm,hs as bn,sa as bo,ql as bp,wa as bq,fg as br,LL as bs,VL as bt,mg as bu,Qu as bv,Ui as bw,c6 as bx,l6 as by,d6 as bz,tt as c,Cj as c$,MN as c0,CN as c1,BF as c2,Ql as c3,qw as c4,dr as c5,I3 as c6,T3 as c7,$3 as c8,D3 as c9,RF as cA,Tv as cB,xj as cC,LF as cD,vj as cE,OF as cF,ti as cG,Ai as cH,cO as cI,S4 as cJ,gF as cK,A3 as cL,Bz as cM,Hz as cN,jf as cO,w3 as cP,qz as cQ,Wz as cR,eF as cS,Zz as cT,Rj as cU,wj as cV,Mi as cW,kj as cX,Nj as cY,jj as cZ,Sj as c_,L3 as ca,O3 as cb,z3 as cc,R3 as cd,wg as ce,Zy as cf,Rl as cg,ho as ch,ur as ci,fS as cj,Sk as ck,Ck as cl,cj as cm,dj as cn,e6 as co,EF as cp,CF as cq,t6 as cr,_F as cs,DF as ct,IF as cu,MF as cv,TF as cw,AF as cx,$F as cy,PF as cz,y3 as d,Ka as d$,vF as d0,k3 as d1,j3 as d2,N3 as d3,qi as d4,B6 as d5,H6 as d6,P3 as d7,Kz as d8,jd as d9,V3 as dA,H3 as dB,U3 as dC,q3 as dD,W3 as dE,Id as dF,sm as dG,l3 as dH,d3 as dI,R1 as dJ,Na as dK,Us as dL,By as dM,K3 as dN,h3 as dO,wo as dP,MR as dQ,ya as dR,c3 as dS,g3 as dT,f3 as dU,ug as dV,r3 as dW,a3 as dX,ZF as dY,e3 as dZ,Q$ as d_,bs as da,L4 as db,uD as dc,hD as dd,pD as de,ta as df,gd as dg,gD as dh,Jz as di,Vz as dj,Yz as dk,Gz as dl,Qz as dm,Xz as dn,Ca as dp,J6 as dq,R0 as dr,ec as ds,q6 as dt,up as du,V6 as dv,W6 as dw,hF as dx,F3 as dy,B3 as dz,x3 as e,m3 as e0,s3 as e1,n3 as e2,oN as e3,i3 as e4,o3 as e5,G3 as e6,_1 as e7,t3 as e8,XF as e9,si as ea,UF as eb,zF as ec,FF as ed,J3 as ee,n6 as ef,_d as eg,a6 as eh,r6 as ei,i6 as ej,X3 as ek,Q3 as el,Z3 as em,Y3 as en,s6 as eo,M3 as ep,U6 as eq,yF as er,bF as es,xF as et,Aw as eu,kF as ev,jF as ew,wF as ex,Sa as f,v3 as g,Os as h,Nr as i,kn as j,Zd as k,o6 as l,ys as m,ZN as n,b3 as o,Ys as p,qL as q,eD as r,ii as s,Dn as t,vi as u,ai as v,os as w,Xl as x,Do as y,Re as z};
|