@runfusion/fusion 0.27.1 → 0.28.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 +3418 -864
- package/dist/client/assets/AgentDetailView-DSpIqBOs.css +1 -0
- package/dist/client/assets/{AgentDetailView-shgiiUb4.js → AgentDetailView-V32TpEe1.js} +3 -3
- package/dist/client/assets/{AgentsView-CpwqOVDz.js → AgentsView-CxITZE-U.js} +3 -3
- package/dist/client/assets/ChatView-7WPHyB_7.js +1 -0
- package/dist/client/assets/DevServerView-Diw4hjw0.js +1 -0
- package/dist/client/assets/{DirectoryPicker-C0kmRv0u.js → DirectoryPicker-CWSApoLU.js} +1 -1
- package/dist/client/assets/{DocumentsView-B94U9ijs.js → DocumentsView-1kr0dhsV.js} +1 -1
- package/dist/client/assets/{EvalsView-O_4YWy--.js → EvalsView-cDfXYiK6.js} +1 -1
- package/dist/client/assets/{ExperimentalAgentOnboardingModal-CkEiF85-.js → ExperimentalAgentOnboardingModal-lNSf6UtY.js} +1 -1
- package/dist/client/assets/{InsightsView-D-Qe0tRr.js → InsightsView-D2AjxOnu.js} +1 -1
- package/dist/client/assets/{MemoryView-CoRUmRvb.js → MemoryView-Dq4yjIPI.js} +1 -1
- package/dist/client/assets/{NodesView-DQzXjcLc.js → NodesView-Cpmkze7n.js} +4 -4
- package/dist/client/assets/{PiExtensionsManager-Dn1LmFbq.js → PiExtensionsManager-oi9FHT0y.js} +2 -2
- package/dist/client/assets/PluginManager-C4UoLv4U.css +1 -0
- package/dist/client/assets/PluginManager-o12KG4e8.js +1 -0
- package/dist/client/assets/ResearchView-C7uXon3o.css +1 -0
- package/dist/client/assets/ResearchView-C9bjVB7-.js +1 -0
- package/dist/client/assets/{SettingsModal-Bg1-3JO_.js → SettingsModal-CT01a5Rh.js} +1 -1
- package/dist/client/assets/SettingsModal-Cu93Jjho.js +31 -0
- package/dist/client/assets/{SetupWizardModal-DuzYPbuJ.js → SetupWizardModal-Agi3XNtZ.js} +1 -1
- package/dist/client/assets/{SkillsView-BIFoVNUf.js → SkillsView-DmZfbGLs.js} +1 -1
- package/dist/client/assets/{StashRecoveryView-C52KsV7f.js → StashRecoveryView-BwKJQaUW.js} +1 -1
- package/dist/client/assets/{TodoView-sS_mT0Y7.js → TodoView-uJRg4Cnl.js} +2 -2
- package/dist/client/assets/dashboard-view-C7Snlgow.js +21 -0
- package/dist/client/assets/dashboard-view-DqWnXEbq.css +1 -0
- package/dist/client/assets/{folder-open-B9cwJ-OX.js → folder-open-DU-Ec_iC.js} +1 -1
- package/dist/client/assets/index-CD0_dkME.css +1 -0
- package/dist/client/assets/index-DiewofJh.js +692 -0
- package/dist/client/assets/{star-BDn04UYV.js → star-Qi0GspVN.js} +1 -1
- package/dist/client/assets/{upload-zdPPycKQ.js → upload-Dx_l9Vbu.js} +1 -1
- package/dist/client/assets/{users-CPYZjK2g.js → users-3Qw_TMah.js} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/client/version.json +1 -1
- package/dist/droid-cli/package.json +1 -1
- package/dist/extension.js +2628 -573
- package/dist/pi-claude-cli/package.json +1 -1
- package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
- package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/registration.test.ts +2 -4
- package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/runtime-availability.test.ts +5 -2
- package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/workflow-integration.test.ts +7 -4
- package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
- package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
- 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/package.json +1 -1
- package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
- package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
- package/package.json +1 -1
- package/skill/fusion/references/engine-tools.md +1 -0
- package/skill/fusion/references/extension-tools.md +3 -1
- package/dist/client/assets/AgentDetailView-B7QRcHJH.css +0 -1
- package/dist/client/assets/ChatView-DyRBOIKL.js +0 -1
- package/dist/client/assets/DevServerView-Cdelj9-m.js +0 -1
- package/dist/client/assets/PluginManager-DtRQXia5.css +0 -1
- package/dist/client/assets/PluginManager-Y0fs-6No.js +0 -1
- package/dist/client/assets/ResearchView-BEI4ZSGs.css +0 -1
- package/dist/client/assets/ResearchView-CjOxKhdS.js +0 -1
- package/dist/client/assets/SettingsModal-DL7tjJQa.js +0 -31
- package/dist/client/assets/dashboard-view-BoTzlP8b.css +0 -1
- package/dist/client/assets/dashboard-view-MB-86hAu.js +0 -21
- package/dist/client/assets/index-BOjPRqEk.js +0 -692
- package/dist/client/assets/index-BmSEq8Rb.css +0 -1
|
@@ -0,0 +1,692 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentDetailView-V32TpEe1.js","assets/vendor-react-K0fH_qHe.js","assets/star-Qi0GspVN.js","assets/ExperimentalAgentOnboardingModal-lNSf6UtY.js","assets/ExperimentalAgentOnboardingModal-B-APN_lM.css","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/AgentDetailView-DSpIqBOs.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/TodoView-uJRg4Cnl.js","assets/TodoView-Cx9cVhq7.css","assets/SetupWizardModal-Agi3XNtZ.js","assets/DirectoryPicker-CWSApoLU.js","assets/folder-open-DU-Ec_iC.js","assets/DirectoryPicker-DzKVmxOf.css","assets/projectDetection-G3XuxD2X.js","assets/SetupWizardModal-CGYGKurR.css","assets/SettingsModal-Cu93Jjho.js","assets/SettingsModal-CT01a5Rh.js","assets/SettingsModal-Ci0_sqbU.css","assets/users-3Qw_TMah.js","assets/SettingsModal-DWKgRxBA.css","assets/dashboard-view-C7Snlgow.js","assets/createLucideIcon-BazL2hk5.js","assets/dashboard-view-DqWnXEbq.css","assets/dashboard-view-BWGH_fAq.js","assets/dashboard-view-DdGlfuu-.css","assets/AgentsView-CxITZE-U.js","assets/upload-Dx_l9Vbu.js","assets/AgentsView-B3ADnF0D.css","assets/DocumentsView-1kr0dhsV.js","assets/DocumentsView-gv4zG3aT.css","assets/InsightsView-D2AjxOnu.js","assets/InsightsView-B0J4mhzV.css","assets/ResearchView-C9bjVB7-.js","assets/ResearchView-C7uXon3o.css","assets/EvalsView-cDfXYiK6.js","assets/EvalsView-CUNJ1TLc.css","assets/NodesView-Cpmkze7n.js","assets/NodesView-DT4pXowv.css","assets/ChatView-7WPHyB_7.js","assets/ChatView-DwJAd5G1.css","assets/SkillsView-DmZfbGLs.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-Dq4yjIPI.js","assets/MemoryView-zaXewZzi.css","assets/DevServerView-Diw4hjw0.js","assets/DevServerView-DlZpuAnj.css","assets/StashRecoveryView-BwKJQaUW.js","assets/StashRecoveryView-B_8WIQEo.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as i,j as t,R as ga,a as $a,g as Kg,c as vy}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 Jg=(...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 yy=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 wy=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 Rm=e=>{const n=wy(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 Fc={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 ky=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},jy=i.createContext({}),Ny=()=>i.useContext(jy),Sy=i.forwardRef(({color:e,size:n,strokeWidth:s,absoluteStrokeWidth:a,className:r="",children:o,iconNode:l,...c},d)=>{const{size:u=24,strokeWidth:m=2,absoluteStrokeWidth:h=!1,color:f="currentColor",className:p=""}=Ny()??{},g=a??h?Number(s??m)*24/Number(n??u):s??m;return i.createElement("svg",{ref:d,...Fc,width:n??u??Fc.width,height:n??u??Fc.height,stroke:e??f,strokeWidth:g,className:Jg("lucide",p,r),...!o&&!ky(c)&&{"aria-hidden":"true"},...c},[...l.map(([w,v])=>i.createElement(w,v)),...Array.isArray(o)?o:[o]])});/**
|
|
33
|
+
* @license lucide-react v1.7.0 - ISC
|
|
34
|
+
*
|
|
35
|
+
* This source code is licensed under the ISC license.
|
|
36
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
37
|
+
*/const it=(e,n)=>{const s=i.forwardRef(({className:a,...r},o)=>i.createElement(Sy,{ref:o,iconNode:n,className:Jg(`lucide-${yy(Rm(e))}`,`lucide-${e}`,a),...r}));return s.displayName=Rm(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 Cy=[["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"}]],Js=it("activity",Cy);/**
|
|
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 Ey=[["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"}]],_y=it("archive-restore",Ey);/**
|
|
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 My=[["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"}]],zo=it("archive",My);/**
|
|
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 Ay=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Bo=it("arrow-down",Ay);/**
|
|
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 Ry=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],Ga=it("arrow-left",Ry);/**
|
|
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 Iy=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],Uo=it("arrow-right",Iy);/**
|
|
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 Ty=[["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"}]],Yg=it("arrow-up-down",Ty);/**
|
|
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 Py=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],La=it("arrow-up",Py);/**
|
|
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 $y=[["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"}]],Dy=it("book-open",$y);/**
|
|
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 Ly=[["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"}]],Qn=it("bot",Ly);/**
|
|
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 Oy=[["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"}]],eu=it("box",Oy);/**
|
|
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 Fy=[["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"}]],Io=it("brain",Fy);/**
|
|
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 zy=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],Qg=it("calendar",zy);/**
|
|
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 By=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],Im=it("check-check",By);/**
|
|
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 Uy=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],ks=it("check",Uy);/**
|
|
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 Hy=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],gn=it("chevron-down",Hy);/**
|
|
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 qy=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],pc=it("chevron-left",qy);/**
|
|
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 Vy=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],qn=it("chevron-right",Vy);/**
|
|
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 Wy=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],Li=it("chevron-up",Wy);/**
|
|
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 Gy=[["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"}]],Vs=it("circle-alert",Gy);/**
|
|
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 Ky=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],Xn=it("circle-check-big",Ky);/**
|
|
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 Jy=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],fc=it("circle-dot",Jy);/**
|
|
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 Yy=[["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"}]],tu=it("circle-question-mark",Yy);/**
|
|
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 Qy=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],Xy=it("circle-stop",Qy);/**
|
|
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 Zy=[["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"}]],Ho=it("circle-x",Zy);/**
|
|
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 ew=[["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"}]],tw=it("clipboard-list",ew);/**
|
|
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 nw=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],ta=it("clock",nw);/**
|
|
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 sw=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Xg=it("code",sw);/**
|
|
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 iw=[["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"}]],Tm=it("columns-3",iw);/**
|
|
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 aw=[["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"}]],ba=it("copy",aw);/**
|
|
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 rw=[["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"}]],Zg=it("cpu",rw);/**
|
|
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 ow=[["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"}]],lw=it("download",ow);/**
|
|
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 cw=[["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"}]],dw=it("ellipsis-vertical",cw);/**
|
|
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 uw=[["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"}]],nu=it("ellipsis",uw);/**
|
|
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 mw=[["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"}]],eb=it("external-link",mw);/**
|
|
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 hw=[["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"}]],zu=it("eye-off",hw);/**
|
|
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 pw=[["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"}]],Fr=it("eye",pw);/**
|
|
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 fw=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]],Si=it("file-code",fw);/**
|
|
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 gw=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M9 10h6",key:"9gxzsh"}],["path",{d:"M12 13V7",key:"h0r20n"}],["path",{d:"M9 17h6",key:"r8uit2"}]],su=it("file-diff",gw);/**
|
|
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 bw=[["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"}]],xw=it("file-minus",bw);/**
|
|
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 vw=[["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"}]],tb=it("file-pen",vw);/**
|
|
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 yw=[["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"}]],ww=it("file-plus",yw);/**
|
|
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 kw=[["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"}]],jw=it("file-question-mark",kw);/**
|
|
253
|
+
* @license lucide-react v1.7.0 - ISC
|
|
254
|
+
*
|
|
255
|
+
* This source code is licensed under the ISC license.
|
|
256
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
257
|
+
*/const Nw=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],xa=it("file-text",Nw);/**
|
|
258
|
+
* @license lucide-react v1.7.0 - ISC
|
|
259
|
+
*
|
|
260
|
+
* This source code is licensed under the ISC license.
|
|
261
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
262
|
+
*/const Sw=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M11 18h2",key:"12mj7e"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"M9 13v-.5a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 .5.5v.5",key:"qbrxap"}]],Cw=it("file-type",Sw);/**
|
|
263
|
+
* @license lucide-react v1.7.0 - ISC
|
|
264
|
+
*
|
|
265
|
+
* This source code is licensed under the ISC license.
|
|
266
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
267
|
+
*/const Ew=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]],nb=it("file",Ew);/**
|
|
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 _w=[["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"}]],Mw=it("flag",_w);/**
|
|
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 Aw=[["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"}]],iu=it("folder-git-2",Aw);/**
|
|
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 Rw=[["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"}]],Pm=it("folder-root",Rw);/**
|
|
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 Iw=[["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"}]],js=it("folder",Iw);/**
|
|
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 Tw=[["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"}]],ql=it("funnel",Tw);/**
|
|
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 Pw=[["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"}]],Os=it("git-branch",Pw);/**
|
|
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 $w=[["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"}]],Nr=it("git-commit-horizontal",$w);/**
|
|
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 Dw=[["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"}]],sb=it("git-merge",Dw);/**
|
|
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 Lw=[["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"}]],ii=it("git-pull-request",Lw);/**
|
|
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 Ow=[["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"}]],gc=it("globe",Ow);/**
|
|
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 Fw=[["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"}]],bc=it("grid-3x3",Fw);/**
|
|
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 zw=[["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"}]],xc=it("grip-vertical",zw);/**
|
|
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 Bw=[["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"}]],Uw=it("hard-drive",Bw);/**
|
|
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 Hw=[["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"}]],qw=it("heart",Hw);/**
|
|
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 Vw=[["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"}]],Oa=it("history",Vw);/**
|
|
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 Ww=[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]],ma=it("inbox",Ww);/**
|
|
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 Gw=[["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"}]],ib=it("key",Gw);/**
|
|
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 Kw=[["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"}]],Jw=it("keyboard",Kw);/**
|
|
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 Yw=[["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"}]],Fa=it("layers",Yw);/**
|
|
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 Qw=[["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"}]],va=it("layout-grid",Qw);/**
|
|
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 Xw=[["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"}]],Oi=it("lightbulb",Xw);/**
|
|
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 Zw=[["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"}]],Sr=it("link",Zw);/**
|
|
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 ek=[["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"}]],tk=it("list-checks",ek);/**
|
|
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 nk=[["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"}]],$m=it("list-ordered",nk);/**
|
|
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 sk=[["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"}]],ik=it("list-plus",sk);/**
|
|
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 ak=[["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"}]],vc=it("list-tree",ak);/**
|
|
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 rk=[["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"}]],au=it("list",rk);/**
|
|
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 ok=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],jt=it("loader-circle",ok);/**
|
|
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 lk=[["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"}]],yc=it("lock",lk);/**
|
|
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 ck=[["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"}]],za=it("mail",ck);/**
|
|
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 dk=[["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"}]],uk=it("map",dk);/**
|
|
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 mk=[["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"}]],wc=it("maximize-2",mk);/**
|
|
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 hk=[["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"}]],pk=it("message-square-plus",hk);/**
|
|
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 fk=[["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"}]],Zi=it("message-square",fk);/**
|
|
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 gk=[["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"}]],qo=it("minimize-2",gk);/**
|
|
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 bk=[["path",{d:"M5 12h14",key:"1ays0h"}]],xk=it("minus",bk);/**
|
|
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 vk=[["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"}]],Cr=it("monitor",vk);/**
|
|
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 yk=[["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"}]],wk=it("move",yk);/**
|
|
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 kk=[["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"}]],jk=it("network",kk);/**
|
|
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 Nk=[["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"}]],ru=it("package",Nk);/**
|
|
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 Sk=[["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"}]],ab=it("paperclip",Sk);/**
|
|
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 Ck=[["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"}]],Ci=it("pause",Ck);/**
|
|
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 Ek=[["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"}]],Hs=it("pencil",Ek);/**
|
|
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 _k=[["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"}]],os=it("play",_k);/**
|
|
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 Mk=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],$n=it("plus",Mk);/**
|
|
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 Ak=[["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"}]],Rk=it("puzzle",Ak);/**
|
|
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 Ik=[["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"}]],rb=it("radio",Ik);/**
|
|
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 Tk=[["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"}]],ps=it("refresh-cw",Tk);/**
|
|
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 Pk=[["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"}]],Dm=it("rocket",Pk);/**
|
|
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 $k=[["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"}]],Dk=it("rotate-ccw",$k);/**
|
|
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 Lk=[["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"}]],Ok=it("rotate-cw",Lk);/**
|
|
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 Fk=[["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"}]],ob=it("save",Fk);/**
|
|
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 zk=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Xi=it("search",zk);/**
|
|
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 Bk=[["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"}]],Da=it("send",Bk);/**
|
|
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 Uk=[["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"}]],To=it("server",Uk);/**
|
|
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 Hk=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Co=it("settings",Hk);/**
|
|
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 qk=[["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"}]],Vk=it("shield-alert",qk);/**
|
|
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 Wk=[["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"}]],Gk=it("shield",Wk);/**
|
|
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 Kk=[["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"}]],Jk=it("skull",Kk);/**
|
|
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 Yk=[["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"}]],ms=it("sparkles",Yk);/**
|
|
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 Qk=[["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"}]],Bu=it("square-check-big",Qk);/**
|
|
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 Xk=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],$i=it("square",Xk);/**
|
|
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 Zk=[["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"}]],Es=it("target",Zk);/**
|
|
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 ej=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],ea=it("terminal",ej);/**
|
|
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 tj=[["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"}]],Vl=it("text-wrap",tj);/**
|
|
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 nj=[["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"}]],Tn=it("trash-2",nj);/**
|
|
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 sj=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],ij=it("trending-up",sj);/**
|
|
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 aj=[["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"}]],zr=it("triangle-alert",aj);/**
|
|
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 rj=[["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"}]],Lm=it("unlink",rj);/**
|
|
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 oj=[["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"}]],Ra=it("user",oj);/**
|
|
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 lj=[["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"}]],lb=it("webhook",lj);/**
|
|
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 cj=[["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"}]],Wl=it("workflow",cj);/**
|
|
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 dj=[["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"}]],Om=it("wrench",dj);/**
|
|
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 uj=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],mn=it("x",uj);/**
|
|
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 mj=[["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"}]],ls=it("zap",mj),ou="fusion:version-reload",lu="fusion:version-update";let Uu=!0;function zc(e){Uu=e}function hj(){try{if(sessionStorage.getItem(lu))return sessionStorage.removeItem(lu),!0}catch{}return!1}function Hu(e){if(sessionStorage.getItem(ou)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}if(sessionStorage.setItem(ou,"1"),!Uu){console.info("[versionCheck] auto-reload disabled by setting, skipping reload:",e);return}console.info("[versionCheck] reloading:",e),window.location.reload()}function pj(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 fj(e){return pj(e)?(Hu(`chunk load error: ${e?.message??e}`),!0):!1}async function gj(){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 bj(){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&&(Uu=!1)}catch{}}const xj=6e4;let Fm=0,Bc=!1;async function Uc(){if(!(Bc||document.visibilityState!=="visible")&&!(Date.now()-Fm<xj)){Fm=Date.now(),Bc=!0;try{const e=await gj();if(e&&e!=="1d87d7711-c6fabaa4"){try{sessionStorage.setItem(lu,"1")}catch{}Hu(`build version changed: 1d87d7711-c6fabaa4 -> ${e}`)}}finally{Bc=!1}}}function vj(){bj(),window.setTimeout(()=>sessionStorage.removeItem(ou),5e3),document.addEventListener("visibilitychange",()=>{Uc()}),window.addEventListener("focus",()=>{Uc()}),window.setTimeout(()=>void Uc(),2e3)}class Vo 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),!fj(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(zr,{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 Is({children:e,onError:n}){return t.jsx(Vo,{level:"page",onError:n,children:e})}function Ia({children:e,onError:n}){return t.jsx(Vo,{level:"modal",onError:n,children:e})}function yj({children:e,onError:n}){return t.jsx(Vo,{level:"root",onError:n,children:e})}const wj="modulepreload",kj=function(e){return"/"+e},zm={},En=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=kj(u),u in zm)return;zm[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":wj,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)})},qu="fn.authToken",Bm="token",jj="fn_token";let vr,Um=!1,Gl=!1;const cu="fn:auth-token-recovery-required";function Nj(){try{const e=window.localStorage.getItem(qu);return e&&e.length>0?e:void 0}catch{return}}function cb(e){try{window.localStorage.setItem(qu,e)}catch{}}function Sj(){if(!(Um||typeof window>"u")){Um=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(Bm);if(!n)return;cb(n),e.searchParams.delete(Bm);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function Er(){if(vr!==void 0)return vr;const e=Sj();if(e)return vr=e,e;const n=Nj();if(n)return vr=n,n}function Cj(e){vr=e,Gl=!1,cb(e)}function Ej(){vr=void 0,Gl=!1;try{window.localStorage.removeItem(qu)}catch{}}function Hm(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function _j(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function Mj(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!_j(e.protocol))return!1;const s=e.hostname===n.hostname,a=e.port===n.port,r=Hm(e.protocol)===Hm(n.protocol);return s&&a&&r}function Aj(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 Fi(e){const n=Er();if(!n||typeof window>"u")return e;const s=Aj(e);return!s||!Mj(s.parsed)?e:(s.parsed.searchParams.set(jj,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function _i(e){const n=Er();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function Rj(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function Ij(){typeof window>"u"||Gl||(Gl=!0,window.dispatchEvent(new CustomEvent(cu)))}async function Tj(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();Rj(a)&&Ij()}catch{}}function Pj(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,Er();const e=window.fetch.bind(window);window.fetch=function(s,a){const r=Er(),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=>(Tj(d),d))}}class Kl extends Error{status;details;constructor(n,s,a){super(n),this.name="ApiRequestError",this.status=s,this.details=a}}function $j(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function Ms(e){return`/api${e}`}async function I(e,n={}){const s=Ms(e),a=Er(),r=(()=>{if(a){const f=new Headers(n.headers??{});return f.has("Content-Type")||f.set("Content-Type","application/json"),_i(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")||$j(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 Kl(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function Dj(){return I("/health")}function Lj(){return I("/health/refresh",{method:"POST"})}function _6(){return I("/updates/check")}function Oj(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 I(`/tasks${l}`)}async function Ba(e,n){const a=Ms(V(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(a,{headers:_i({"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 db(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:w,planningModelId:v,thinkingLevel:b,summarize:y,reviewLevel:S,executionMode:j,priority:C,source:x,nodeId:N,branch:R,baseBranch:F,githubTracking:E}=e;return Jo(V("/tasks",n),{method:"POST",nodeId:s?.transportNodeId,localNodeId:s?.localNodeId,body:JSON.stringify({title:a,description:r,column:o,dependencies:l,breakIntoSubtasks:c,enabledWorkflowSteps:d,assignedAgentId:u,modelPresetId:m,modelProvider:h,modelId:f,validatorModelProvider:p,validatorModelId:g,planningModelProvider:w,planningModelId:v,thinkingLevel:b,summarize:y,reviewLevel:S,executionMode:j,priority:C,source:x,nodeId:N,branch:R,baseBranch:F,githubTracking:E})})}function Us(e,n,s){return I(V(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Fj(e,n,s,a,r,o,l,c,d){return I(V("/tasks/batch-update-models",d),{method:"POST",body:JSON.stringify({taskIds:e,modelProvider:n,modelId:s,validatorModelProvider:a,validatorModelId:r,planningModelProvider:o,planningModelId:l,nodeId:c})})}function zj(e,n,s,a){return I(V(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n,...typeof a=="object"&&a?.preserveProgress?{preserveProgress:!0}:{}})})}function Bj(e,n,s){const a=new URLSearchParams;s?.removeDependencyReferences&&a.set("removeDependencyReferences","true");const r=a.size>0?`?${a.toString()}`:"";return I(V(`/tasks/${e}${r}`,n),{method:"DELETE"})}function Uj(e,n){return I(V(`/tasks/${e}/merge`,n),{method:"POST"})}function Hj(e,n){return I(V(`/tasks/${e}/retry`,n),{method:"POST"})}function qj(e,n){return I(V(`/tasks/${e}/reset`,n),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirm:!0})})}function Vj(e,n){return I(V(`/tasks/${e}/duplicate`,n),{method:"POST"})}function ub(e,n){return I(V(`/tasks/${e}/pause`,n),{method:"POST"})}function Wj(e,n){return I(V(`/tasks/${e}/unpause`,n),{method:"POST"})}function Gj(e,n){return I(V(`/tasks/${e}/archive`,n),{method:"POST"})}function Kj(e,n){return I(V(`/tasks/${e}/unarchive`,n),{method:"POST"})}function Jj(e){return I(V("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function Yj(e,n){return I(V(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function Qj(e,n){return I(V(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function Xj(e){return I(V("/config",e))}function kc(e){return I(V("/settings",e))}function sl(e,n){return I(V("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function Zj(e){return I(V("/update-check",e))}function M6(e){return I(V("/remote/settings",e))}function A6(e,n){return I(V("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function R6(e){return I(V("/remote/status",e))}function I6(e){return I(V("/remote/install-cloudflared",e),{method:"POST"})}function T6(e){return I(V("/remote/tunnel/start",e),{method:"POST"})}function P6(e){return I(V("/remote/tunnel/stop",e),{method:"POST"})}function $6(e){return I(V("/remote/tunnel/kill-external",e),{method:"POST"})}function D6(e){return I(V("/remote/token/persistent/regenerate",e),{method:"POST"})}function L6(e,n){return I(V("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function mb(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 O6(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:a}=e,r=mb(null,s,a);return I(V(`/remote/url${r}`,n))}function F6(e="text",n={}){const{projectId:s,tokenType:a="persistent",ttlMs:r}=n,o=mb(e,a,r);return I(V(`/remote/qr${o}`,s))}function z6(e){return I(V("/memory",e))}function B6(e,n){return I(V("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function U6(e){return I(V("/memory/files",e))}function H6(e,n){const s=`path=${encodeURIComponent(e)}`;return I(V(`/memory/file?${s}`,n))}function q6(e,n,s){return I(V("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function V6(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 I(V("/memory/compact",a),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function W6(e){return I(V("/memory/dream",e),{method:"POST"})}function G6(e){return I(V("/memory/insights",e))}function K6(e,n){return I(V("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function J6(e){return I(V("/memory/extract",e),{method:"POST"})}function Y6(e){return I(V("/memory/audit",e))}function Q6(e){return I(V("/memory/stats",e))}function X6(e){return I(V("/memory/backend",e))}function Z6(e){return I(V("/memory/install-qmd",e),{method:"POST"})}function e3(e,n){return I(V("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function na(){return I("/settings/global")}function Bn(e){return I("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function t3(e){return I(V("/settings/scopes",e))}function n3(e){return I(V("/settings/pi-extensions",e))}function s3(e,n){return I(V("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function i3(e,n,s){return I(V("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function a3(){return I("/pi-settings")}async function r3(e){return I("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function o3(e){return I("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function l3(e){return I(V("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function jc(e,n,s){const a=new FormData;a.append("file",n);const r=await fetch(Ms(V(`/tasks/${e}/attachments`,s)),{method:"POST",headers:_i(),body:a}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function eN(e,n,s){return I(V(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function qm(e,n,s){const a=new URLSearchParams;s?.limit!==void 0&&a.set("limit",String(s.limit)),s?.offset!==void 0&&a.set("offset",String(s.offset));const r=a.toString()?`?${a.toString()}`:"",o=V(`/tasks/${e}/logs${r}`,n),l=await fetch(Ms(o),{headers:_i()});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 tN(e,n,s,a){return I(V(`/tasks/${e}/comments/${n}`,a),{method:"PATCH",body:JSON.stringify({text:s})})}function nN(e,n,s){return I(V(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function sN(e,n){return I(V(`/tasks/${e}/documents`,n))}function iN(e,n,s){return I(V(`/tasks/${e}/documents/${n}/revisions`,s))}async function c3(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 I(V(r,n))}function d3(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const a=s.toString(),r=`/files/markdown-list${a?`?${a}`:""}`;return I(V(r,e))}function Vm(e,n,s,a,r){return I(V(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:a?.author,metadata:a?.metadata})})}function aN(e,n,s){return I(V(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function rN(e,n,s){return I(V(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function oN(e,n,s){return I(V(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function lN(e,n){return I(V(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function cN(e,n,s){return I(V(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Ws(){return I("/models")}function dN(){return I("/usage")}function uN(){return I("/providers/claude-cli/status")}function mN(){return I("/system/fn-binary/status")}function hN(){return I("/system/fn-binary/install",{method:"POST"})}function pN(){return I("/providers/droid-cli/status")}function fN(){return I("/providers/cursor-cli/status")}function gN(){return I("/providers/llama-cpp/status")}async function u3(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return I(`/providers/hermes/status${n}`)}async function m3(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await I(`/providers/hermes/profiles${n}`)).profiles??[]}async function h3(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return I(`/providers/openclaw/status${n}`)}async function p3(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),I(`/providers/paperclip/status?${n.toString()}`)}async function f3(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),(await I(`/providers/paperclip/companies?${n.toString()}`)).companies??[]}async function g3(e){const n=new URLSearchParams({apiUrl:e.apiUrl,companyId:e.companyId});return e.apiKey&&n.set("apiKey",e.apiKey),(await I(`/providers/paperclip/agents?${n.toString()}`)).agents??[]}async function b3(e){return I("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function x3(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return I(`/providers/paperclip/cli-status${s?`?${s}`:""}`)}async function v3(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 I(`/providers/paperclip/cli-companies${s?`?${s}`:""}`)).companies??[]}async function y3(e){const n=new URLSearchParams({companyId:e.companyId});return e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath),(await I(`/providers/paperclip/cli-agents?${n.toString()}`)).agents??[]}async function w3(e={}){const n=new URLSearchParams;e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return I(`/providers/paperclip/cli-discovery${s?`?${s}`:""}`)}function bN(e){return I("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function xN(e){return I("/auth/droid-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function vN(e){return I("/auth/cursor-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function yN(e){return I("/auth/llama-cpp",{method:"POST",body:JSON.stringify({enabled:e})})}async function wN(){const n=(await I("/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 kN(e){return I("/custom-providers",{method:"POST",body:JSON.stringify(e)})}function k3(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 I(`/custom-providers/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(a)})}function j3(e){return I(`/custom-providers/${encodeURIComponent(e)}`,{method:"DELETE"})}function jN(e){const n=e.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible";return kN({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 Po(){return I("/auth/status")}function NN(e){return I("/auth/login",{method:"POST",body:JSON.stringify({provider:e,origin:window.location.origin})})}function SN(e,n){return I("/auth/manual-code",{method:"POST",body:JSON.stringify({provider:e,code:n})})}function CN(e){return I("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function EN(e){return I("/auth/cancel",{method:"POST",body:JSON.stringify({provider:e})})}function _N(e,n){return I("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function MN(e){return I("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function AN(e,n,s,a){return I("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:a})})}function RN(e,n,s,a){return I(V("/github/issues/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function IN(e,n,s){return I("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function TN(e,n,s,a){return I(V("/github/pulls/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function PN(e){return I(V("/git/remotes",e))}function $N(e){return I(V("/git/remotes/detailed",e))}function DN(e,n,s){return I(V("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function LN(e,n){return I(V(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ON(e,n,s){return I(V(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function FN(e,n,s){return I(V(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function zN(e,n,s){return I(V(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function BN(e,n){return I(V(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function UN(e,n){return(await I(V("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function il(e,n,s,a){return I(V("/terminal/sessions",a),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function Wm(e,n){return I(V(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function HN(e){return I(V("/terminal/sessions",e))}function ji(e){return I(V("/git/status",e))}function qN(e,n){const s=e?`?limit=${e}`:"";return I(V(`/git/commits${s}`,n))}function Jl(e,n){return I(V(`/git/commits/${e}/diff`,n))}function VN(e){return I(V("/git/commits/ahead",e))}function WN(e,n,s,a){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return I(V(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,a))}function Xr(e){return I(V("/git/branches",e))}function GN(e,n,s){const a=`?limit=${n}`;return I(V(`/git/branches/${encodeURIComponent(e)}/commits${a}`,s))}function KN(e){return I(V("/git/worktrees",e))}function JN(e,n,s){return I(V("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function YN(e,n){return I(V(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function Gm(e,n,s){const a=n?"?force=true":"";return I(V(`/git/branches/${encodeURIComponent(e)}${a}`,s),{method:"DELETE"})}function QN(e,n){return I(V("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function XN(e,n){const s=typeof e=="string"?void 0:e;return I(V("/git/pull",typeof e=="string"?e:n),{method:"POST",body:JSON.stringify({rebase:s?.rebase??!1})})}function ZN(e){return I(V("/git/push",e),{method:"POST"})}function al(e){return I(V("/git/stashes",e))}function eS(e,n){return I(V("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function tS(e,n,s){return I(V(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function nS(e,n){return I(V(`/git/stashes/${e}`,n),{method:"DELETE"})}function sS(e,n){return I(V(`/git/stashes/${e}/diff`,n))}function iS(e,n,s){const a=new URLSearchParams;return a.set("path",e),a.set("staged",String(n)),I(V(`/git/diff/file?${a.toString()}`,s))}function cr(e){return I(V("/git/changes",e))}function Km(e,n){return I(V("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function aS(e,n){return I(V("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function Jm(e,n){return I(V("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function rS(e,n){return I(V("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function oS(e){return I(V("/workspaces",e))}function lS(e,n,s){const a=new URLSearchParams({workspace:e});return n&&a.set("path",n),s&&a.set("projectId",s),I(`/files?${a.toString()}`)}function cS(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),I(`/files/${encodeURIComponent(n)}?${a.toString()}`)}function dS(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),I(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function uS(e,n,s){const a=new URLSearchParams({q:e});return n&&a.set("workspace",n),s&&a.set("projectId",s),I(`/files/search?${a.toString()}`)}function mS(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),I(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function hS(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),I(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function pS(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),I(`/files/${encodeURIComponent(n)}/delete?${a.toString()}`,{method:"POST"})}function fS(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),I(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function hb(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${a.toString()}`}function gS(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${a.toString()}`}function bS(e,n,s){return I(V("/planning/create-draft",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function xS(e,n,s,a,r){return I(V("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId,planningDepth:a?.planningDepth,customQuestionCount:a?.customQuestionCount,...r?{existingSessionId:r}:{}})})}function Ym(e,n,s,a){return I(V("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function vS(e,n,s){return I(V(`/planning/${encodeURIComponent(e)}/back`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function yS(e,n,s){return I(V(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function wS(e,n,s){return I(V(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function pb(e,n,s){return I(V("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function N3(e,n,s,a){return I(V("/agents/onboarding/start-streaming",s),{method:"POST",body:JSON.stringify({intent:e,context:n,mode:n.mode,existingAgentConfig:n.existingAgentConfig,planningModelProvider:a?.planningModelProvider,planningModelId:a?.planningModelId})})}function S3(e,n,s){return I(V("/agents/onboarding/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n})})}function C3(e,n){return I(V("/agents/onboarding/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function kS(e,n,s){return I(V("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function jS(e,n,s){return I(V("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function NS(e,n,s){return I(V("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const du=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(du))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function SS(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function Br(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 w=Number.parseInt(g,10);return Number.isFinite(w)?d!==null&&w<=d?!1:(d=w,!0):!0},h=()=>{if(o)return;const p=SS(e,d),g=new EventSource(Fi(p));r=g,g.onopen=()=>{l=0,u=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},g.onmessage=w=>{const v=w;m(v)&&n.onMessage?.(v)};for(const[w,v]of Object.entries(n.events??{}))g.addEventListener(w,b=>{const y=b;m(y)&&v(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 v=Math.min(1e3*2**(l-1),3e4);c=setTimeout(()=>{c=null,h()},v)}};h();const f={close:()=>{o=!0,c&&(clearTimeout(c),c=null),r?.close(),du.delete(f)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return du.add(f),f}function Qm(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 _r(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 CS(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 ES(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((a,r)=>CS(a,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function _S(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 Xm(e){return Array.isArray(e)?e.map(Qm):(e.candidates??[]).map(Qm)}async function MS(e){try{const n=await I(V("/dev-server/candidates",e));return Xm(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await I(V("/dev-server/detect",e));return Xm(s)}throw n}}function Vu(e){return I(V("/dev-server/status",e)).then(_r)}async function E3(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 I(V(`/dev-server/logs/history${a}`,n));return ES(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await Vu(n);return _S(o.logs,e)}throw r}}function AS(e,n){const s=e.cwd??e.packagePath??".",a=e.scriptName;return I(V("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:a,scriptId:a,cwd:s,packagePath:e.packagePath})}).then(_r)}function RS(e){return I(V("/dev-server/stop",e),{method:"POST"}).then(_r)}function IS(e){return I(V("/dev-server/restart",e),{method:"POST"}).then(_r)}async function TS(e,n){const s=typeof e=="string"?{url:e}:e;try{const a=await I(V("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return _r(a)}catch(a){if(a instanceof Error&&/\/dev-server\/preview-url/.test(a.message)){const r=await I(V("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return _r(r)}throw a}}function _3(e){return Ms(V("/dev-server/logs/stream",e))}async function M3(e){try{return(await I(V("/devserver",e))).sessions??[]}catch{try{const n=await Vu(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 A3(e,n){try{return await I(V(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await Vu(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 R3(e,n){try{return await I(V(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await AS({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 I3(e,n){try{return await I(V(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await RS(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 T3(e,n){try{return await I(V(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await IS(n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}}}async function P3(e,n,s){try{const a=await I(V(`/devserver/${encodeURIComponent(e)}/preview`,s),{method:"POST",body:JSON.stringify({url:n})});return{url:a.url??null,source:a.source??null}}catch{const a=await TS({url:n},s);return{url:a.previewUrl??a.manualUrl??null,source:"manual"}}}async function $3(e){try{return(await I(V("/devserver/detect",e))).candidates??[]}catch{try{return(await MS(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function D3(e,n){return Ms(V(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function Wo(e,n,s=25e3){const a=setInterval(()=>{_0(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(a)}}}function PS(e,n){return Ms(V(`/planning/${encodeURIComponent(e)}/stream`,n))}function $S(e,n){return Ms(V(`/agents/onboarding/${encodeURIComponent(e)}/stream`,n))}function L3(e,n,s,a){const r=$S(e,n),o=Br(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 DS(e,n,s,a){const r=PS(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Br(r,{onOpen:()=>{c(),o=Wo(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 Go(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 LS(e){return I(Go("/routines",e))}function OS(e,n){return I(Go("/routines",n),{method:"POST",body:JSON.stringify(e)})}function Zm(e,n,s){return I(Go(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function FS(e,n){await I(Go(`/routines/${e}`,n),{method:"DELETE"})}function zS(e,n){return I(Go(`/routines/${e}/trigger`,n),{method:"POST"})}function eh(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 I(`/activity${s}`)}function BS(e){const n=V("/activity",e);return I(n,{method:"DELETE"})}function Ko(e){return I(V("/workflow-steps",e))}function th(e,n){return I(V("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function US(e,n,s){return I(V(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function HS(e,n){return I(V(`/workflow-steps/${e}`,n),{method:"DELETE"})}function nh(e,n){return I(V(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function qS(e,n){return I(V(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function VS(){return I("/workflow-step-templates")}function WS(){return I("/plugin-workflow-step-templates")}function GS(e,n){return I(V(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function $o(e){return I(V("/scripts",e))}function KS(e,n,s){return I(V("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function JS(e,n){return I(V(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function fb(e,n,s){return(await I(V("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const rl={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 gb(e){if(!(e instanceof Error))return rl.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?rl.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?rl.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:rl.NETWORK}function YS(e,n){return I(V("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function QS(e,n,s){return I(V(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function XS(e,n){return Ms(V(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function ZS(e,n,s,a){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=Br(XS(e,n),{onOpen:()=>{l(),r=Wo(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 e1(e,n,s,a,r){return I(V("/subtasks/create-tasks",a),{method:"POST",body:JSON.stringify({sessionId:e,parentTaskId:s,...r?.branch!==void 0?{branch:r.branch}:{},...r?.baseBranch!==void 0?{baseBranch:r.baseBranch}:{},...r?.branchSelection?{branchSelection:r.branchSelection}:{},...r?.branchAssignment?{branchAssignment:r.branchAssignment}:{},subtasks:n.map(o=>({tempId:o.id,title:o.title,description:o.description,size:o.suggestedSize,dependsOn:o.dependsOn}))})})}function bb(e,n,s){return I(V("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function V(e,n){if(!n)return e;const s=e.includes("?")?"&":"?";return`${e}${s}projectId=${encodeURIComponent(n)}`}function t1(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 Jo(e,n){const{nodeId:s,localNodeId:a,...r}=n??{},o=t1(e,s,a);return I(o,r)}function Ur(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 I(`/agents${a}`)}function uu(e,n){return I(V(`/agents/${encodeURIComponent(e)}`,n))}function n1(e,n){return I(V("/agents",n),{method:"POST",body:JSON.stringify(e)})}function s1(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function O3(e,n,s){const a=new FormData;a.append("file",n);const r=await fetch(Ms(V(`/agents/${encodeURIComponent(e)}/avatar`,s)),{method:"POST",headers:_i(),body:a}),o=await r.json();if(!r.ok)throw new Error(o.error||"Avatar upload failed");return o}function F3(e,n){return I(V(`/agents/${encodeURIComponent(e)}/avatar`,n),{method:"DELETE"})}function z3(e,n){return I(V(`/agents/${encodeURIComponent(e)}/upgrade-heartbeat-procedure`,n),{method:"POST"})}function B3(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function U3(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function H3(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function q3(e,n){return I(V(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function V3(e,n,s){const a=`path=${encodeURIComponent(n)}`;return I(V(`/agents/${encodeURIComponent(e)}/memory/file?${a}`,s))}function W3(e,n,s,a){return I(V(`/agents/${encodeURIComponent(e)}/memory/file`,a),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function i1(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function a1(e,n){return I(V(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function G3(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 I(`/agents/${encodeURIComponent(e)}/runs${r}`)}function K3(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function J3(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function Y3(e,n,s){const a=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return I(V(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:a,triggerDetail:r})})}function Q3(e,n){return I(V(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function r1(e){return I(V("/agents/stats",e))}function X3(e,n){return I(V(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function Z3(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const a=s.toString();return I(`/agents/org-tree${a?`?${a}`:""}`)}function e5(e,n){return I(V(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function sh(e,n,s){return I(V(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function xb(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 o1(e,n){const s=await I(V(`/tasks/${encodeURIComponent(e)}/review`,n));return xb(s)}async function l1(e,n){const s=await I(V(`/tasks/${encodeURIComponent(e)}/review/refresh`,n),{method:"POST"});return xb(s)}function c1(e,n,s){return I(V(`/tasks/${encodeURIComponent(e)}/review/address`,s),{method:"POST",body:JSON.stringify({selectedItems:n,tab:"review"})})}function t5(e,n){return I(V(`/agents/${encodeURIComponent(e)}/tasks`,n))}function n5(){return I("/agents/companies")}function s5(e,n){return I(V("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function i5(e,n){return I(V("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function a5(e,n){return I(V(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function r5(e){return I(V("/backups",e))}function o5(e){return I(V("/backups",e),{method:"POST"})}function l5(e,n){const s=V("/settings/export",n),a=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return I(a)}function c5(e,n,s){return I(V("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function d1(e){return Array.isArray(e.nodeMappings)||Array.isArray(e.projectNodeMappings)||Array.isArray(e.pathMappings)}function ih(){return I("/projects/across-nodes")}function Yl(){return I("/nodes")}function d5(){return I("/docker/nodes")}function u5(e){return I(`/docker/nodes/${encodeURIComponent(e)}/container-status`)}function m5(e,n){const s=new URLSearchParams;typeof n?.tail=="number"&&s.set("tail",String(n.tail));const a=s.size>0?`?${s.toString()}`:"";return I(`/docker/nodes/${encodeURIComponent(e)}/logs${a}`)}function h5(e){return I("/docker-nodes",{method:"POST",body:JSON.stringify(e)})}function u1(e){return I("/nodes",{method:"POST",body:JSON.stringify(e)})}function m1(e){return I("/nodes/discover-projects",{method:"POST",body:JSON.stringify(e)})}function h1(e,n){return I(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function p1(e){return I(`/nodes/${encodeURIComponent(e)}/docker-config`)}function f1(e,n){return I(`/nodes/${encodeURIComponent(e)}/docker-config`,{method:"PATCH",body:JSON.stringify(n)})}function g1(e){return I(`/nodes/${encodeURIComponent(e)}/docker-config/diff`)}function ah(e){return I(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function b1(e){const n=await I(`/nodes/${encodeURIComponent(e)}/health-check`,{method:"POST"});return{nodeId:n.nodeId??e,status:n.status,responseTimeMs:n.responseTimeMs,error:n.error,checkedAt:n.checkedAt??new Date().toISOString()}}async function p5(){return I("/mesh/state")}function f5(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=Er();l&&o.set("fn_token",l);const c=o.toString(),d=`/browse-directory${c?`?${c}`:""}`;return I(d)}function x1(e){return I("/projects",{method:"POST",body:JSON.stringify(e)})}function vb(e){return I(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function v1(e,n,s){return I(`/projects/${encodeURIComponent(e)}/path-mappings/${encodeURIComponent(n)}`,{method:"PUT",body:JSON.stringify({path:s})})}function rh(e){return I(`/projects/${encodeURIComponent(e)}/health`)}function y1(e){return I(V("/executor/stats",e))}function w1(e){return I(V("/system-stats",e))}function k1(e){return I(V("/kill-vitest",e),{method:"POST"})}function oh(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 I(`/activity-feed${s}`)}function j1(e){return I(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function N1(e){return I(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function g5(){return I("/global-concurrency")}function b5(e){return I("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function S1(e,n){return I(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function yb(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 I(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function C1(e,n){return I(V(`/tasks/${encodeURIComponent(e)}/commit-associations`,n))}function E1(e){return I(V("/missions",e))}function _1(e,n){return I(V("/missions",n),{method:"POST",body:JSON.stringify(e)})}function wb(e,n){return I(V(`/missions/${encodeURIComponent(e)}`,n))}function M1(e,n,s){return I(V(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function A1(e,n){return I(V(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function R1(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 I(V(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function I1(e){return I(V("/missions/health",e))}function T1(e,n,s){return I(V(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function P1(e,n,s){return I(V(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function $1(e,n){return I(V(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function D1(e,n,s){return I(V(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function L1(e,n,s){return I(V(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function O1(e,n){return I(V(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function F1(e,n){return I(V(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function z1(e,n,s){return I(V(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function B1(e,n,s){return I(V(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function U1(e,n){return I(V(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function H1(e,n,s){return I(V(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function q1(e,n){return I(V(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function V1(e,n,s,a,r){return I(V(`/missions/features/${encodeURIComponent(e)}/triage`,a),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s,...r})})}function W1(e,n,s){return I(V(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST",body:JSON.stringify({})})}function Hc(e,n){return I(V(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function G1(e,n,s){return I(V(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function K1(e,n,s){return I(V(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function J1(e,n,s){return I(V(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function Y1(e,n,s){return I(V(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function Q1(e,n){return I(V(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function qc(e,n){return I(V(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function lh(e,n){return I(V(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function X1(e,n){return I(V(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function ch(e,n){return I(V(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function Z1(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 I(V(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function e0(e,n){return I(V(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function t0(e,n){return I(V(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function n0(e,n){return I(V(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function s0(e,n){return I(V(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function i0(e,n,s){return I(V(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function a0(e,n,s){return I(V("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function r0(e,n,s,a){return I(V("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function o0(e,n,s){return I(V(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function kb(e,n,s){return I(V("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}async function l0(e){const n=e?`?${new URLSearchParams({projectId:e}).toString()}`:"";return(await I(`/missions/interview/drafts${n}`)).drafts??[]}function c0(e,n,s){return I(V(`/missions/interview/drafts/${encodeURIComponent(e)}/discard`,n),{method:"POST",body:JSON.stringify({tabId:s})})}function d0(e,n,s,a){return I(V("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function u0(e,n,s,a){const r=Ms(V(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Br(r,{onOpen:()=>{c(),o=Wo(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 Yo(e,n,s){return V(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function Qo(e,n,s){return V(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function m0(e,n){return I(Yo(e,"/start",n),{method:"POST"})}function h0(e,n,s,a){return I(Yo(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function p0(e,n,s,a){const r=Ms(Yo(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Br(r,{onOpen:()=>{c(),o=Wo(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 f0(e,n,s){return I(Yo(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function g0(e,n){return I(Yo(e,"/skip",n),{method:"POST"})}function b0(e,n){return I(Qo(e,"/start",n),{method:"POST"})}function x0(e,n,s,a){return I(Qo(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function v0(e,n,s,a){const r=Ms(Qo(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Br(r,{onOpen:()=>{c(),o=Wo(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 y0(e,n,s){return I(Qo(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function w0(e,n){return I(Qo(e,"/skip",n),{method:"POST"})}async function k0(e,n){try{return await I(V(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function x5(e){return I(V("/todos",e))}function v5(e,n){const s={title:e};return I(V("/todos",n),{method:"POST",body:JSON.stringify(s)})}function y5(e,n,s){const a={title:n};return I(V(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function w5(e,n){return I(V(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function k5(e,n,s){const a={text:n};return I(V(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(a)})}function j5(e,n,s){const a=n;return I(V(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function N5(e,n){return I(V(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function S5(e,n,s){return I(V(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function Mr(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function Wu(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(Ms(`/ai-sessions${a?`?${a}`:""}`),{headers:_i()});return r.ok?(await r.json()).sessions??[]:[]}async function j0(e){return I(`/ai-sessions/${encodeURIComponent(e)}/archive`,{method:"POST"})}async function N0(e){return I(`/ai-sessions/${encodeURIComponent(e)}/unarchive`,{method:"POST"})}async function Di(e){const n=await fetch(Ms(`/ai-sessions/${encodeURIComponent(e)}`),{headers:_i()});return n.ok?n.json():null}async function S0(e,n){const s=await I(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function C0(e,n){return I(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function E0(e,n){return I(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function jb(e){await fetch(Ms(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:_i()})}function _0(e,n){return I(V(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function M0(e,n,s){return I(V(`/ai-sessions/${encodeURIComponent(e)}/draft`,s),{method:"PATCH",body:JSON.stringify(n)})}function A0(e,n){return I(V(`/planning/${encodeURIComponent(e)}/summarize-draft-title`,n),{method:"POST"})}function R0(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.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 I(`/messages/inbox${a}`)}function I0(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 I(`/messages/outbox${a}`)}function Nb(e){return I(V("/messages/unread-count",e))}function T0(e,n){return I(V("/messages",n),{method:"POST",body:JSON.stringify(e)})}function P0(e,n){return I(V(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function $0(e){return I(V("/messages/read-all",e),{method:"POST"})}function D0(e,n){return I(V(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function L0(e,n,s){const a=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return I(V(a,s))}function O0(e,n){return I(V(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function F0(e){return I(V("/agents/mailbox/all",e))}function ol(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 I(`/approvals${a}`)}function dh(e,n){return I(V(`/approvals/${encodeURIComponent(e)}`,n))}function z0(e,n,s){return I(V(`/approvals/${encodeURIComponent(e)}/decision`,s),{method:"POST",body:JSON.stringify(n)})}function C5(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 I(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function E5(e,n){return I(V(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function _5(e,n,s){const a=new URLSearchParams;s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/performance${r}`)}function M5(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 I(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function A5(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function R5(e,n){return I(V(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function I5(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function T5(e,n){return I(V(`/agents/${encodeURIComponent(e)}/budget`,n))}function P5(e,n){return I(V(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function $5(e){return I(V("/plugins",e))}async function D5(e,n){return I(V("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function L5(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function O5(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function F5(e,n){return I(V(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function z5(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function B5(e,n,s){return I(V(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function U5(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/setup-status`,n))}async function H5(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/setup/install`,n),{method:"POST"})}async function q5(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function V5(e,n,s){return I(V(`/plugins/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function W5(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/rescan`,n),{method:"POST"})}async function B0(e){return I(V("/plugins/ui-slots",e))}async function U0(e){return I(V("/plugins/dashboard-views",e))}async function G5(e){return I(V("/plugins/runtimes",e))}async function H0(e){return(await I(V("/skills/discovered",e))).skills}async function K5(e,n,s){return I(V("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function J5(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 I(V(`/skills/catalog${r}`,s))}async function Y5(e,n){return(await I(V(`/skills/${encodeURIComponent(e)}/content`,n))).content}function uh(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const a=s.toString();return I(`/chat/sessions${a?`?${a}`:""}`)}async function q0(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 I(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function V0(e,n){return I(V("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function W0(e,n){return I(V(`/chat/sessions/${encodeURIComponent(e)}`,n))}function Q5(e,n,s){return I(V(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function X5(e,n){return I(V(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Zr(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 I(V(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function Z5(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 I(`/chat/rooms${a?`?${a}`:""}`)}function e8(e,n){const s={...e,...n?{projectId:n}:{}};return I(V("/chat/rooms",n),{method:"POST",body:JSON.stringify(s)})}function t8(e,n){return I(V(`/chat/rooms/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function n8(e,n){return I(V(`/chat/rooms/${encodeURIComponent(e)}/members`,n))}function s8(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 I(V(`/chat/rooms/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function i8(e,n,s){return I(V(`/chat/rooms/${encodeURIComponent(e)}/messages`,s),{method:"POST",body:JSON.stringify(n)})}function G0(e,n){return I(V(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function K0(e){if(!e||typeof e!="object")return null;const n=e,s=typeof n.summary=="string"?n.summary.trim():"";if(!s)return null;const a=(()=>{const r=n.reference;if(!r||typeof r!="object")return;const o=r,l=typeof o.kind=="string"?o.kind.trim():"",c=typeof o.id=="string"?o.id.trim():"";if(!(!l||!c))return{kind:l,id:c,...typeof o.label=="string"&&o.label.trim()?{label:o.label.trim()}:{}}})();return{summary:s,...typeof n.errorClass=="string"&&n.errorClass.trim()?{errorClass:n.errorClass.trim()}:{},...typeof n.code=="string"&&n.code.trim()?{code:n.code.trim()}:{},...typeof n.detail=="string"&&n.detail.trim()?{detail:n.detail.trim()}:{},...a?{reference:a}:{}}}function Sb(e){try{const n=JSON.parse(e),s=K0(n);return s||(n&&typeof n=="object"&&typeof n.message=="string"?n.message:typeof n=="string"?n:e||"Stream error")}catch{return e||"Stream error"}}function J0(e,n,s,a,r,o){const l=Ms(V(`/chat/sessions/${encodeURIComponent(e)}/messages`,r)),c=new AbortController;let d=!1,u=!1,m=!1;const h=Math.max(1e3,6e4);let f=null;const p=()=>{f&&(clearTimeout(f),f=null)},g=()=>{m||(m=!0,p())},w=(v,b)=>{if(v)switch(g(),v){case"thinking":try{s.onThinking?.(JSON.parse(b))}catch{s.onThinking?.(b)}break;case"text":try{s.onText?.(JSON.parse(b))}catch{s.onText?.(b)}break;case"tool_start":try{s.onToolStart?.(JSON.parse(b))}catch{}break;case"tool_end":try{s.onToolEnd?.(JSON.parse(b))}catch{}break;case"fallback":try{s.onFallback?.(JSON.parse(b))}catch{}break;case"done":u=!0;try{const y=JSON.parse(b);s.onDone?.({messageId:typeof y.messageId=="string"?y.messageId:"",...y.message&&typeof y.message=="object"?{message:y.message}:{}})}catch{s.onDone?.({messageId:""})}break;case"error":u=!0,s.onError?.(Sb(b));break}};return(async()=>{try{const v=Array.isArray(a)&&a.length>0,b=v?(()=>{const E=new FormData;return E.append("content",n),a.forEach(_=>E.append("attachments",_)),E})():JSON.stringify({content:n}),y=await fetch(l,{method:"POST",headers:v?_i():_i({"Content-Type":"application/json"}),body:b,signal:c.signal});if(!y.ok){const E=await y.text();let _=`Request failed: ${y.status}`;try{_=JSON.parse(E).error||_}catch{}s.onError?.(_);return}if(!y.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected"),f=setTimeout(()=>{u||d||m||(u=!0,s.onError?.("Timed out waiting for first response event"),c.abort())},h);const S=y.body.getReader(),j=new TextDecoder;let C="",x="",N=[];const R=(E,_=!1)=>{C+=E;const K=C.split(`
|
|
643
|
+
`);C=K.pop()||"",_&&C.length>0&&(K.push(C),C="");for(const U of K){const A=U.endsWith("\r")?U.slice(0,-1):U;if(A.startsWith("event:"))x=A.slice(6).trim();else if(A.startsWith("data:")){const T=A.slice(5);N.push(T.startsWith(" ")?T.slice(1):T)}else if(A===""){const T=N.join(`
|
|
644
|
+
`);w(x,T),x="",N=[]}}if(_&&x&&N.length>0){const U=N.join(`
|
|
645
|
+
`);w(x,U),x="",N=[]}};for(;;){const{done:E,value:_}=await S.read();if(E){R(j.decode(),!0);break}R(j.decode(_,{stream:!0}))}const F=C.length>0||x.length>0||N.length>0;!u&&!d&&!F&&s.onError?.("Connection closed unexpectedly"),p()}catch(v){if(v instanceof DOMException&&v.name==="AbortError"){!d&&!u&&s.onError?.("Connection aborted"),p();return}if(d){p();return}p(),s.onError?.(v instanceof Error?v.message:"Connection error")}})(),{close:()=>{d=!0,p(),c.abort()},isConnected:()=>!d}}function Y0(e,n,s,a){const r=Ms(V(`/chat/sessions/${encodeURIComponent(e)}/stream`,s)),o=new AbortController;let l=!1,c=!1;const d=(u,m)=>{if(u)switch(u){case"thinking":try{n.onThinking?.(JSON.parse(m))}catch{n.onThinking?.(m)}break;case"text":try{n.onText?.(JSON.parse(m))}catch{n.onText?.(m)}break;case"tool_start":try{n.onToolStart?.(JSON.parse(m))}catch{}break;case"tool_end":try{n.onToolEnd?.(JSON.parse(m))}catch{}break;case"fallback":try{n.onFallback?.(JSON.parse(m))}catch{}break;case"done":c=!0;try{const h=JSON.parse(m);n.onDone?.({messageId:typeof h.messageId=="string"?h.messageId:"",...h.message&&typeof h.message=="object"?{message:h.message}:{}})}catch{n.onDone?.({messageId:""})}break;case"error":c=!0,n.onError?.(Sb(m));break}};return(async()=>{try{const u=new Headers(_i());typeof a?.lastEventId=="number"&&u.set("Last-Event-ID",String(a.lastEventId));const m=await fetch(r,{method:"GET",headers:u,signal:o.signal});if(!m.ok){const y=await m.text();let S=`Request failed: ${m.status}`;try{S=JSON.parse(y).error||S}catch{}n.onError?.(S);return}if(!m.body){n.onError?.("No response body");return}n.onConnectionStateChange?.("connected");const h=m.body.getReader(),f=new TextDecoder;let p="",g="",w=[];const v=(y,S=!1)=>{p+=y;const j=p.split(`
|
|
646
|
+
`);p=j.pop()||"",S&&p.length>0&&(j.push(p),p="");for(const C of j){const x=C.endsWith("\r")?C.slice(0,-1):C;if(x.startsWith("event:"))g=x.slice(6).trim();else if(x.startsWith("data:")){const N=x.slice(5);w.push(N.startsWith(" ")?N.slice(1):N)}else if(x===""){const N=w.join(`
|
|
647
|
+
`);d(g,N),g="",w=[]}}if(S&&g&&w.length>0){const C=w.join(`
|
|
648
|
+
`);d(g,C),g="",w=[]}};for(;;){const{done:y,value:S}=await h.read();if(y){v(f.decode(),!0);break}v(f.decode(S,{stream:!0}))}const b=p.length>0||g.length>0||w.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 a8(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 I(V(`/insights${a}`,n))}function r8(e,n){return I(V(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function o8(e,n){return I(V(`/insights/${encodeURIComponent(e)}/archive`,n),{method:"POST"})}function l8(e,n){return I(V(`/insights/${encodeURIComponent(e)}/unarchive`,n),{method:"POST"})}function c8(e="manual",n,s,a,r){const o={trigger:e,inputMetadata:n};return a&&(o.modelProvider=a),r&&(o.modelId=r),I(V("/insights/run",s),{method:"POST",body:JSON.stringify(o)})}function d8(e){return I(V("/insights/runs",e))}function u8(e,n){return I(V(`/insights/runs/${encodeURIComponent(e)}`,n))}function m8(e,n){return I(V(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function h8(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 I(V(`/evals${a}`,n))}function p8(e,n){return I(V(`/evals/${encodeURIComponent(e)}`,n))}function f8(e){return I(V("/evals/runs",e))}function g8(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 I(V(`/research/runs${a}`,n))}function b8(e,n){return I(V("/research/runs",n),{method:"POST",body:JSON.stringify(e)})}function x8(e,n){return I(V(`/research/runs/${encodeURIComponent(e)}`,n))}function Cb(e){if(e instanceof Kl){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 v8(e,n){try{return await I(V(`/research/runs/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}catch(s){Cb(s)}}async function y8(e,n){try{return await I(V(`/research/runs/${encodeURIComponent(e)}/retry`,n),{method:"POST"})}catch(s){Cb(s)}}function w8(e,n,s){return I(V(`/research/runs/${encodeURIComponent(e)}/export?format=${encodeURIComponent(n)}`,s))}function k8(e,n,s){const a=n.findingId??"finding-1";return I(V(`/research/runs/${encodeURIComponent(e)}/findings/${encodeURIComponent(a)}/task`,s),{method:"POST",body:JSON.stringify({title:n.title,description:n.description,priority:n.priority,attachExport:n.attachExport})})}function j8(e,n,s){const a=n.findingId??"finding-1";return I(V(`/research/runs/${encodeURIComponent(e)}/findings/${encodeURIComponent(a)}/tasks/${encodeURIComponent(n.taskId)}/enrich`,s),{method:"POST",body:JSON.stringify({attachExport:n.attachExport})})}async function Q0(e){return Jo("/health",{nodeId:e})}async function X0(e){return Jo("/projects",{nodeId:e})}async function Z0(e,n,s){const a=new URLSearchParams({projectId:n});return s&&s.trim()&&a.set("q",s.trim()),Jo(`/tasks?${a.toString()}`,{nodeId:e})}async function eC(e,n){return Jo(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function N8(e){return I(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function S8(e){return I(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function C8(e){return I(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function E8(e){return I(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}async function tC(e,n){return Promise.all(n.map(({projectId:s,path:a})=>v1(s,e,a)))}function nC(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 sC({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}=nC(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 iC(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Ua({status:e,showLabel:n=!1,className:s,compact:a=!1}){const r=iC(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 mh=new Map,aC=6e4;function Eb(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=mh.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 w=await B0(e);if(h||d.current)return;mh.set(m,{slots:w,expiresAt:Date.now()+aC}),s(w),c.current=!0}catch(w){if(h||d.current)return;l(w instanceof Error?w.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 hh({size:e,color:n,label:s="llama.cpp"}){return t.jsx(Zg,{size:e,color:n,"aria-label":s,"data-testid":"llama-cpp-icon"})}const rC={sm:16,md:20,lg:24};function oC({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 ph({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 Ri({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 lC({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 fh({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 cC({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 Vc({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 gh({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 bh({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 xh({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 Wc({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 vh({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 eo({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 yh({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 Gc({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 wh({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 Kc({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 dC({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 uC({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 kh({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 Jc({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 mC({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 jh({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 Yc({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 Nh({size:e,label:n="OpenClaw"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":n,children:[t.jsx("rect",{width:"16",height:"16",fill:"none"}),t.jsxs("g",{fill:"#3a0a0d",children:[t.jsx("rect",{x:"1",y:"5",width:"1",height:"3"}),t.jsx("rect",{x:"2",y:"4",width:"1",height:"1"}),t.jsx("rect",{x:"2",y:"8",width:"1",height:"1"}),t.jsx("rect",{x:"3",y:"3",width:"1",height:"1"}),t.jsx("rect",{x:"3",y:"9",width:"1",height:"1"}),t.jsx("rect",{x:"4",y:"2",width:"1",height:"1"}),t.jsx("rect",{x:"4",y:"10",width:"1",height:"1"}),t.jsx("rect",{x:"5",y:"2",width:"6",height:"1"}),t.jsx("rect",{x:"11",y:"2",width:"1",height:"1"}),t.jsx("rect",{x:"12",y:"3",width:"1",height:"1"}),t.jsx("rect",{x:"12",y:"9",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"4",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"8",width:"1",height:"1"}),t.jsx("rect",{x:"14",y:"5",width:"1",height:"3"}),t.jsx("rect",{x:"5",y:"11",width:"6",height:"1"}),t.jsx("rect",{x:"4",y:"12",width:"1",height:"1"}),t.jsx("rect",{x:"11",y:"12",width:"1",height:"1"}),t.jsx("rect",{x:"3",y:"13",width:"1",height:"1"}),t.jsx("rect",{x:"12",y:"13",width:"1",height:"1"}),t.jsx("rect",{x:"5",y:"14",width:"6",height:"1"})]}),t.jsxs("g",{fill:"#ff4f40",children:[t.jsx("rect",{x:"5",y:"3",width:"6",height:"1"}),t.jsx("rect",{x:"4",y:"4",width:"8",height:"1"}),t.jsx("rect",{x:"3",y:"5",width:"10",height:"1"}),t.jsx("rect",{x:"3",y:"6",width:"10",height:"1"}),t.jsx("rect",{x:"3",y:"7",width:"10",height:"1"}),t.jsx("rect",{x:"4",y:"8",width:"8",height:"1"}),t.jsx("rect",{x:"5",y:"9",width:"6",height:"1"}),t.jsx("rect",{x:"5",y:"12",width:"6",height:"1"}),t.jsx("rect",{x:"6",y:"13",width:"4",height:"1"})]}),t.jsxs("g",{fill:"#ff775f",children:[t.jsx("rect",{x:"1",y:"6",width:"2",height:"1"}),t.jsx("rect",{x:"2",y:"5",width:"1",height:"1"}),t.jsx("rect",{x:"2",y:"7",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"6",width:"2",height:"1"}),t.jsx("rect",{x:"13",y:"5",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"7",width:"1",height:"1"})]}),t.jsxs("g",{fill:"#081016",children:[t.jsx("rect",{x:"6",y:"5",width:"1",height:"1"}),t.jsx("rect",{x:"9",y:"5",width:"1",height:"1"})]}),t.jsxs("g",{fill:"#f5fbff",children:[t.jsx("rect",{x:"6",y:"4",width:"1",height:"1"}),t.jsx("rect",{x:"9",y:"4",width:"1",height:"1"})]})]})}function Qc({size:e,color:n,label:s="Paperclip"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":s,children:t.jsx("path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",stroke:n,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}function Sh({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 hC({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 pC({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 fC={anthropic:{component:oC,color:"var(--provider-anthropic)"},"claude-cli":{component:Sh,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:Sh,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"droid-cli":{component:hC,color:"var(--provider-openai)",label:"Factory AI — via Droid CLI"},"cursor-cli":{component:pC,color:"var(--provider-cursor-cli)",label:"Cursor — via Cursor CLI"},"llama-cpp":{component:hh,color:"var(--provider-ollama)",label:"llama.cpp"},"llama-server":{component:hh,color:"var(--provider-ollama)",label:"llama.cpp"},openai:{component:ph,color:"var(--provider-openai)"},"openai-codex":{component:ph,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:Ri,color:"var(--provider-gemini)"},gemini:{component:Ri,color:"var(--provider-gemini)"},"google-antigravity":{component:Ri,color:"var(--provider-gemini)",label:"Google Gemini"},antigravity:{component:Ri,color:"var(--provider-gemini)",label:"Google Gemini"},"google-vertex":{component:Ri,color:"var(--provider-gemini)",label:"Google Vertex AI"},vertex:{component:Ri,color:"var(--provider-gemini)",label:"Google Vertex AI"},"google-cloud-code":{component:Ri,color:"var(--provider-gemini)",label:"Google Cloud Code"},"cloud-code":{component:Ri,color:"var(--provider-gemini)",label:"Google Cloud Code"},"google-gemini-cli":{component:Ri,color:"var(--provider-gemini)",label:"Google Gemini CLI"},"google-generative-ai":{component:Ri,color:"var(--provider-gemini)",label:"Google Generative AI"},ollama:{component:lC,color:"var(--text)"},github:{component:jh,color:"var(--text)"},"github-copilot":{component:jh,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:mC,color:"var(--provider-openrouter)"},minimax:{component:fh,color:"var(--provider-minimax)"},"minimax-cn":{component:fh,color:"var(--provider-minimax)",label:"MiniMax (CN)"},zai:{component:cC,color:"var(--provider-zai)"},kimi:{component:Vc,color:"var(--provider-kimi)"},moonshot:{component:Vc,color:"var(--provider-kimi)"},"kimi-coding":{component:Vc,color:"var(--provider-kimi)",label:"Kimi"},bedrock:{component:gh,color:"var(--provider-bedrock)"},"amazon-bedrock":{component:gh,color:"var(--provider-bedrock)",label:"Amazon Bedrock"},xai:{component:bh,color:"var(--text)"},grok:{component:bh,color:"var(--text)",label:"xAI"},opencode:{component:xh,color:"var(--provider-opencode)"},"opencode-go":{component:xh,color:"var(--provider-opencode)",label:"Opencode (Go)"},deepseek:{component:Wc,color:"var(--provider-deepseek)",label:"DeepSeek"},"deepseek-ai":{component:Wc,color:"var(--provider-deepseek)",label:"DeepSeek"},"deep-seek":{component:Wc,color:"var(--provider-deepseek)",label:"DeepSeek"},cloudflare:{component:vh,color:"var(--provider-cloudflare)",label:"Cloudflare"},cloudflared:{component:vh,color:"var(--provider-cloudflare)",label:"Cloudflare"},qwen:{component:eo,color:"var(--provider-qwen)"},"qwen-ai":{component:eo,color:"var(--provider-qwen)",label:"Qwen"},"qwen-coder":{component:eo,color:"var(--provider-qwen)",label:"Qwen Coder"},alibaba:{component:eo,color:"var(--provider-qwen)",label:"Qwen"},tongyi:{component:eo,color:"var(--provider-qwen)",label:"Qwen"},lmstudio:{component:yh,color:"var(--provider-lmstudio)",label:"LM Studio"},"lm-studio":{component:yh,color:"var(--provider-lmstudio)",label:"LM Studio"},huggingface:{component:Gc,color:"var(--provider-huggingface)",label:"Hugging Face"},"hugging-face":{component:Gc,color:"var(--provider-huggingface)",label:"Hugging Face"},hf:{component:Gc,color:"var(--provider-huggingface)",label:"Hugging Face"},mistral:{component:wh,color:"var(--provider-mistral)",label:"Mistral AI"},"mistral-ai":{component:wh,color:"var(--provider-mistral)",label:"Mistral AI"},azure:{component:Kc,color:"var(--provider-azure)"},"azure-openai":{component:Kc,color:"var(--provider-azure)",label:"Azure OpenAI"},"azure-openai-responses":{component:Kc,color:"var(--provider-azure)",label:"Azure OpenAI"},fireworks:{component:Jc,color:"var(--provider-fireworks)",label:"Fireworks AI"},"fireworks-ai":{component:Jc,color:"var(--provider-fireworks)",label:"Fireworks AI"},fireworksai:{component:Jc,color:"var(--provider-fireworks)",label:"Fireworks AI"},cerebras:{component:dC,color:"var(--provider-cerebras)"},groq:{component:uC,color:"var(--provider-groq)"},vercel:{component:kh,color:"var(--provider-vercel)"},"vercel-ai-gateway":{component:kh,color:"var(--provider-vercel)",label:"Vercel AI Gateway"},hermes:{component:Yc,color:"var(--provider-hermes)",label:"Hermes"},"hermes-agent":{component:Yc,color:"var(--provider-hermes)",label:"Hermes"},hermesagent:{component:Yc,color:"var(--provider-hermes)",label:"Hermes"},openclaw:{component:Nh,color:"var(--provider-openclaw)",label:"OpenClaw"},"open-claw":{component:Nh,color:"var(--provider-openclaw)",label:"OpenClaw"},paperclip:{component:Qc,color:"var(--provider-paperclip)",label:"Paperclip"},paperclipai:{component:Qc,color:"var(--provider-paperclip)",label:"Paperclip"},"paperclip-ai":{component:Qc,color:"var(--provider-paperclip)",label:"Paperclip"}};function zn({provider:e,size:n="sm"}){const s=e.toLowerCase(),a=fC[s],r=a?.component,o=a?.color??"var(--text-muted)",l=a?.label,c=rC[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(Zg,{size:c})})}function _b({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 pN();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 xN(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,w=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"droid"})," CLI. Uses your existing Factory AI subscription / quota instead of an API key."]}),v=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),g?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void f(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void f(!0),disabled:o!==null||!p,title:p?void 0:"`droid` binary not detected on PATH — install Droid CLI first.",children:o==="enabling"?"Enabling…":"Enable"})]});return s?t.jsxs("div",{className:`auth-provider-card auth-provider-card--cli${e?" auth-provider-card--authenticated":""}`,"data-testid":"droid-cli-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(zn,{provider:"droid-cli",size:"sm"}),t.jsx("strong",{children:"Factory AI — via Droid CLI"}),t.jsx(gC,{status:a,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:v})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:"Details"}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[w,t.jsx(Ch,{status:a,authenticated:e}),c&&t.jsx(Eh,{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(zn,{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"}),w,t.jsx(Ch,{status:a,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(Eh,{action:c})]})}function gC({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 Ch({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(jt,{size:10,className:"animate-spin"})," Probing local CLI…"]});const{binary:s,enabled:a,extension:r,ready:o}=e;return s.available?a?r&&r.status!=="ok"?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--warning",children:["⚠ Extension load failed: ",r.reason??r.status]}):o||n?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--connected",children:["✓ Connected",s.version?` — ${s.version}`:""]}):t.jsx("small",{className:"settings-muted",children:"Enabled. Validating…"}):t.jsxs("small",{className:"settings-muted",children:[t.jsx("code",{children:"droid"})," ",s.version?`(${s.version})`:""," detected",s.binaryPath?` at ${s.binaryPath}`:"",". Click Enable to route AI calls through it."]}):t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--error",children:["✗ ",s.reason??"`droid` not found on PATH"]})}function Eh({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 _h({actions:e}){return t.jsx(_b,{compact:!0,authenticated:!1,onToggled:()=>{e?.refreshAuthProviders?.()}})}function bC({actions:e}){return t.jsx(_b,{authenticated:!1,onToggled:()=>{e?.refreshAuthProviders?.()}})}function xC(){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 vC({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 yC=[{pluginId:"fusion-plugin-droid-runtime",slotId:"settings-provider-card",componentPath:"./components/settings-provider-card.js",component:_h},{pluginId:"fusion-plugin-droid-runtime",slotId:"settings-integration-card",componentPath:"./components/settings-integration-card.js",component:_h},{pluginId:"fusion-plugin-droid-runtime",slotId:"onboarding-provider-card",componentPath:"./components/onboarding-provider-card.js",component:bC},{pluginId:"fusion-plugin-droid-runtime",slotId:"onboarding-setup-help",componentPath:"./components/onboarding-setup-help.js",component:xC},{pluginId:"fusion-plugin-droid-runtime",slotId:"post-onboarding-recommendation",componentPath:"./components/post-onboarding-recommendation.js",component:vC}];function wC(e){return yC.find(s=>s.pluginId===e.pluginId&&s.slotId===e.slot.slotId&&s.componentPath===e.slot.componentPath)?.component??null}function kC({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 pa({slotId:e,projectId:n,pluginIds:s,renderPlaceholder:a=!0,actions:r}){const{getSlotsForId:o,loading:l,error:c}=Eb(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(Vo,{level:"page",children:t.jsx(t.Fragment,{children:d.map((u,m)=>{const h=`${u.pluginId}-${u.slot.slotId}-${m}`,f=wC(u);return f?t.jsx(f,{entry:u,actions:r},h):a?t.jsx(kC,{slotId:u.slot.slotId,pluginId:u.pluginId},h):null})})})}function jC(){return typeof window>"u"?"desktop":window.matchMedia("(max-width: 768px)").matches?"mobile":window.matchMedia("(min-width: 769px) and (max-width: 1024px)").matches?"tablet":"desktop"}function oi(){const[e,n]=i.useState(jC);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 Hr(e){return e.replace(/\\/g,"/")}function Gu(e){return e.replace(/[\\/]+$/g,"")}function Ku(e){const n=Hr(Gu(e));return n?n.split("/").filter(Boolean):[]}function Ju(e){const n=Hr(Gu(e));if(!n)return e;const s=n.split("/").filter(Boolean);return s[s.length-1]||n}function Mb(e,n){const s=Ku(e);return s.length===0?Hr(e):s.slice(-2).join("/")}function NC(e){const n=Hr(Gu(e)),s=n.lastIndexOf("/");return s<0?"":n.slice(0,s+1)}function SC(e,n){return!e||e==="."?n:[...Ku(e),n].join("/")}function CC(e){const n=Ku(e);return n.length===0?".":(n.pop(),n.length===0?".":n.join("/"))}function _8(e){const n=Hr(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 Yu=new Map;function Xo(e,n){return`plugin:${e}:${n}`}function Ab(e){const n=/^plugin:([^:]+):(.+)$/u.exec(e);return n?{pluginId:n[1],viewId:n[2]}:null}function wr(e){return Ab(e)!==null}function ll(e,n,s){Yu.set(Xo(e,n),s)}function EC(e,n){return Yu.get(Xo(e,n))??null}function Rb(e,n){return Yu.has(Xo(e,n))}function Xc({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(zr,{}),"Plugin view unavailable"]}),t.jsxs("p",{className:"plugin-dashboard-view-missing-description",children:["No host registration found for ",t.jsx("code",{children:e}),"."]})]})}function _C({viewId:e,context:n}){const s=Ab(e);if(!s)return t.jsx(Xc,{viewId:e});const a=EC(s.pluginId,s.viewId);return a?t.jsx(Vo,{fallback:t.jsx(Xc,{viewId:e}),children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(a,{context:n})})}):t.jsx(Xc,{viewId:e})}const Eo=Xo,MC={activity:Js,bot:Qn,brain:Io,checksquare:Bu,clock:ta,filetext:xa,folder:js,gitbranch:Os,grid3x3:bc,layoutgrid:va,mail:za,map:uk,messagesquare:Zi,monitor:Cr,search:Xi,sparkles:ms,target:Es,workflow:Wl,zap:ls};function AC(e){return(e??"").trim().toLowerCase().replace(/[-_\s]/g,"")}function Ql(e){return MC[AC(e)]??bc}const cl="__fusion:no-branch__",Ib={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function RC({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(gn,{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=Ib[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:Mb(d.path)})]}),u&&t.jsx(ks,{size:14,className:"project-selector-check"})]},d.id)}),t.jsx("div",{className:"project-selector-divider",role:"presentation"}),t.jsx("button",{className:"project-selector-manage",onClick:()=>{s(),o(!1)},"data-testid":"manage-projects-action",children:"Manage Projects"})]})]})})}function Mh({size:e=16}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:t.jsx("path",{d:"M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.203 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.942.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z"})})}function IC({onOpenSettings:e,onOpenGitHubImport:n,onOpenPlanning:s,onResumePlanning:a,activePlanningSessionCount:r=0,onOpenUsage:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:d,mailboxUnreadCount:u=0,mailboxPendingApprovalCount:m=0,chatHasUnreadResponse:h=!1,stashOrphanCount:f=0,onOpenSchedules:p,onOpenGitManager:g,onOpenNodes:w,showNodesButton:v,onOpenWorkflowSteps:b,onOpenScripts:y,onRunScript:S,onToggleTerminal:j,onOpenFiles:C,filesOpen:x,onOpenTodos:N,todosOpen:R,todosEnabled:F,globalPaused:E,enginePaused:_,onToggleGlobalPause:K,onToggleEnginePause:U,view:A="board",onChangeView:T,showSkillsTab:H,showAgentsTab:Q,searchQuery:se="",onSearchChange:O,branchFilter:M="",baseBranchFilter:D="",branchOptions:$=[],baseBranchOptions:k=[],onBranchFilterChange:X,onBaseBranchFilterChange:le,projects:ke=[],currentProject:He,onSelectProject:ye,onViewAllProjects:je,projectId:ne,shellHost:fe={kind:"browser"},mobileNavEnabled:Z,availableNodes:re=[],currentNode:q,onSelectNode:L,isRemote:xe=!1,experimentalFeatures:he,pluginDashboardViews:B=[],shellConnectionControl:pe}){const ze=oi(),ae=ze==="mobile",Te=ae||ze==="tablet",rt=ae&&Z,[Be,ce]=i.useState(!1),[Re,Le]=i.useState(!1),[ct,Ue]=i.useState(!1),[ue,oe]=i.useState(!1),[Ee,ft]=i.useState(!1),[ht,tt]=i.useState(!1),[xt,Me]=i.useState(!1),[Ye,dt]=i.useState(!1),[wt,St]=i.useState(!1),[Fe,J]=i.useState(!1),[me,Ze]=i.useState(!1),[be,gt]=i.useState({}),[$t,Ie]=i.useState(!1),[ge,st]=i.useState(-1),[yt,pt]=i.useState(null),[vt,Ut]=i.useState({}),[Dt,nn]=i.useState(!1),on=i.useRef(null),sn=i.useRef(null),ln=i.useRef(null),xn=i.useRef(null),qt=i.useRef(null),Qt=i.useRef(null),hn=i.useRef(!1),Zt=i.useRef(null),ve=i.useRef(null),Pe=i.useRef(null),Ke=i.useRef(null),at=i.useRef(null),We=i.useRef(null),It=i.useRef(null),Lt=i.useRef(null),Bt=i.useRef(!1),Gt=i.useMemo(()=>re.filter(G=>G.type==="remote"),[re]),bt=Gt.length>0,Ot=i.useMemo(()=>Object.entries(be).sort(([G],[Oe])=>G.localeCompare(Oe)),[be]),en=Ot.length>0,Kt=Ot.length+(en?1:0),Sn=i.useMemo(()=>Object.entries(vt).sort(([G],[Oe])=>G.localeCompare(Oe)),[vt]),dn=i.useMemo(()=>!!(T||he?.researchView||F||he?.insights||H||he?.memoryView||he?.devServerView||!rt||B.some(G=>G.view.placement!=="primary")),[T,he,F,H,rt,B]),Jt=i.useCallback(()=>{const G=window.visualViewport;return G&&G.width>0&&G.height>0?{width:G.width,height:G.height,offsetTop:G.offsetTop,offsetLeft:G.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),tn=i.useCallback(()=>{const G=It.current;if(!G)return;const Oe=G.getBoundingClientRect(),Mt=Lt.current,{width:Xt,height:_n,offsetTop:Pn,offsetLeft:kn}=Jt(),Vn=16,$s=16,vs=6,As=Mt?.offsetWidth||Math.max(Oe.width,260),bn=Math.min(As,Math.max(Xt-Vn*2,160)),Ht=Mt?.offsetHeight||280,On=Math.min(Ht,Math.max(_n-$s*2,160)),Fn=Oe.top-Pn,as=Oe.bottom-Pn,Wn=Oe.right-kn,Rs=_n-as,In=Fn,rs=Rs<On&&In>Rs,Ns=Math.min(Math.max(Wn-bn,Vn),Xt-Vn-bn)+kn,ys=rs?Math.max($s+Pn,Fn-On-vs+Pn):Math.min(as+vs+Pn,_n+Pn-$s-On);pt({top:ys,left:Ns,width:bn})},[Jt]),Ne=i.useCallback((G,Oe)=>{S?.(G,Oe),Ze(!1),st(-1)},[S]),W=i.useCallback(()=>{y?.(),Ze(!1),st(-1)},[y]),Y=i.useCallback(G=>{switch(G.key){case"ArrowDown":G.preventDefault(),Kt>0&&st(Oe=>Oe<Kt-1?Oe+1:0);break;case"ArrowUp":G.preventDefault(),Kt>0&&st(Oe=>Oe>0?Oe-1:Kt-1);break;case"Enter":if(G.preventDefault(),ge>=0)if(ge<Ot.length){const[Oe,Mt]=Ot[ge];Ne(Oe,Mt)}else en&&ge===Ot.length&&W();break;case"Home":G.preventDefault(),Kt>0&&st(0);break;case"End":G.preventDefault(),Kt>0&&st(Kt-1);break}},[W,Ne,ge,Ot,en,Kt]);i.useEffect(()=>{hn.current=Ee},[Ee]),i.useEffect(()=>{Bt.current=me},[me]),i.useEffect(()=>{if(!Ee||!Te)return;let G=!1;return nn(!0),$o(ne).then(Oe=>{G||Ut(Oe)}).catch(()=>{G||Ut({})}).finally(()=>{G||nn(!1)}),()=>{G=!0}},[Ee,Te,ne]),i.useEffect(()=>{if(!me||Te)return;let G=!1;return Ie(!0),$o(ne).then(Oe=>{G||gt(Oe)}).catch(()=>{G||gt({})}).finally(()=>{G||Ie(!1)}),()=>{G=!0}},[me,Te,ne]),i.useEffect(()=>{if(!me)return;const G=Oe=>{We.current&&!We.current.contains(Oe.target)&&Ze(!1)};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[me]),i.useEffect(()=>{if(!me)return;const G=Oe=>{Oe.key==="Escape"&&(Ze(!1),It.current?.focus())};return document.addEventListener("keydown",G),()=>document.removeEventListener("keydown",G)},[me]),i.useEffect(()=>{if(me){st(-1);const G=window.setTimeout(()=>Lt.current?.focus(),0);return()=>window.clearTimeout(G)}pt(null)},[me]),i.useEffect(()=>{if(!me)return;const G=requestAnimationFrame(()=>{tn()});return()=>cancelAnimationFrame(G)},[me,$t,Ot.length,en,tn]),i.useEffect(()=>{if(!me)return;const G=()=>tn();window.addEventListener("resize",G),window.addEventListener("scroll",G,!0);const Oe=window.visualViewport;return Oe&&(Oe.addEventListener("resize",G),Oe.addEventListener("scroll",G)),()=>{window.removeEventListener("resize",G),window.removeEventListener("scroll",G,!0),Oe&&(Oe.removeEventListener("resize",G),Oe.removeEventListener("scroll",G))}},[me,tn]),i.useEffect(()=>{Te&&(Ze(!1),st(-1))},[Te]);const _e=Be||se.length>0,ut=(Re||se.length>0)&&!ct,At=(A==="board"||A==="list")&&!ae&&O&&!ct&&se.length===0,zt=(A==="board"||A==="list")&&!ae&&O,yn=A==="board";i.useEffect(()=>{se===""&&Ue(!1)},[se]),i.useEffect(()=>{if(!ue)return;const G=Oe=>{sn.current&&!sn.current.contains(Oe.target)&&on.current&&!on.current.contains(Oe.target)&&oe(!1)};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[ue]),i.useEffect(()=>{if(!wt)return;const G=Oe=>{xn.current&&!xn.current.contains(Oe.target)&&ln.current&&!ln.current.contains(Oe.target)&&St(!1)};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[wt]),i.useEffect(()=>{if(!ht)return;const G=Oe=>{Zt.current&&!Zt.current.contains(Oe.target)&&tt(!1)};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[ht]),i.useEffect(()=>{const G=Oe=>{if(Oe.key==="Escape"){if(dt(!1),St(!1),hn.current){ft(!1);return}if(Bt.current){Ze(!1),It.current?.focus();return}oe(!1),ce(!1),tt(!1),Me(!1)}};return document.addEventListener("keydown",G),()=>document.removeEventListener("keydown",G)},[]),i.useEffect(()=>{if(!xt)return;const G=Oe=>{ve.current&&!ve.current.contains(Oe.target)&&Me(!1)};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[xt]),i.useEffect(()=>{if(!Fe)return;const G=Oe=>{at.current&&!at.current.contains(Oe.target)&&J(!1)};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[Fe]),i.useEffect(()=>{if(!Fe)return;const G=Oe=>{Oe.key==="Escape"&&J(!1)};return document.addEventListener("keydown",G),()=>document.removeEventListener("keydown",G)},[Fe]),i.useEffect(()=>{if(!Ye)return;const G=Oe=>{Pe.current&&!Pe.current.contains(Oe.target)&&Ke.current&&!Ke.current.contains(Oe.target)&&dt(!1)};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[Ye]);const Zn=i.useCallback(()=>{ce(G=>!G)},[]),vn=i.useCallback(()=>{Le(!0),Ue(!1)},[]),Dn=i.useCallback(()=>{Le(!1),Ue(!0),O&&O("")},[O]),de=i.useCallback(()=>{oe(G=>!G)},[]),nt=i.useCallback(G=>{G&&G(),oe(!1),ft(!1)},[]),ot=i.useCallback(()=>{ce(!1),O&&O("")},[O]),_t=fe.kind==="desktop-shell";return t.jsxs("div",{className:"header-wrapper",children:[t.jsxs("header",{className:"header","data-shell-kind":fe.kind,children:[t.jsxs("div",{className:"header-left",children:[t.jsxs("div",{className:"header-brand",children:[t.jsxs("svg",{className:"header-logo",width:24,height:24,viewBox:"0 0 128 128",fill:"none","aria-label":"Fusion logo",role:"img",children:[t.jsx("circle",{cx:"64",cy:"64",r:"52",stroke:"currentColor",strokeWidth:"8"}),t.jsx("path",{d:"M26 101C44 82 62 64 82 45C90 37 98 30 104 24C96 35 89 47 81 60C70 79 57 95 43 108C38 112 32 108 26 101Z",fill:"currentColor"})]}),t.jsx("h1",{className:"logo",children:"Fusion"})]}),ae&&ke.length>=1&&ye&&t.jsxs("div",{className:"mobile-project-switch",ref:ve,children:[t.jsx("button",{className:`mobile-project-switch-trigger${xt?" mobile-project-switch-trigger--open":""}`,onClick:()=>Me(G=>!G),title:"Switch project","aria-label":"Switch project","aria-expanded":xt,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(gn,{size:14,className:`mobile-project-switch-chevron${xt?" mobile-project-switch-chevron--open":""}`})}),xt&&t.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:ke.map(G=>{const Oe=He?.id===G.id,Mt=Ib[G.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${Oe?" mobile-project-switch-item--current":""}`,onClick:()=>{ye(G),Me(!1)},role:"option","aria-selected":Oe,"data-testid":`mobile-project-switch-item-${G.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:Mt||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:G.name}),t.jsx("span",{className:"mobile-project-switch-path",children:Mb(G.path)})]}),Oe&&t.jsx(ks,{size:14,className:"mobile-project-switch-check"})]},G.id)})})]}),!Te&&ke.length>=1&&je&&t.jsx(RC,{projects:ke,currentProject:He??null,onViewAll:je,onSelectProject:ye}),bt&&t.jsxs("div",{className:`header-node-selector${ae?" header-node-selector--mobile":""}`,ref:ae?void 0:Zt,children:[t.jsx(sC,{node:q??null,showDetails:!ae}),!ae&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${ht?" node-selector-trigger--open":""}`,onClick:()=>tt(G=>!G),title:"Switch node","aria-label":"Switch node","aria-expanded":ht,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(qn,{size:12,className:`node-selector-chevron${ht?" node-selector-chevron--open":""}`})}),ht&&t.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[t.jsxs("button",{className:`node-selector-option${xe?"":" node-selector-option--active"}`,onClick:()=>{L?.(null),tt(!1)},role:"option","aria-selected":!xe,"data-testid":"node-option-local",children:[t.jsx(Ua,{status:"online",compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),Gt.map(G=>t.jsxs("button",{className:`node-selector-option${q?.id===G.id?" node-selector-option--active":""}`,onClick:()=>{L?.(G),tt(!1)},role:"option","aria-selected":q?.id===G.id,"data-testid":`node-option-${G.id}`,children:[t.jsx(Ua,{status:G.status,compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:G.name}),t.jsx("span",{className:"node-selector-option-status",children:G.status})]},G.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[pe,rt&&T&&(A==="board"||A==="list")&&t.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${A==="board"?" active":""}`,onClick:()=>T("board"),title:"Board view","aria-label":"Board view","aria-pressed":A==="board","data-testid":"mobile-view-toggle-board",children:t.jsx(va,{size:16})}),t.jsx("button",{className:`view-toggle-btn${A==="list"?" active":""}`,onClick:()=>T("list"),title:"List view","aria-label":"List view","aria-pressed":A==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(au,{size:16})})]}),O&&ae&&(rt||A==="board"||A==="list")&&!_e&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:Zn,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx(Xi,{size:16})}),At&&t.jsx("button",{className:"btn-icon",onClick:vn,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(Xi,{size:16})}),ae&&rt&&o&&t.jsx("button",{className:"btn-icon",onClick:G=>o(G.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(Js,{size:16})}),!rt&&T&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${A==="board"?" active":""}`,onClick:()=>T("board"),title:"Board view","aria-label":"Board view","aria-pressed":A==="board",children:t.jsx(va,{size:16})}),t.jsx("button",{className:`view-toggle-btn${A==="list"?" active":""}`,onClick:()=>T("list"),title:"List view","aria-label":"List view","aria-pressed":A==="list",children:t.jsx(au,{size:16})}),Q&&t.jsx("button",{className:`view-toggle-btn${A==="agents"?" active":""}`,onClick:()=>T("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":A==="agents",children:t.jsx(Qn,{size:16})}),t.jsx("button",{className:`view-toggle-btn${A==="missions"?" active":""}`,onClick:()=>T("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":A==="missions",children:t.jsx(Es,{size:16})}),t.jsxs("button",{className:`view-toggle-btn${A==="chat"?" active":""}`,onClick:()=>T("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":A==="chat","data-testid":"header-chat-view-btn",children:[t.jsx(Zi,{size:16}),h&&A!=="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${A==="documents"?" active":""}`,onClick:()=>T("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":A==="documents",children:t.jsx(xa,{size:16})}),t.jsxs("button",{className:`view-toggle-btn${A==="mailbox"?" active":""}`,onClick:()=>T("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":A==="mailbox",children:[t.jsx(za,{size:16}),m>0&&A!=="mailbox"&&t.jsx("span",{className:"status-dot status-dot--pending header-chat-unread-dot","aria-label":"Pending approvals"})]}),B.filter(G=>G.view.placement==="primary").sort((G,Oe)=>(G.view.order??Number.MAX_SAFE_INTEGER)-(Oe.view.order??Number.MAX_SAFE_INTEGER)).map(G=>{const Oe=Eo(G.pluginId,G.view.viewId),Mt=Ql(G.view.icon);return t.jsx("button",{className:`view-toggle-btn${A===Oe||A==="graph"&&G.pluginId==="fusion-plugin-dependency-graph"&&G.view.viewId==="graph"?" active":""}`,onClick:()=>T(G.pluginId==="fusion-plugin-dependency-graph"&&G.view.viewId==="graph"?"graph":Oe),title:`${G.view.label} view`,"aria-label":`${G.view.label} view`,"aria-pressed":A===Oe,"data-testid":`view-toggle-plugin-${G.pluginId}-${G.view.viewId}`,children:t.jsx(Mt,{size:16})},`${G.pluginId}:${G.view.viewId}`)}),dn&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:Ke,className:`view-toggle-btn${["research","skills","insights","memory","dev-server","devserver","graph","stash-recovery"].includes(A)||he?.evalsView&&A==="evals"||F&&R||wr(A)?" active":""}`,onClick:()=>dt(G=>!G),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":Ye,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(gn,{size:12})}),Ye&&t.jsxs("div",{ref:Pe,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[he?.evalsView&&t.jsxs("button",{className:`view-toggle-overflow-item${A==="evals"?" active":""}`,onClick:()=>{T("evals"),dt(!1)},role:"menuitem","data-testid":"view-overflow-evals",children:[t.jsx(Es,{size:14}),t.jsx("span",{children:"Evals"})]}),t.jsxs("button",{className:`view-toggle-overflow-item${A==="stash-recovery"?" active":""}`,onClick:()=>{T("stash-recovery"),dt(!1)},role:"menuitem","data-testid":"view-overflow-stash-recovery",children:[t.jsx(Oa,{size:14}),t.jsx("span",{children:"Stash Recovery"}),f>0?t.jsx("span",{className:"btn-badge",children:f}):null]}),he?.researchView&&t.jsxs("button",{className:`view-toggle-overflow-item${A==="research"?" active":""}`,onClick:()=>{T("research"),dt(!1)},role:"menuitem","data-testid":"view-overflow-research",children:[t.jsx(Xi,{size:14}),t.jsx("span",{children:"Research"})]}),he?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${A==="insights"?" active":""}`,onClick:()=>{T("insights"),dt(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(ms,{size:14}),t.jsx("span",{children:"Insights"})]}),H&&t.jsxs("button",{className:`view-toggle-overflow-item${A==="skills"?" active":""}`,onClick:()=>{T("skills"),dt(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(ls,{size:14}),t.jsx("span",{children:"Skills"})]}),he?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${A==="memory"?" active":""}`,onClick:()=>{T("memory"),dt(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(Io,{size:14}),t.jsx("span",{children:"Memory"})]}),he?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${A==="dev-server"||A==="devserver"?" active":""}`,onClick:()=>{T("devserver"),dt(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(Cr,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]}),F&&N&&t.jsxs("button",{className:`view-toggle-overflow-item${R?" active":""}`,onClick:()=>{N(),dt(!1)},role:"menuitem","data-testid":"view-overflow-todos",children:[t.jsx(Bu,{size:14}),t.jsx("span",{children:"Todos"})]}),B.filter(G=>G.view.placement!=="primary").sort((G,Oe)=>(G.view.order??Number.MAX_SAFE_INTEGER)-(Oe.view.order??Number.MAX_SAFE_INTEGER)).map(G=>{const Oe=Eo(G.pluginId,G.view.viewId),Mt=Ql(G.view.icon);return t.jsxs("button",{className:`view-toggle-overflow-item${A===Oe||A==="graph"&&G.pluginId==="fusion-plugin-dependency-graph"&&G.view.viewId==="graph"?" active":""}`,onClick:()=>{T(G.pluginId==="fusion-plugin-dependency-graph"&&G.view.viewId==="graph"?"graph":Oe),dt(!1)},role:"menuitem","data-testid":`view-overflow-plugin-${G.pluginId}-${G.view.viewId}`,children:[t.jsx(Mt,{size:14}),t.jsx("span",{children:G.view.label})]},`${G.pluginId}:${G.view.viewId}`)})]})]})]}),!Te&&o&&t.jsx("button",{className:"btn-icon",onClick:G=>o(G.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"desktop-header-usage-btn",children:t.jsx(Js,{size:16})}),!Te&&c&&t.jsx("button",{className:"btn-icon",onClick:c,title:"System Stats","data-testid":"desktop-header-system-stats-btn",children:t.jsx(Cr,{size:16})}),!Te&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(Oa,{size:16})}),!Te&&!_t&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(Mh,{size:16})}),!Te&&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(Oi,{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})]}),!Te&&t.jsxs("div",{className:"terminal-split-btn",ref:We,children:[t.jsx("button",{className:"btn-icon btn-icon--terminal terminal-split-btn__main",onClick:j,title:"Open Terminal","data-testid":"terminal-toggle-btn",children:t.jsx(ea,{size:16})}),y&&S&&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${me?" btn-icon--active":""}`,onClick:()=>Ze(G=>!G),title:"Scripts","aria-haspopup":"listbox","aria-expanded":me,"aria-label":"Quick scripts","data-testid":"scripts-btn",children:t.jsx(gn,{size:12,className:`quick-scripts-dropdown__trigger-chevron${me?" rotate":""}`})}),me&&t.jsx("div",{ref:Lt,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:Y,"data-testid":"quick-scripts-dropdown",style:yt?{position:"fixed",top:`${yt.top}px`,left:`${yt.left}px`,width:`${yt.width}px`,right:"auto"}:void 0,children:$t?t.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[t.jsx(jt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):Ot.length===0?t.jsxs("div",{className:"quick-scripts-dropdown__empty","data-testid":"quick-scripts-empty",children:[t.jsx("div",{className:"quick-scripts-dropdown__empty-icon",children:t.jsx(ea,{size:16})}),t.jsx("p",{children:"No scripts configured"}),t.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:W,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:Ot.map(([G,Oe],Mt)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${ge===Mt?"highlighted":""}`,onClick:()=>Ne(G,Oe),role:"option","aria-selected":ge===Mt,"data-testid":`quick-script-item-${G}`,children:[t.jsx(os,{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:G}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:Oe,children:Oe.length>50?`${Oe.slice(0,50)}...`:Oe})]})]},G))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${en&&ge===Ot.length?"highlighted":""}`,onClick:W,"data-testid":"quick-scripts-manage",children:[t.jsx(Co,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})]}),!Te&&C&&t.jsx("button",{className:`btn-icon${x?" btn-icon--active":""}`,onClick:C,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(js,{size:16})}),!Te&&g&&t.jsx("button",{className:"btn-icon",onClick:g,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Os,{size:16})}),!Te&&b&&t.jsx("button",{className:"btn-icon",onClick:b,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(Wl,{size:16})}),!Te&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:ln,className:"btn-icon",onClick:()=>St(G=>!G),title:"More actions","aria-label":"More actions","aria-expanded":wt,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(nu,{size:16})}),wt&&t.jsxs("div",{ref:xn,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[w&&v!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{w(),St(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx(To,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{nt(p),St(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(ta,{size:14}),t.jsx("span",{children:"Automation"})]})]})]}),t.jsxs("div",{className:"engine-control-split-btn",ref:at,children:[t.jsx("button",{className:`btn-icon engine-control-split-btn__main${E?" btn-icon--stopped":""}`,onClick:K,title:E?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:E?t.jsx(os,{size:16}):t.jsx($i,{size:16})}),t.jsx("span",{className:"engine-control-split-btn__divider"}),t.jsx("button",{className:`btn-icon engine-control-split-btn__chevron${Fe?" btn-icon--active":""}`,onClick:()=>J(G=>!G),title:"Engine options","aria-haspopup":"menu","aria-expanded":Fe,"data-testid":"engine-control-chevron-btn",children:t.jsx(gn,{size:12})}),Fe&&t.jsx("div",{className:"engine-control-split-btn__menu",role:"menu",children:t.jsxs("button",{className:`engine-control-split-btn__menu-item${_?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{U?.(),J(!1)},role:"menuitem",title:_?"Resume scheduling":"Pause triage",disabled:!!E,"data-testid":"engine-control-pause-triage-btn",children:[_?t.jsx(os,{size:14}):t.jsx(Ci,{size:14}),t.jsx("span",{children:_?"Resume scheduling":"Pause triage"})]})})]}),!Te&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(Co,{size:16})}),t.jsx(pa,{slotId:"header-action",projectId:ne}),Te&&!rt&&t.jsx("button",{ref:on,className:"btn-icon compact-overflow-trigger",onClick:de,title:"More header actions","aria-label":"More header actions","aria-expanded":ue,"aria-haspopup":"menu",children:t.jsx(nu,{size:16})}),Te&&!rt&&ue&&t.jsxs("div",{ref:sn,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[ke.length>=1&&je&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>nt(je),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(bc,{size:16}),t.jsx("span",{children:"Projects"})]}),C&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>nt(C),role:"menuitem","data-testid":"overflow-files-btn",children:[t.jsx(js,{size:16}),t.jsx("span",{children:"Browse Files"})]}),t.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>nt(r>0&&a?a:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx(Oi,{size:16}),r>0&&t.jsx("span",{className:"header-badge header-badge--pulse","data-testid":"overflow-planning-badge",children:r})]}),t.jsx("span",{children:r>0?`Resume planning session (${r})`:"Create a task with AI planning"})]}),g&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>nt(g),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(Os,{size:16}),t.jsx("span",{children:"Git Manager"})]}),w&&v!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>nt(w),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(To,{size:16}),t.jsx("span",{children:"Nodes"})]}),!_t&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>nt(n),role:"menuitem",children:[t.jsx(Mh,{size:16}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("div",{className:"mobile-overflow-group","data-testid":"overflow-terminal-group",children:[t.jsxs("div",{className:"mobile-overflow-split-row",children:[t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-split-primary",onClick:()=>nt(j),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[t.jsx(ea,{size:16}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>ft(G=>!G),role:"menuitem","aria-expanded":Ee,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(qn,{size:14,className:`mobile-overflow-chevron${Ee?" mobile-overflow-chevron--open":""}`})})]}),Ee&&t.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:Dt?t.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[t.jsx(jt,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):Sn.length>0?t.jsxs(t.Fragment,{children:[Sn.map(([G,Oe])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{S&&S(G,Oe),oe(!1),ft(!1)},role:"menuitem","data-testid":`overflow-script-item-${G}`,children:[t.jsx(os,{size:14}),t.jsx("span",{children:G})]},G)),y&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>nt(y),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Si,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):y&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>nt(y),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Si,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>nt(p),role:"menuitem","data-testid":"overflow-schedules-btn",children:[t.jsx(ta,{size:16}),t.jsx("span",{children:"Automation"})]}),l&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>nt(l),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[t.jsx(Oa,{size:16}),t.jsx("span",{children:"View Activity Log"})]}),d&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>nt(d),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(za,{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:G=>nt(()=>o(G.currentTarget.getBoundingClientRect())),role:"menuitem","data-testid":"overflow-usage-btn",children:[t.jsx(Js,{size:16}),t.jsx("span",{children:"View Usage"})]}),b&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>nt(b),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(Wl,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>nt(e),role:"menuitem",children:[t.jsx(Co,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),zt&&ut&&t.jsxs("div",{className:"header-floating-search",children:[t.jsxs("div",{className:"header-search",children:[t.jsx(Xi,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:se,onChange:G=>O(G.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:Dn,"aria-label":"Close search",children:t.jsx(mn,{size:14})})]}),yn&&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:M,onChange:G=>X?.(G.target.value),"data-testid":"working-branch-filter",children:[t.jsx("option",{value:"",children:"All working branches"}),t.jsx("option",{value:cl,children:"No working branch"}),$.map(G=>t.jsx("option",{value:G,children:G},G))]})]}),t.jsxs("label",{className:"header-branch-filter-label",children:[t.jsx("span",{children:"Base branch"}),t.jsxs("select",{className:"header-branch-filter-select",value:D,onChange:G=>le?.(G.target.value),"data-testid":"target-branch-filter",children:[t.jsx("option",{value:"",children:"All base branches"}),t.jsx("option",{value:cl,children:"No base branch"}),k.map(G=>t.jsx("option",{value:G,children:G},G))]})]})]})]}),O&&ae&&_e&&t.jsxs("div",{className:"header-floating-search",children:[t.jsxs("div",{ref:qt,className:"header-search mobile-search-expanded",children:[t.jsx(Xi,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:Qt,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:se,onChange:G=>O(G.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:ot,"aria-label":"Close search",children:t.jsx(mn,{size:14})})]}),yn&&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:M,onChange:G=>X?.(G.target.value),"data-testid":"working-branch-filter-mobile",children:[t.jsx("option",{value:"",children:"All working branches"}),t.jsx("option",{value:cl,children:"No working branch"}),$.map(G=>t.jsx("option",{value:G,children:G},G))]})]}),t.jsxs("label",{className:"header-branch-filter-label",children:[t.jsx("span",{children:"Base branch"}),t.jsxs("select",{className:"header-branch-filter-select",value:D,onChange:G=>le?.(G.target.value),"data-testid":"target-branch-filter-mobile",children:[t.jsx("option",{value:"",children:"All base branches"}),t.jsx("option",{value:cl,children:"No base branch"}),k.map(G=>t.jsx("option",{value:G,children:G},G))]})]})]})]})]})}const TC={themeMode:"dark",colorTheme:"default",dashboardFontScalePct:100,defaultProvider:void 0,defaultModelId:void 0,fallbackProvider:void 0,fallbackModelId:void 0,defaultThinkingLevel:void 0,ntfyEnabled:!1,ntfyTopic:void 0,ntfyBaseUrl:void 0,ntfyAccessToken:void 0,ntfyEvents:["in-review","merged","failed","awaiting-approval","awaiting-user-review","planning-awaiting-input","message:agent-to-user","message:agent-to-agent","message:room","gridlock","fallback-used","memory-dreams-processed"],ntfyDashboardHost:void 0,webhookEnabled:!1,webhookUrl:void 0,webhookFormat:"generic",webhookEvents:[],notificationProviders:[],customProviders:[],defaultProjectId:void 0,setupComplete:void 0,favoriteProviders:void 0,favoriteModels:void 0,openrouterModelSync:!0,opencodeGoModelSync:!0,updateCheckEnabled:!0,fnBinaryCheckEnabled:!0,updateCheckFrequency:"daily",autoReloadOnVersionChange:!0,showGitHubStarButton:!0,githubTrackingDefaultRepo:void 0,modelOnboardingComplete:void 0,useClaudeCli:void 0,useDroidCli:void 0,useLlamaCpp:void 0,executionGlobalProvider:void 0,executionGlobalModelId:void 0,planningGlobalProvider:void 0,planningGlobalModelId:void 0,validatorGlobalProvider:void 0,validatorGlobalModelId:void 0,titleSummarizerGlobalProvider:void 0,titleSummarizerGlobalModelId:void 0,daemonToken:void 0,daemonPort:4040,daemonHost:"127.0.0.1",settingsSyncEnabled:!1,settingsSyncAuth:!1,settingsSyncInterval:9e5,settingsSyncConflictResolution:"last-write-wins",dashboardCurrentNodeId:void 0,dashboardCurrentProjectIdByNode:void 0,vitestAutoKillEnabled:!0,vitestKillThresholdPct:90,persistAgentToolOutput:!0,persistAgentThinkingLog:!1,researchGlobalDefaults:{searchProvider:void 0,synthesisProvider:void 0,synthesisModelId:void 0,enabledSources:{webSearch:!0,pageFetch:!0,github:!1,localDocs:!0,llmSynthesis:!0},maxSourcesPerRun:20,defaultExportFormat:"markdown"},researchGlobalEnabled:!0,researchGlobalMaxConcurrentRuns:3,researchGlobalDefaultTimeout:3e5,researchGlobalMaxSourcesPerRun:20,researchGlobalMaxSynthesisRounds:2,researchGlobalWebSearchProvider:"builtin",researchGlobalSearxngUrl:void 0,researchGlobalBraveApiKey:void 0,researchGlobalGoogleSearchApiKey:void 0,researchGlobalGoogleSearchCx:void 0,researchGlobalTavilyApiKey:void 0,researchGlobalGitHubEnabled:!1,researchGlobalLocalDocsEnabled:!0,researchGlobalMaxSearchResults:10,researchGlobalFetchTimeoutMs:3e4,researchGlobalUserAgent:"FusionResearchBot/1.0",remoteAccess:{activeProvider:null,providers:{tailscale:{enabled:!1,hostname:"",targetPort:0,acceptRoutes:!1},cloudflare:{enabled:!1,quickTunnel:!0,tunnelName:"",tunnelToken:null,ingressUrl:""}},tokenStrategy:{persistent:{enabled:!0,token:null},shortLived:{enabled:!1,ttlMs:9e5,maxTtlMs:864e5}},lifecycle:{rememberLastRunning:!1,wasRunningOnShutdown:!1,lastRunningProvider:null}},experimentalFeatures:{}},PC={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",directMergeCommitStrategy:"auto",requirePrApproval:!1,pushAfterMerge:!1,pushRemote:"origin",unavailableNodePolicy:"block",defaultNodeId:void 0,worktreeInitCommand:void 0,testCommand:void 0,buildCommand:void 0,recycleWorktrees:!1,executorAllowSiblingBranchRename:!1,worktreeNaming:"random",taskPrefix:"FN",includeTaskIdInCommit:!0,commitAuthorEnabled:!0,commitAuthorName:"Fusion",commitAuthorEmail:"noreply@runfusion.ai",planningProvider:void 0,planningModelId:void 0,planningFallbackProvider:void 0,planningFallbackModelId:void 0,defaultProviderOverride:void 0,defaultModelIdOverride:void 0,executionProvider:void 0,executionModelId:void 0,validatorProvider:void 0,validatorModelId:void 0,validatorFallbackProvider:void 0,validatorFallbackModelId:void 0,modelPresets:[],autoSelectModelPreset:!1,completionDocumentationMode:"off",defaultPresetBySize:{},autoResolveConflicts:!0,smartConflictResolution:!0,mergerAutostashMaxAgeHours:24,worktreeRebaseBeforeMerge:!0,worktreeRebaseRemote:"",worktreeRebaseLocalBase:!0,mergeConflictStrategy:"smart-prefer-main",mergeDiffVolumeMinLines:void 0,mergeDiffVolumeThreshold:void 0,mergeDiffVolumeAllowlist:void 0,mergeStrategyOverlapBehavior:"flip-to-prefer-branch",workflowStepTimeoutMs:36e4,workflowRevisionForkOnScopeMismatch:!0,strictScopeEnforcement:!1,buildRetryCount:0,verificationFixRetries:3,buildTimeoutMs:3e5,requirePlanApproval:!1,agentProvisioning:{},specStalenessEnabled:!1,specStalenessMaxAgeMs:360*60*1e3,taskStuckTimeoutMs:6e5,staleHighFanoutBlockerAgeThresholdMs:7200*1e3,aiSessionTtlMs:10080*60*1e3,aiSessionCleanupIntervalMs:3600*1e3,autoUnpauseEnabled:!0,autoUnpauseBaseDelayMs:3e5,autoUnpauseMaxDelayMs:36e5,maxStuckKills:6,preserveProgressOnStuckRequeue:!0,maxPostReviewFixes:1,maxSpawnedAgentsPerParent:5,maxSpawnedAgentsGlobal:20,maintenanceIntervalMs:3e5,autoArchiveDoneTasksEnabled:!0,autoArchiveDoneAfterMs:2880*60*1e3,archiveAgentLogMode:"compact",autoUpdatePrStatus:!1,githubCommentOnDone:!1,githubCommentTemplate:void 0,githubTrackingEnabledByDefault:!1,githubTrackingDefaultRepo:void 0,githubAuthMode:"gh-cli",githubAuthToken:void 0,autoBackupEnabled:!1,autoBackupSchedule:"0 2 * * *",autoBackupRetention:7,autoBackupDir:".fusion/backups",memoryBackupEnabled:!1,memoryBackupSchedule:"0 3 * * *",memoryBackupRetention:14,memoryBackupDir:".fusion/backups/memory",memoryBackupScope:"all",autoSummarizeTitles:!1,useAiMergeCommitSummary:!0,titleSummarizerProvider:void 0,titleSummarizerModelId:void 0,titleSummarizerFallbackProvider:void 0,titleSummarizerFallbackModelId:void 0,scripts:void 0,setupScript:void 0,insightExtractionEnabled:!1,insightExtractionSchedule:"0 2 * * *",insightExtractionMinIntervalMs:864e5,taskEvaluationEnabled:!1,taskEvaluationSchedule:"0 5 * * *",taskEvaluationProvider:void 0,taskEvaluationModelId:void 0,taskEvaluationFollowUpPolicy:"off",taskEvaluationRetention:void 0,memoryEnabled:!0,memoryBackendType:"qmd",memoryAutoSummarizeEnabled:!1,memoryAutoSummarizeThresholdChars:5e4,memoryAutoSummarizeSchedule:"0 3 * * *",memoryDreamsEnabled:!1,memoryDreamsSchedule:"0 4 * * *",tokenCap:void 0,runStepsInNewSessions:!1,maxParallelSteps:2,missionStaleThresholdMs:6e5,missionMaxTaskRetries:3,missionHealthCheckIntervalMs:3e5,agentPrompts:void 0,promptOverrides:void 0,reflectionEnabled:!1,reflectionIntervalMs:36e5,reflectionAfterTask:!0,reviewHandoffPolicy:"disabled",showQuickChatFAB:!1,researchSettings:{enabled:!0,searchProvider:void 0,synthesisProvider:void 0,synthesisModelId:void 0,enabledSources:{webSearch:!0,pageFetch:!0,github:!1,localDocs:!0,llmSynthesis:!0},limits:{maxConcurrentRuns:3,maxSourcesPerRun:20,maxDurationMs:3e5,requestTimeoutMs:3e4}},evalSettings:{enabled:!1,intervalMs:864e5,evaluatorProvider:void 0,evaluatorModelId:void 0,followUpPolicy:"suggest-only",retentionDays:30},researchEnabled:!0,researchMaxConcurrentRuns:3,researchDefaultTimeout:3e5,researchMaxSourcesPerRun:20,researchMaxSynthesisRounds:2},$C=Object.freeze(Object.keys(TC)),DC=Object.freeze(Object.keys(PC));function M8(e){return $C.includes(e)}function A8(e){return DC.includes(e)}function Se(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function LC(e){return!!(e?.provider&&e?.modelId)}function ya(...e){for(const n of e)if(LC(n))return{provider:n.provider,modelId:n.modelId};return{}}function Nc(e){return ya({provider:e?.defaultProviderOverride,modelId:e?.defaultModelIdOverride},{provider:e?.defaultProvider,modelId:e?.defaultModelId})}function OC(e){return ya({provider:e?.executionProvider,modelId:e?.executionModelId},{provider:e?.executionGlobalProvider,modelId:e?.executionGlobalModelId},Nc(e))}function FC(e){return ya({provider:e?.planningProvider,modelId:e?.planningModelId},{provider:e?.planningGlobalProvider,modelId:e?.planningGlobalModelId},Nc(e))}function zC(e){return ya({provider:e?.validatorProvider,modelId:e?.validatorModelId},{provider:e?.validatorGlobalProvider,modelId:e?.validatorGlobalModelId},Nc(e))}function R8(e){return ya({provider:e?.titleSummarizerProvider,modelId:e?.titleSummarizerModelId},{provider:e?.titleSummarizerGlobalProvider,modelId:e?.titleSummarizerGlobalModelId},{provider:e?.planningProvider,modelId:e?.planningModelId},Nc(e))}function Tb(e,n){return ya({provider:e.modelProvider,modelId:e.modelId},OC(n))}function Pb(e,n){return ya({provider:e.validatorModelProvider,modelId:e.validatorModelId},zC(n))}function $b(e,n){return ya({provider:e.planningModelProvider,modelId:e.planningModelId},FC(n))}const I8=["off","minimal","low","medium","high"],ha=["triage","todo","in-progress","in-review","done","archived"],Xl="triage";function Qu(e){return typeof e=="string"&&ha.includes(e)}function Db(e,n=Xl){return Qu(e)?e:n}const wa=["low","normal","high","urgent"],Ps="normal",Xu=5,Lb=7200*1e3,BC=["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"],Sc=/^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/,hs={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},UC={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"},mu={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 HC(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 Ah(e){return e==="urgent"?3:e==="high"?2:e==="low"?0:1}function Rh(e,n){return Ah(n)-Ah(e)}function Zc(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 Ih(e){const n=e.columnMovedAt??e.updatedAt??e.createdAt,s=Date.parse(n);return Number.isFinite(s)?s:0}function Th(e){return e==="merging"||e==="merging-pr"||e==="merging-fix"}function Ob(e,n){return n==="todo"?[...e].sort((s,a)=>{const r=Rh(s.priority,a.priority);return r!==0?r:s.createdAt!==a.createdAt?s.createdAt.localeCompare(a.createdAt):Zc(s.id,a.id)}):[...e].sort((s,a)=>{if(n==="done"){const o=Ih(a)-Ih(s);return o!==0?o:Zc(s.id,a.id)}if(n==="in-review"){const o=Th(s.status),l=Th(a.status);if(o!==l)return o?-1:1}const r=Rh(s.priority,a.priority);return r!==0?r:Zc(s.id,a.id)})}function qC(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 VC({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 Fb=i.createContext(null);function WC({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 ga.createElement(Fb.Provider,{value:d},e,ga.createElement(VC,{isOpen:c!==null,options:c?.options??null,onConfirm:()=>l(!0),onCancel:()=>l(!1)}))}function li(){const e=i.useContext(Fb);return e||{confirm:async n=>!1}}function GC(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 zb({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(ii,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("a",{className:`card-github-badge ${GC(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,href:n.url,target:"_blank",rel:"noopener noreferrer",children:[t.jsx(fc,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function dl(e,n){return`${e??"default"}:${n}`}class KC{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=dl(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const a=dl(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=dl(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(Fi(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=dl(this.projectId,l.taskId),d=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:Ph(l,"prInfo")?l.prInfo??null:d?.prInfo,issueInfo:Ph(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 Ta=new KC;let JC=0;function Ph(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function Bb(e){const n=i.useRef(null);n.current===null&&(n.current=`badge-hook-${JC++}`);const s=i.useSyncExternalStore(o=>Ta.subscribe(o),()=>Ta.getSnapshot(),()=>Ta.getSnapshot()),a=i.useCallback(o=>{Ta.subscribeTask(n.current,o)},[]),r=i.useCallback(o=>{Ta.unsubscribeTask(n.current,o)},[]);return i.useEffect(()=>{Ta.setProjectId(e??null)},[e]),i.useEffect(()=>()=>{Ta.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:a,unsubscribeFromBadge:r}}function Zl(e,n,s,a){return e===void 0||!n?s:!a||n>=a?e??void 0:s}function YC({taskId:e,prInfo:n,issueInfo:s,updatedAt:a,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:d}=Bb(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=Zl(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??a),f=Zl(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??a);return!h&&!f?null:t.jsx(zb,{prInfo:h,issueInfo:f})}const QC=i.memo(YC);QC.displayName="TaskCardBadge";const hi={data:new Map,pendingPromise:null,lastFetchTime:null},XC=5e3;function zl(e,n){return n?`${n}::${e}`:e}function ZC(e,n){const s=hi.data.get(zl(e,n));if(!(!s||Date.now()-s.timestamp>XC))return s}function eE(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 UN(c,e)}catch(h){u=h instanceof Error?h:new Error(String(h));const f=Se(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=hi.data.get(zl(f,e));return p&&p.timestamp>u})&&hi.lastFetchTime&&hi.lastFetchTime>u)return;if(a.current&&(clearTimeout(a.current),a.current=null),hi.pendingPromise){s(!0);try{await hi.pendingPromise}finally{s(!1)}return}s(!0);const h=r(c);hi.pendingPromise=h;try{const f=await h,p=Date.now();for(const[g,w]of Object.entries(f))hi.data.set(zl(g,e),{result:w,timestamp:p});hi.lastFetchTime=p}catch{}finally{hi.pendingPromise=null,s(!1)}},[r,e]),l=i.useCallback(c=>hi.data.get(zl(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:hi.lastFetchTime,getBatchData:l}}const hu=new Map,tE=3e4;function Ub(e,n,s,a){return`${e}:${n??""}:${s??""}:${a??""}`}function nE(e,n,s,a){const r=Ub(e,n,s,a),o=hu.get(r);return o?Date.now()>o.expiresAt?(hu.delete(r),null):o.stats:null}function sE(e,n,s,a,r){const o=Ub(e,n,s,a);hu.set(o,{stats:r,expiresAt:Date.now()+tE})}function iE(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 w=g?l:void 0,v=c!==void 0?String(c):void 0;let b=!1;async function y(j=!1){if(!j){const C=nE(e,a,w,v);if(C){b||(m(C),f(!1));return}}f(!0);try{const C=await yb(e,w,a);b||(m(C.stats),sE(e,a,w,v,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 aE=new Set(["failed","stuck-killed"]);function ec(e,n,s){if(e.column!=="in-progress"||e.status&&aE.has(e.status)||!n||n<=0)return!1;const a=new Date(e.updatedAt).getTime();return(s??Date.now())-a>n}function rE(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function oE(e){return e==="done"||e==="skipped"}function lE(e,n,s){const a=s?.get(e)?.trim();if(a)return a;const r=n?.workflowStepName?.trim();return r||e}function Hb(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:lE(d,u,n),status:u?rE(u.status):"pending",source:"workflow",phase:u?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(d=>oE(d.status)).length;return{total:l,completed:c,items:o}}function cE(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 qb(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:cE(n)}})}function Vb(e){if(!e||e.length===0)return null;let n=0,s=0;for(const a of qb(e))typeof a.durationMs=="number"&&(n+=a.durationMs,s+=1);return s>0?n:null}function Ha(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function Wb(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=Ha(r.startedAt);if(o==null)continue;let l;if(r.completedAt){const c=Ha(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 Gb(e,n,s){const a=Ha(e);if(a==null)return null;const r=Ha(n),o=r!=null&&r>=a?r:s;return Math.max(0,o-a)}function Zu(e){if(!(e instanceof Error))return null;const n=e.details;if(n?.code==="TASK_HAS_DEPENDENTS"&&Array.isArray(n.dependentIds))return{dependentIds:n.dependentIds.filter(a=>typeof a=="string")};const s=e.message.match(/[A-Z]+-\d+/g)??[];return s.length>1?{dependentIds:[...new Set(s.slice(1))]}:null}const pu=new Map;async function dE(e,n){const s=pu.get(e);if(s)return s;try{const a=await wb(e,n);return pu.set(e,a.title),a.title}catch{return e}}const $h=12;function uE(e){return e.length<=$h?e:e.slice(0,$h-3)+"..."}const fu=new Map;async function mE(e,n){const s=fu.get(e);if(s)return s;try{const a=await uu(e,n);return fu.set(e,a.name),a.name}catch{return e}}function hE(e){return typeof e=="string"&&wa.includes(e)?e:Ps}function pE(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}function Kb(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 fE(e){return e.sourceType==="agent_heartbeat"||e.sourceType==="automation"||!!Kb(e)}const gE=new Set(["triage","todo"]),Dh=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]),Lh=new Set(["merging","merging-pr","merging-fix"]),bE={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},xE=new Set(["in-progress","in-review","done"]),vE=3e4;function yE(e){return e==="merging-fix"?"Merging fixes…":e}function wE(e){const n=Ha(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function Oh(e,n){const s=Ha(e.columnMovedAt??e.updatedAt);return s==null?null:Math.max(0,n-s)}function vo(e,n){return Gb(e.executionStartedAt,e.executionCompletedAt,n)}function kE(e){return e.column==="done"?wE(e):null}function Jb(e,n){const s=Ha(e.updatedAt);return s==null?null:Math.max(0,n-s)}function jE(e,n){const s=vo(e,n);if(s!=null)return s;const a=Jb(e,n),r=yo(e,n);return r!=null?r+(a??0):a}function yo(e,n){if(typeof e.timedExecutionMs=="number")return e.timedExecutionMs;const s=Vb(e.log),a=Wb(e.workflowStepResults,n);return s==null&&a==null?null:(s??0)+(a??0)}function Fh(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 zh(e){if(!e)return null;const n=e.trim();return n.length>0?n:null}function NE(e){const n=zh(e.branch),s=zh(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 Bh(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 Uh(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 SE(e,n){return e.length!==n.length?!1:e.every((s,a)=>s.name===n[a]?.name&&s.status===n[a]?.status)}function ed(e,n){return e.length!==n.length?!1:e.every((s,a)=>s===n[a])}function CE(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>s===n[a])}function EE(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function _E(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 ME(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 AE(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 RE(e,n){const s=e.task,a=n.task;return e.queued===n.queued&&e.projectId===n.projectId&&e.globalPaused===n.globalPaused&&e.taskStuckTimeoutMs===n.taskStuckTimeoutMs&&e.onOpenDetail===n.onOpenDetail&&e.addToast===n.addToast&&e.onUpdateTask===n.onUpdateTask&&e.onArchiveTask===n.onArchiveTask&&e.onUnarchiveTask===n.onUnarchiveTask&&e.onDeleteTask===n.onDeleteTask&&e.onRetryTask===n.onRetryTask&&e.onOpenDetailWithTab===n.onOpenDetailWithTab&&e.onOpenMission===n.onOpenMission&&e.onMoveTask===n.onMoveTask&&e.workflowStepNameLookup===n.workflowStepNameLookup&&e.disableDrag===n.disableDrag&&e.fanout?.totalCount===n.fanout?.totalCount&&e.fanout?.activeTodoCount===n.fanout?.activeTodoCount&&e.fanout?.isHighFanout===n.fanout?.isHighFanout&&e.fanout?.escalation?.blockingAgeMs===n.fanout?.escalation?.blockingAgeMs&&ed(e.fanout?.dependentIds??[],n.fanout?.dependentIds??[])&&ed(e.fanout?.staleBlockedByDependentIds??[],n.fanout?.staleBlockedByDependentIds??[])&&s.id===a.id&&s.title===a.title&&s.description===a.description&&s.column===a.column&&s.columnMovedAt===a.columnMovedAt&&s.timedExecutionMs===a.timedExecutionMs&&s.updatedAt===a.updatedAt&&s.createdAt===a.createdAt&&s.status===a.status&&s.priority===a.priority&&s.executionMode===a.executionMode&&s.paused===a.paused&&s.error===a.error&&s.size===a.size&&s.blockedBy===a.blockedBy&&s.worktree===a.worktree&&s.branch===a.branch&&s.baseBranch===a.baseBranch&&s.breakIntoSubtasks===a.breakIntoSubtasks&&s.currentStep===a.currentStep&&s.modelProvider===a.modelProvider&&s.modelId===a.modelId&&s.validatorModelProvider===a.validatorModelProvider&&s.validatorModelId===a.validatorModelId&&s.planningModelProvider===a.planningModelProvider&&s.planningModelId===a.planningModelId&&s.reviewLevel===a.reviewLevel&&s.missionId===a.missionId&&s.assignedAgentId===a.assignedAgentId&&s.mergeRetries===a.mergeRetries&&s.sourceType===a.sourceType&&s.sourceAgentId===a.sourceAgentId&&s.sourceMetadata?.issueUrl===a.sourceMetadata?.issueUrl&&s.sourceMetadata?.agentName===a.sourceMetadata?.agentName&&ME(s.attachments,a.attachments)&&AE(s.comments,a.comments)&&ed(s.dependencies,a.dependencies)&&SE(s.steps,a.steps)&&CE(s.enabledWorkflowSteps,a.enabledWorkflowSteps)&&_E(s.workflowStepResults,a.workflowStepResults)&&Uh(s.prInfo,a.prInfo)&&Uh(s.issueInfo,a.issueInfo)}function IE({task:e,projectId:n,queued:s,onOpenDetail:a,addToast:r,globalPaused:o,onUpdateTask:l,onArchiveTask:c,onUnarchiveTask:d,onDeleteTask:u,onRetryTask:m,onOpenDetailWithTab:h,taskStuckTimeoutMs:f,onOpenMission:p,onMoveTask:g,lastFetchTimeMs:w,workflowStepNameLookup:v,disableDrag:b,fanout:y}){const[S,j]=i.useState(!1),[C,x]=i.useState(!1),[N,R]=i.useState(!1),[F,E]=i.useState(e.description||""),[_,K]=i.useState(!1),[U,A]=i.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(Ne=>Ne.status==="done"||Ne.status==="skipped")),[T,H]=i.useState(null),[Q,se]=i.useState(null),[O,M]=i.useState(!1),[D,$]=i.useState(!1),[k,X]=i.useState(()=>Date.now()),le=i.useRef(null),ke=i.useRef(!1),He=i.useRef(null),ye=i.useRef(null),[je,ne]=i.useState(!1),{badgeUpdates:fe,subscribeToBadge:Z,unsubscribeFromBadge:re}=Bb(n),{confirm:q}=li(),L=i.useRef(null),xe=i.useRef(!1),he=i.useCallback(Ne=>Ne instanceof Element?!!Ne.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);i.useEffect(()=>{E(e.description||"")},[e.id,e.description]),i.useEffect(()=>{if(!O)return;const Ne=W=>{ye.current&&!ye.current.contains(W.target)&&M(!1)};return document.addEventListener("click",Ne),()=>document.removeEventListener("click",Ne)},[O]),i.useEffect(()=>{if(!e.missionId){H(null);return}const Ne=pu.get(e.missionId);if(Ne){H(Ne);return}let W=!1;return dE(e.missionId,n).then(Y=>{W||H(Y)}),()=>{W=!0}},[e.missionId,n]),i.useEffect(()=>{if(!e.assignedAgentId){se(null);return}const Ne=fu.get(e.assignedAgentId);if(Ne){se(Ne);return}se(null);let W=!1;return mE(e.assignedAgentId,n).then(Y=>{W||se(Y)}),()=>{W=!0}},[e.assignedAgentId,n]),i.useEffect(()=>{if(N&&le.current){const Ne=le.current;Ne.focus(),Ne.style.height="auto",Ne.style.height=Ne.scrollHeight+"px"}},[N]),i.useEffect(()=>{if(typeof IntersectionObserver>"u"){ne(!0);return}const Ne=He.current;if(!Ne)return;const W=new IntersectionObserver(([Y])=>{ne(Y?.isIntersecting??!0)},{rootMargin:"200px"});return W.observe(Ne),()=>W.disconnect()},[N,e.id]);const B=i.useCallback(Ne=>{Ne.dataTransfer.setData("text/plain",e.id),Ne.dataTransfer.effectAllowed="move",j(!0)},[e.id]),pe=i.useCallback(()=>{j(!1)},[]),ze=i.useCallback(Ne=>Ne.dataTransfer.types.includes("Files"),[]),ae=i.useCallback(Ne=>{ze(Ne)&&(Ne.preventDefault(),Ne.stopPropagation(),Ne.dataTransfer.dropEffect="copy",x(!0))},[ze]),Ve=i.useCallback(Ne=>{ze(Ne)&&(Ne.preventDefault(),Ne.stopPropagation(),x(!1))},[ze]),Te=i.useCallback(async Ne=>{if(!ze(Ne))return;Ne.preventDefault(),Ne.stopPropagation(),x(!1);const W=Array.from(Ne.dataTransfer.files);for(const Y of W)try{await jc(e.id,Y,n),r(`Attached ${Y.name} to ${e.id}`,"success")}catch(_e){r(`Failed to attach ${Y.name}: ${Se(_e)}`,"error")}},[e.id,ze,r]),rt=i.useCallback(()=>{N||a(e)},[e,a,N]),Be=i.useCallback(Ne=>{if(ke.current){ke.current=!1;return}he(Ne.target)||rt()},[rt,he]),ce=i.useCallback(Ne=>{const W=Ne.touches[0];W&&(L.current={x:W.clientX,y:W.clientY,time:Date.now()},xe.current=!1)},[]),Re=i.useCallback(Ne=>{if(!L.current)return;const W=Ne.touches[0];if(!W)return;const Y=Math.abs(W.clientX-L.current.x),_e=Math.abs(W.clientY-L.current.y);(Y>Hh||_e>Hh)&&(xe.current=!0)},[]),Le=i.useCallback(Ne=>{if(he(Ne.target)||!L.current)return;const Y=Date.now()-L.current.time<TE,_e=!xe.current;Y&&_e&&(ke.current=!0,rt()),L.current=null,xe.current=!1},[rt,he]),ct=i.useCallback(async(Ne,W)=>{Ne.stopPropagation();try{const Y=await Ba(W,n);a(Y)}catch{r(`Failed to load dependency ${W}`,"error")}},[a,r]),Ue=e.status==="failed",ue=e.paused===!0,oe=!!(e.paused&&e.pausedByAgentId),Ee=hE(e.priority),ft=Ee!==Ps,ht=ec(e,f,w),tt=e.column==="triage"&&e.status==="awaiting-approval",xt=e.column==="archived",Me=!o&&!s&&!Ue&&!ue&&!ht&&!tt&&(e.column==="in-progress"||Dh.has(e.status)),Ye=!b&&!s&&!ue&&!N&&!xt,dt=gE.has(e.column)&&!Me&&!ue&&!s&&l,wt=e.githubTracking?.issue,St=!!wt,Fe=!!(e.prInfo||e.issueInfo),J=e.sourceType==="github_import",me=St&&!J&&!(e.issueInfo&&e.issueInfo.number===wt?.number),Ze=i.useMemo(()=>NE(e),[e.id,e.branch,e.baseBranch]),be=!!(Ze.branch||Ze.baseBranch),gt=EE(e.sourceMetadata),$t=fE(e),Ie=Kb(e),ge=Ie?`Created by agent: ${Ie}`:"Created by agent",st=!!(e.assignedAgentId&&Q===null),yt=i.useMemo(()=>{const Ne=[];return e.modelProvider&&Ne.push(e.modelProvider),e.validatorModelProvider&&!Ne.includes(e.validatorModelProvider)&&Ne.push(e.validatorModelProvider),e.planningModelProvider&&!Ne.includes(e.planningModelProvider)&&Ne.push(e.planningModelProvider),Ne},[e.modelProvider,e.validatorModelProvider,e.planningModelProvider]),pt=i.useMemo(()=>Hb(e,v),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,v]),vt=pt.total>0&&(e.status==="executing"||e.column==="in-progress");i.useEffect(()=>{if(e.column!=="in-progress"&&e.column!=="in-review")return;const Ne=e.status!=null&&Lh.has(e.status);if(e.column==="in-progress"){const Y=vo(e,Date.now()),_e=Oh(e,Date.now()),ut=yo(e,Date.now());if(Y==null&&_e==null&&ut==null)return}if(!Ne&&e.column==="in-review"){const Y=vo(e,Date.now()),_e=yo(e,Date.now());if(Y==null&&_e==null)return}X(Date.now());const W=window.setInterval(()=>{X(Date.now())},vE);return()=>window.clearInterval(W)},[e.column,e.status,e.columnMovedAt,e.updatedAt,e.workflowStepResults,e.timedExecutionMs,e.executionStartedAt,e.executionCompletedAt]);const Ut=i.useMemo(()=>{if(!xE.has(e.column))return null;if(e.status!=null&&Lh.has(e.status)){const At=jE(e,k);if(At!=null){const zt=Bh(At);if(zt){const yn=Jb(e,k),Zn=yn==null?null:Fh(yn),vn=Zn?`Execution time ${zt}. Merge phase ${Zn}`:`Execution time ${zt}. Merging`;return{label:zt,title:vn,ariaLabel:vn}}}}if(e.column==="in-progress"){const At=vo(e,k)??Oh(e,k)??yo(e,k);if(At==null)return null;const zt=Fh(At);return zt?{label:zt,title:`In progress ${zt}`,ariaLabel:`In progress ${zt}`}:null}const W=vo(e,k)??yo(e,k);if(W==null)return null;const Y=Bh(W);if(!Y)return null;const _e=kE(e);if(_e==null)return{label:Y,title:`Execution time ${Y}`,ariaLabel:`Execution time ${Y}`};const ut=new Date(_e).toLocaleString();return{label:Y,title:`Execution time ${Y}. Completed ${ut}`,ariaLabel:`Execution time ${Y}. Completed ${ut}`}},[e.column,e.status,e.columnMovedAt,e.timedExecutionMs,e.updatedAt,e.workflowStepResults,e.log,e.executionStartedAt,e.executionCompletedAt,k]);i.useEffect(()=>{if(!Fe||!je){re(e.id);return}return Z(e.id),()=>{re(e.id)}},[Fe,je,Z,e.id,re]);const Dt=fe.get(`${n??"default"}:${e.id}`),nn=e.column==="in-progress"||e.column==="in-review",on=i.useMemo(()=>e.steps.map(Ne=>`${Ne.name}:${Ne.status}`).join("|"),[e.steps]),{stats:sn}=iE(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:je,worktree:e.worktree,stepVersion:nn?on:void 0,pollIntervalMs:nn?3e4:void 0}),ln=i.useMemo(()=>ZC(e.id,n),[e.id,n]),xn=i.useMemo(()=>{const Ne=Dt?.prInfo,W=Dt?.timestamp,Y=ln?.result?.prInfo,_e=ln?.timestamp?new Date(ln.timestamp).toISOString():void 0,ut=e.prInfo,At=e.prInfo?.lastCheckedAt??e.updatedAt;let zt=Zl(Ne,W,ut,At);const yn=W&&W>=At?W:At;return Y&&_e&&(!yn||_e>yn)&&(zt=Y),zt},[Dt,ln,e.prInfo,e.updatedAt]),qt=i.useMemo(()=>{const Ne=Dt?.issueInfo,W=Dt?.timestamp,Y=ln?.result?.issueInfo,_e=ln?.timestamp?new Date(ln.timestamp).toISOString():void 0,ut=e.issueInfo,At=e.issueInfo?.lastCheckedAt??e.updatedAt;let zt=Zl(Ne,W,ut,At);const yn=W&&W>=At?W:At;return Y&&_e&&(!yn||_e>yn)&&(zt=Y),zt},[Dt,ln,e.issueInfo,e.updatedAt]),Qt=i.useCallback(Ne=>{Ne?.stopPropagation(),!(!dt||_)&&(R(!0),E(e.description||""))},[dt,_,e.description]),hn=i.useCallback(()=>{R(!1),E(e.description||"")},[e.description]),Zt=i.useCallback(()=>F!==(e.description||""),[F,e.description]),ve=i.useCallback(async()=>{if(!(!l||_)){if(!Zt()){hn();return}K(!0);try{await l(e.id,{description:F.trim()||void 0}),r(`Updated ${e.id}`,"success"),R(!1)}catch(Ne){r(`Failed to update ${e.id}: ${Se(Ne)}`,"error")}finally{K(!1)}}},[l,e.id,F,_,Zt,hn,r]),Pe=i.useCallback(Ne=>{Ne.key==="Enter"&&!Ne.shiftKey?(Ne.preventDefault(),ve()):Ne.key==="Escape"&&(Ne.preventDefault(),hn())},[ve,hn]),Ke=i.useCallback(()=>{setTimeout(()=>{const Ne=document.activeElement;Ne===le.current||Ne?.closest(".card-editing-content")||(Zt()?ve():hn())},0)},[Zt,ve,hn]),at=i.useCallback(Ne=>{dt&&(Ne.stopPropagation(),Qt(Ne))},[dt,Qt]),We=i.useCallback(Ne=>{Ne.stopPropagation(),Qt(Ne)},[Qt]),It=i.useCallback(Ne=>{E(Ne.target.value);const W=Ne.target;W.style.height="auto",W.style.height=W.scrollHeight+"px"},[]),Lt=i.useCallback(Ne=>{Ne.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch(W=>{r(`Failed to archive ${e.id}: ${Se(W)}`,"error")})},[r,c,e.id]),Bt=i.useCallback(Ne=>{Ne.stopPropagation(),d&&d(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch(W=>{r(`Failed to unarchive ${e.id}: ${Se(W)}`,"error")})},[r,d,e.id]),Gt=i.useCallback(async Ne=>{if(Ne.stopPropagation(),!(!u||!await q({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0})))try{await u(e.id),r(`Deleted ${e.id}`,"success")}catch(Y){const _e=Zu(Y);if(!_e||_e.dependentIds.length===0){r(`Failed to delete ${e.id}: ${Se(Y)}`,"error");return}const ut=_e.dependentIds.join(", ");if(!await q({title:"Force Delete Task",message:`${e.id} is a dependency of ${ut}.
|
|
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(zt){r(`Failed to delete ${e.id}: ${Se(zt)}`,"error")}}},[r,q,u,e.id]),bt=i.useCallback(Ne=>{Ne.stopPropagation(),h?.(e,"changes")},[e,h]),Ot=i.useCallback(Ne=>{Ne.stopPropagation(),A(W=>!W)},[]),en=i.useCallback(Ne=>{Ne.stopPropagation(),e.missionId&&p&&p(e.missionId)},[e.missionId,p]),Kt=i.useCallback(Ne=>{Ne.stopPropagation(),M(W=>!W)},[]),Sn=i.useCallback(async(Ne,W)=>{if(Ne.stopPropagation(),M(!1),!!g)try{const Y=e.steps.some(At=>At.status!=="pending"),_e=(W==="todo"||W==="triage")&&Y;let ut;if(_e){if(await q({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))ut={preserveProgress:!0};else if(!await q({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await g(e.id,W,ut),r(`Moved ${e.id} to ${hs[W]}`,"success")}catch(Y){r(`Failed to move ${e.id}: ${Se(Y)}`,"error")}},[r,q,g,e.id,e.steps]),dn=i.useCallback(async Ne=>{if(Ne.stopPropagation(),!(!m||D)){$(!0);try{await m(e.id)}catch(W){r(`Failed to retry ${e.id}: ${Se(W)}`,"error")}finally{$(!1)}}},[r,D,m,e.id]),Jt=`card${S?" dragging":""}${s?" queued":""}${Me?" agent-active":""}${Ue?" failed":""}${ue?" paused":""}${ht?" stuck":""}${tt?" awaiting-approval":""}${C?" file-drop-target":""}${N?" card-editing":""}${_?" card-saving":""}`,tn=(()=>{if(e.column==="in-progress"){const Ne=sn?.filesChanged,W=Ne==null||Ne===0?e.modifiedFiles?.length:void 0,Y=Ne!=null&&Ne>0?Ne:W;return Y==null||Y===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:bt,disabled:!h,children:[t.jsx(js,{size:12}),t.jsxs("span",{children:[Y," ",Y===1?"file":"files"," changed"]})]})}if(e.column==="in-review"){const Ne=sn?.filesChanged,W=Ne==null||Ne===0?e.modifiedFiles?.length:void 0,Y=Ne!=null&&Ne>0?Ne:W;return Y==null||Y===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:bt,disabled:!h,children:[t.jsx(js,{size:12}),t.jsxs("span",{children:[Y," ",Y===1?"file":"files"," changed"]})]})}if(e.column==="done"){const Ne=sn?.filesChanged,W=e.mergeDetails?.filesChanged,Y=Ne??W;if(Y!=null&&Y>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:bt,disabled:!h,children:[t.jsx(js,{size:12}),t.jsxs("span",{children:[Y," ",Y===1?"file":"files"," changed"]})]});const _e=e.modifiedFiles?.length;if(_e!=null&&_e>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:bt,disabled:!h,children:[t.jsx(js,{size:12}),t.jsxs("span",{children:[_e," ",_e===1?"file":"files"," changed"]})]})}return null})();return N?t.jsx("div",{ref:He,className:Jt,"data-id":e.id,"data-column":e.column,onDoubleClick:at,children:t.jsxs("div",{className:"card-editing-content",children:[t.jsx("textarea",{ref:le,className:"card-edit-desc-textarea",placeholder:"Task description",value:F,onChange:It,onKeyDown:Pe,onBlur:Ke,disabled:_,rows:4}),_&&t.jsxs("div",{className:"card-edit-loading",children:[t.jsx("span",{className:"card-edit-loading-spinner"}),t.jsx("span",{className:"card-edit-loading-text",children:"Saving..."})]})]})}):t.jsxs("div",{ref:He,className:Jt,"data-id":e.id,"data-column":e.column,draggable:Ye,onDragStart:Ye?B:void 0,onDragEnd:Ye?pe:void 0,onDragOver:ae,onDragLeave:Ve,onDrop:Te,onClick:Be,onTouchStart:ce,onTouchMove:Re,onTouchEnd:Le,onDoubleClick:at,children:[t.jsxs("div",{className:"card-header",children:[t.jsx("span",{className:"card-id",children:e.id}),ue&&t.jsx("span",{className:"card-status-badge paused",children:oe?"paused by agent":"paused"}),!ue&&e.status&&e.status!=="queued"&&t.jsx("span",{className:`card-status-badge card-status-badge--${e.column}${tt?" awaiting-approval":""}${Dh.has(e.status)?" pulsing":""}${Ue?" failed":""}${ht?" stuck":""}`,children:ht?"Stuck":tt?"Awaiting Approval":yE(e.status)}),ht&&(ue||!e.status||e.status==="queued")&&t.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),Fe&&t.jsx(zb,{prInfo:xn,issueInfo:qt}),$t&&t.jsxs("span",{className:"card-agent-created-badge",title:ge,"aria-label":ge,children:[t.jsx(Qn,{size:11,"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:ge}),t.jsx("span",{"aria-hidden":"true",children:"Agent"})]}),ft&&t.jsx("span",{className:`card-priority-badge card-priority-badge--${Ee}`,children:Ee}),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(ls,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),e.missionId&&t.jsxs("span",{className:"card-mission-badge",onClick:en,title:`Mission: ${T??e.missionId}`,role:p?"button":void 0,tabIndex:p?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.jsx(Es,{size:11}),uE(T??e.missionId)]}),t.jsxs("div",{className:"card-header-actions",children:[dt&&t.jsx("button",{className:"card-edit-btn",onClick:We,title:"Edit task","aria-label":"Edit task",children:t.jsx(Hs,{size:12})}),e.column==="triage"&&u&&t.jsx("button",{className:"card-delete-btn",onClick:Gt,title:"Delete task","aria-label":"Delete task",children:t.jsx(Tn,{size:12})}),e.column==="done"&&c&&t.jsx("button",{className:"card-archive-btn",onClick:Lt,title:"Archive task","aria-label":"Archive task",children:"Archive"}),e.column==="archived"&&d&&t.jsx("button",{className:"card-unarchive-btn",onClick:Bt,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),e.column==="in-progress"&&g&&t.jsxs("div",{className:"card-send-back",ref:ye,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:Kt,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":O,children:["Send back",t.jsx(gn,{size:10})]}),O&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:mu["in-progress"].filter(Ne=>Ne!=="in-review").map(Ne=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:W=>Sn(W,Ne),children:hs[Ne]},Ne))})]}),e.column==="in-review"&&g&&t.jsxs("div",{className:"card-send-back",ref:ye,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:Kt,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":O,children:["Move",t.jsx(gn,{size:10})]}),O&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:mu["in-review"].map(Ne=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:W=>Sn(W,Ne),children:Ne==="done"?"Done (no merge)":hs[Ne]},Ne))})]}),e.size&&t.jsx("span",{className:`card-size-badge size-${e.size.toLowerCase()}`,children:e.size})]})]}),Ue&&e.error&&t.jsxs("div",{className:"card-error",title:e.error,children:[t.jsx("span",{className:"card-error-icon",children:"⚠"}),t.jsx("span",{className:"card-error-text",children:e.error.length>60?e.error.slice(0,60)+"…":e.error}),m&&t.jsxs("button",{type:"button",className:"btn btn-sm card-error-retry-btn",onClick:dn,disabled:D,children:[t.jsx(Ok,{size:12}),D?"Retrying…":"Retry"]})]}),t.jsx("div",{className:"card-title",title:e.title||e.description||void 0,children:Vh(e.title,qh)||Vh(e.description,qh)||e.id}),be&&t.jsxs("div",{className:"card-branch-row","aria-label":"Branch metadata",children:[Ze.branch&&t.jsxs("span",{className:"card-branch-chip",title:Ze.branch,children:[t.jsx("span",{className:"card-branch-label",children:"Branch"}),t.jsx("span",{className:"card-branch-value",children:Ze.branch})]}),Ze.baseBranch&&t.jsxs("span",{className:"card-branch-chip",title:Ze.baseBranch,children:[t.jsx("span",{className:"card-branch-label",children:"Base"}),t.jsx("span",{className:"card-branch-value",children:Ze.baseBranch})]})]}),vt&&(()=>{const Ne=pt.completed/pt.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:`${Ne}%`,backgroundColor:bE[e.column]}})}),t.jsxs("span",{className:"card-progress-label",children:[pt.completed,"/",pt.total]})]}),t.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:Ot,"aria-expanded":U,"aria-label":U?"Hide steps":"Show steps",children:[t.jsxs("span",{children:[pt.total," step",pt.total===1?"":"s"]}),t.jsx(gn,{size:14,className:`card-steps-toggle-icon${U?" expanded":""}`})]}),U&&t.jsx("div",{className:"card-steps-list",children:pt.items.map(W=>{const Y=W.source==="workflow"&&W.status==="failed";return t.jsxs("div",{className:"card-step-item",children:[t.jsx("span",{className:`card-step-dot card-step-dot--${W.status}${Y?" card-step-dot--workflow-failed":""}`,"aria-hidden":"true"}),t.jsx("span",{className:`card-step-name${W.status==="done"?" completed":""}`,children:W.name}),W.source==="workflow"&&t.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${W.phase}`,title:"Workflow check",children:"workflow"})]},W.id)})})]})})(),(tn||Ut||J||me)&&t.jsxs("div",{className:"card-footer-row",children:[tn,J&&t.jsx("span",{className:"card-source-provenance",title:gt?`Imported from GitHub: ${gt}`:"Imported from GitHub","aria-label":"Imported from GitHub",children:t.jsx(zn,{provider:"github",size:"sm"})}),me&&wt&&t.jsx("a",{className:"card-source-provenance card-github-tracking-link",href:wt.url,target:"_blank",rel:"noopener noreferrer",title:`Linked GitHub issue: ${wt.owner}/${wt.repo}#${wt.number}`,"aria-label":`Linked GitHub issue #${wt.number}`,onClick:Ne=>Ne.stopPropagation(),children:t.jsx(zn,{provider:"github",size:"sm"})}),Ut&&t.jsxs("span",{className:"card-time-indicator",title:Ut.title,"aria-label":Ut.ariaLabel,children:[t.jsx(ta,{size:12}),t.jsx("span",{children:Ut.label})]})]}),(e.dependencies&&e.dependencies.length>0||s||e.status==="queued"||e.blockedBy||y&&y.totalCount>0)&&t.jsxs("div",{className:"card-meta",children:[e.dependencies&&e.dependencies.length>0&&t.jsx("div",{className:"card-dep-list",children:e.dependencies.map(Ne=>t.jsxs("span",{className:"card-dep-badge clickable",onClick:W=>void ct(W,Ne),title:`Click to view ${Ne}`,children:[t.jsx(Sr,{size:12,style:{verticalAlign:"middle"}})," ",Ne]},Ne))}),e.blockedBy&&t.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${e.blockedBy} (file overlap)`,children:[t.jsx(Fa,{size:12,style:{verticalAlign:"middle"}})," ",e.blockedBy]}),y&&y.totalCount>0&&t.jsxs("span",{className:`card-fanout-badge${y.staleBlockedByDependentIds.length>0?" card-fanout-badge--stale":""}`,"data-tooltip":`Blocking ${y.totalCount} active task(s); ${y.activeTodoCount} waiting in todo${y.isHighFanout?` (high fan-out threshold: ${Xu})`:""}${y.escalation?` · escalated after ${Math.floor(y.escalation.blockingAgeMs/6e4)}m in blocking column`:""}`,children:[t.jsx(Os,{size:12,style:{verticalAlign:"middle"}}),t.jsxs("span",{children:[y.escalation?"Escalated":y.isHighFanout?"High fan-out":"Blocks"," ",t.jsx("span",{className:"card-fanout-count",children:y.totalCount}),y.staleBlockedByDependentIds.length>0?` (${y.staleBlockedByDependentIds.length} stale)`:""]})]}),(s||e.status==="queued")&&e.column!=="in-progress"&&t.jsxs("span",{className:"queued-badge",children:[t.jsx(ta,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),(e.assignedAgentId||yt.length>0)&&t.jsxs("div",{className:"card-agent-row",children:[yt.length>0&&t.jsx("span",{className:"card-provider-icons","data-testid":"card-provider-icons",children:yt.map(Ne=>t.jsx(zn,{provider:Ne,size:"sm"},Ne))}),e.assignedAgentId&&t.jsxs("span",{className:`card-agent-badge${st?" card-agent-badge--loading":""}`,title:`Assigned to ${Q??e.assignedAgentId}`,children:[t.jsx(Qn,{size:11}),t.jsx("span",{className:"card-agent-badge-text","aria-hidden":"true",children:pE(Q??e.assignedAgentId,15)}),t.jsxs("span",{className:"visually-hidden",children:["Assigned to ",Q??e.assignedAgentId]})]})]}),t.jsx(pa,{slotId:"task-card-badge",projectId:n})]})}const Hh=10,TE=300,qh=140;function Vh(e,n){return e?e.length>n?e.slice(0,n)+"…":e:""}const Do=i.memo(IE,RE);Do.displayName="TaskCard";function PE({label:e,activeTasks:n,queuedTasks:s,projectId:a,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:d,onOpenDetailWithTab:u,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p,blockerFanoutMap:g}){return t.jsxs("div",{className:"worktree-group",children:[t.jsxs("div",{className:"worktree-group-header",children:[t.jsx("span",{className:"worktree-icon",children:e==="Up Next"||e==="Unassigned"?t.jsx(tw,{size:14}):t.jsx(Os,{size:14})}),t.jsx("span",{className:"worktree-label",children:e})]}),n.map(w=>t.jsx(Do,{task:w,projectId:a,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:d,onOpenDetailWithTab:u,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p,fanout:g?.get(w.id)},w.id)),s.map(w=>t.jsx(Do,{task:w,projectId:a,queued:!0,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:d,onOpenDetailWithTab:u,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p,fanout:g?.get(w.id)},w.id))]})}const Yb=i.memo(PE);Yb.displayName="WorktreeGroup";function Wh(e){return e.toLowerCase().replace(/[-_./]/g,"")}function $E(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 DE(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 LE(e,n){const s=Wh(e),a=Wh(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&&$E(s,o)||s.length>=4&&DE(s,o,1))return!0;return!1}function OE(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=>LE(o,r))})}function _s({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),[w,v]=i.useState(""),[b,y]=i.useState(0),[S,j]=i.useState(null),[C,x]=i.useState(null),N=i.useRef(null),R=i.useRef(null),F=i.useRef(null),E=i.useRef(null),_=i.useRef(null),K=i.useMemo(()=>OE(e,w),[e,w]),U=i.useMemo(()=>K.reduce((Z,re)=>((Z[re.provider]??=[]).push(re),Z),{}),[K]),A=i.useMemo(()=>{const Z=[];for(const re of u){const q=re.indexOf("/");if(q===-1)continue;const L=re.slice(0,q),xe=re.slice(q+1),he=K.find(B=>B.provider===L&&B.id===xe);he&&Z.push({model:he,fullId:re})}return Z},[u,K]),T=i.useMemo(()=>{const Z=Object.entries(U),re=new Set(c);return Z.sort(([q],[L])=>{const xe=re.has(q),he=re.has(L);if(xe&&!he)return-1;if(!xe&&he)return 1;if(xe&&he){const B=c.indexOf(q),pe=c.indexOf(L);if(B!==pe)return B-pe}return q.localeCompare(L)})},[U,c]),H=typeof h=="string"&&h.length>0,Q=i.useMemo(()=>{if(!n||H&&n===h)return null;const Z=n.indexOf("/");return Z===-1?null:n.slice(0,Z)},[H,h,n]),se=i.useMemo(()=>{const Z=[];return H&&Z.push({type:"no-change",value:h,label:f}),Z.push({type:"default",value:"",label:"Use default"}),Z},[H,f,h]),O=i.useMemo(()=>{const Z=[...se];for(const{model:re,fullId:q}of A)Z.push({type:"favorite",value:q,label:re.name,provider:re.provider});return T.forEach(([re,q])=>{Z.push({type:"provider",value:`__group_${re}`,label:re,provider:re}),q.forEach(L=>{Z.push({type:"model",value:`${L.provider}/${L.id}`,label:L.name,provider:L.provider})})}),Z},[A,T,se]),M=i.useMemo(()=>{if(H&&n===h)return f;if(!n)return"Use default";const Z=n.indexOf("/");if(Z===-1)return n;const re=n.slice(0,Z),q=n.slice(Z+1);return e.find(xe=>xe.provider===re&&xe.id===q)?.name||n},[H,f,h,n,e]),D=i.useMemo(()=>O.findIndex(Z=>Z.value===n),[O,n]),$=i.useCallback(()=>{const Z=window.visualViewport;return Z&&Z.height>0&&Z.width>0?{width:Z.width,height:Z.height,offsetTop:Z.offsetTop,offsetLeft:Z.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),k=i.useCallback(()=>{const{height:Z}=$(),re=typeof window.matchMedia=="function",q=re?window.matchMedia("(max-width: 640px)").matches:!1,L=re?window.matchMedia("(max-width: 768px)").matches:!1;return Z<=0?320:q?Math.min(Z*.6,360):L?Math.min(Z*.7,420):320},[$]),X=i.useCallback(()=>{const Z=R.current;if(!Z)return;const re=Z.getBoundingClientRect(),{width:q,height:L,offsetTop:xe,offsetLeft:he}=$(),B=16,pe=16,ze=4,ae=k(),Ve=re.bottom-xe,Te=re.top-xe,rt=re.left-he,Be=L-Ve,ce=Te,Re=Math.max(Be-pe-ze,160),Le=Math.max(ce-pe-ze,160),ct=Be<ae&&ce>Be,Ue=Math.max(Math.min(ct?Le:Re,ae),160),ue=Math.min(re.width,q-B*2),oe=Math.min(Math.max(rt,B),q-B-ue)+he,Ee=ct?Math.max(pe+xe,Te-Ue-ze+xe):Math.min(Ve+ze+xe,L+xe-pe-Ue);j({top:Ee,left:oe,width:ue,maxHeight:Ue})},[$,k]);i.useEffect(()=>{x(document.body)},[]);const le=i.useRef(!1);i.useEffect(()=>{if(!p){le.current=!1;return}if(le.current||O.length===0)return;const Z=O.findIndex((re,q)=>q>=(D>=0?D:0)&&re.type!=="provider");y(Z>=0?Z:0),le.current=!0},[p,O,D]),i.useEffect(()=>{p&&le.current&&(y(0),_.current&&(_.current.scrollTop=0))},[w,p]),i.useEffect(()=>{if(!p)return;X();const Z=requestAnimationFrame(()=>E.current?.focus());return()=>cancelAnimationFrame(Z)},[p,X]),i.useEffect(()=>{if(!p)return;const Z=()=>X();window.addEventListener("resize",Z),window.addEventListener("scroll",Z,!0);const re=window.visualViewport;return re&&(re.addEventListener("resize",Z),re.addEventListener("scroll",Z)),()=>{window.removeEventListener("resize",Z),window.removeEventListener("scroll",Z,!0),re&&(re.removeEventListener("resize",Z),re.removeEventListener("scroll",Z))}},[p,X]),i.useEffect(()=>{if(!p)return;const Z=re=>{const q=re.target,L=N.current?.contains(q),xe=F.current?.contains(q);!L&&!xe&&(g(!1),v(""))};return document.addEventListener("mousedown",Z),()=>document.removeEventListener("mousedown",Z)},[p]);const ke=i.useCallback(Z=>{switch(Z.key){case"ArrowDown":if(Z.preventDefault(),!p)g(!0);else{let re=b;for(let q=1;q<=O.length;q++){const L=(b+q)%O.length;if(O[L]?.type!=="provider"){re=L;break}}y(re)}break;case"ArrowUp":if(Z.preventDefault(),p){let re=b;for(let q=1;q<=O.length;q++){const L=(b-q+O.length)%O.length;if(O[L]?.type!=="provider"){re=L;break}}y(re)}break;case"Enter":if(Z.preventDefault(),p){const re=O[b];re&&re.type!=="provider"&&re.type!=="favorite"&&(s(re.value),g(!1),v(""))}else g(!0);break;case"Escape":Z.preventDefault(),g(!1),v("");break;case"Tab":p&&(g(!1),v(""));break}},[p,b,O,s]),He=i.useCallback(Z=>{s(Z),g(!1),v("")},[s]),ye=i.useCallback(()=>{v(""),E.current?.focus()},[]),je=i.useCallback(()=>{r||g(Z=>!Z)},[r]);i.useEffect(()=>{if(p&&_.current){const Z=_.current.querySelector(`[data-index="${b}"]`);Z&&typeof Z.scrollIntoView=="function"&&Z.scrollIntoView({block:"nearest"})}},[b,p]);const ne=w.length>0,fe=p&&S?t.jsxs("div",{ref:F,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:ke,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:w,onChange:Z=>v(Z.target.value),onClick:Z=>Z.stopPropagation()}),ne&&t.jsx("button",{type:"button",className:"model-combobox-clear",onClick:ye,"aria-label":"Clear filter",children:"×"})]}),t.jsxs("div",{className:"model-combobox-results-count",children:[K.length," model",K.length!==1?"s":""]}),t.jsxs("div",{ref:_,className:"model-combobox-list",children:[se.map((Z,re)=>t.jsx("div",{"data-index":re,className:`model-combobox-option ${b===re?"model-combobox-option--highlighted":""} ${n===Z.value?"model-combobox-option--selected":""}`,onClick:()=>He(Z.value),onMouseEnter:()=>y(re),role:"option","aria-selected":n===Z.value,children:t.jsx("span",{className:"model-combobox-option-text model-combobox-option-text--default",children:Z.label})},`${Z.type}-${Z.value}`)),A.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"model-combobox-divider"}),A.map(({model:Z,fullId:re},q)=>{const L=q+se.length,xe=b===L,he=n===re;return t.jsxs("div",{"data-index":L,className:`model-combobox-option model-combobox-option--favorite ${xe?"model-combobox-option--highlighted":""} ${he?"model-combobox-option--selected":""}`,onClick:()=>He(re),onMouseEnter:()=>y(L),role:"option","aria-selected":he,children:[t.jsxs("span",{className:"model-combobox-option-main",children:[t.jsx("span",{className:"model-combobox-option-icon",children:t.jsx(zn,{provider:Z.provider,size:"sm"})}),t.jsx("span",{className:"model-combobox-option-text",children:Z.name})]}),t.jsx("span",{className:"model-combobox-option-id",children:Z.id}),m&&t.jsx("button",{type:"button",className:"model-combobox-option-favorite model-combobox-option-favorite--active",onClick:B=>{B.stopPropagation(),m(re)},title:"Remove from favorites","aria-label":`Remove ${Z.name} from favorites`,children:"★"})]},re)}),t.jsx("div",{className:"model-combobox-divider"})]}),T.map(([Z,re])=>{const q=O.findIndex(he=>he.value===`__group_${Z}`),L=c.includes(Z),xe=re.filter(he=>{const B=`${he.provider}/${he.id}`;return!u.includes(B)});return xe.length===0?null:t.jsxs("div",{className:"model-combobox-group",children:[t.jsxs("div",{className:"model-combobox-optgroup","data-index":q,children:[t.jsx(zn,{provider:Z,size:"sm"}),t.jsx("span",{className:"model-combobox-optgroup-text",children:Z}),d&&t.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${L?"model-combobox-optgroup-favorite--active":""}`,onClick:he=>{he.stopPropagation(),d(Z)},title:L?"Remove from favorites":"Add to favorites","aria-label":L?`Remove ${Z} from favorites`:`Add ${Z} to favorites`,children:"★"})]}),xe.map(he=>{const B=`${he.provider}/${he.id}`,pe=O.findIndex(Te=>Te.value===B),ze=b===pe,ae=n===B,Ve=u.includes(B);return t.jsxs("div",{"data-index":pe,className:`model-combobox-option ${ze?"model-combobox-option--highlighted":""} ${ae?"model-combobox-option--selected":""}`,onClick:()=>He(B),onMouseEnter:()=>y(pe),role:"option","aria-selected":ae,children:[t.jsx("span",{className:"model-combobox-option-text",children:he.name}),t.jsx("span",{className:"model-combobox-option-id",children:he.id}),m&&t.jsx("button",{type:"button",className:`model-combobox-option-favorite ${Ve?"model-combobox-option-favorite--active":""}`,onClick:Te=>{Te.stopPropagation(),m(B)},title:Ve?"Remove from favorites":"Add to favorites","aria-label":Ve?`Remove ${he.name} from favorites`:`Add ${he.name} to favorites`,children:Ve?"★":"☆"})]},B)})]},Z)}),K.length===0&&ne&&t.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",w,"'"]})]})]}):null;return t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:N,className:"model-combobox",onKeyDown:ke,children:t.jsxs("button",{ref:R,type:"button",id:o,className:"model-combobox-trigger",onClick:je,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":l,children:[Q&&t.jsx("span",{className:"model-combobox-trigger-icon",children:t.jsx(zn,{provider:Q,size:"sm"})}),t.jsx("span",{className:"model-combobox-trigger-text",children:M||a}),t.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),C&&fe?$a.createPortal(fe,C):null]})}function em(e,n){return typeof n!="string"||n.length===0?e:`kb:${n}:${e}`}function Gn(e,n){if(typeof window>"u")return null;const s=window.localStorage?.getItem;return typeof s!="function"?null:s.call(window.localStorage,em(e,n))}function fs(e,n,s){if(typeof window>"u")return;const a=window.localStorage?.setItem;typeof a=="function"&&a.call(window.localStorage,em(e,s),n)}function Ar(e,n){if(typeof window>"u")return;const s=window.localStorage?.removeItem;typeof s=="function"&&s.call(window.localStorage,em(e,n))}const FE=1e4,zE=1e3;function Cc(){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 Yl();n(b)}catch(b){o(b instanceof Error?b.message:"Failed to fetch nodes")}},[]);i.useEffect(()=>{let b=!1;async function y(){a(!0);try{const j=await Yl();b||(n(j),o(null))}catch(j){b||o(j instanceof Error?j.message:"Failed to fetch nodes")}finally{b||a(!1)}}y();const S=()=>{if(document.visibilityState!=="visible")return;const j=Date.now();j-c.current<zE||(c.current=j,d())};return document.addEventListener("visibilitychange",S),()=>{b=!0,document.removeEventListener("visibilitychange",S)}},[d]),i.useEffect(()=>{if(!s)return l.current=setInterval(()=>{d()},FE),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,d]);const u=i.useCallback(async b=>{const{projectMappings:y,...S}=b,j=await u1(S);if(y.length>0)try{await tC(j.id,y)}catch(C){const x=C instanceof Error?C.message:"Failed to persist project mappings";let N="";try{await ah(j.id)}catch(R){N=R instanceof Error?R.message:"Failed to unregister node after mapping failure"}throw await d(),N?new Error(`${x}. Cleanup also failed: ${N}`):new Error(x)}return await d(),j},[d]),m=i.useCallback(async(b,y)=>{const S=await h1(b,y);return n(j=>j.map(C=>C.id===b?S:C)),S},[]),h=i.useCallback(async b=>{await ah(b),n(y=>y.filter(S=>S.id!==b))},[]),f=i.useCallback(async b=>{const y=await b1(b);n(S=>S.map(j=>j.id===b?{...j,status:y.status,updatedAt:y.checkedAt}:j))},[]),p=i.useCallback(b=>p1(b),[]),g=i.useCallback(async(b,y)=>{const S=await f1(b,y);return n(j=>j.map(C=>C.id===b?{...C,dockerConfig:S}:C)),S},[]),w=i.useCallback(async b=>{const y=await g1(b);return"persistedVersion"in y?y:{persistedVersion:0,deployedVersion:null,needsRecreate:!1}},[]),v=i.useCallback(async b=>m1(b),[]);return{nodes:e,loading:s,error:r,refresh:d,register:u,update:m,unregister:h,healthCheck:f,fetchDockerConfig:p,patchDockerConfig:g,fetchDockerDiff:w,discoverRemoteProjects:v}}const to="kb-quick-entry-text",BE=["image/png","image/jpeg","image/gif","image/webp"];function UE(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function td(e,n){return e&&n?`${e}/${n}`:""}function nd(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 Qb({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"&&Gn(to,l)||""),[g,w]=i.useState(!1),[v,b]=i.useState(!1),[y,S]=i.useState(!1),j=i.useRef(null),C=i.useRef(null),x=i.useRef(!1),N=i.useRef(l),[R,F]=i.useState([]),E=i.useRef([]),[_,K]=i.useState([]),[U,A]=i.useState(!1),[T,H]=i.useState(""),[Q,se]=i.useState(null),[O,M]=i.useState([]),[D,$]=i.useState(void 0),[k,X]=i.useState(!1),[le,ke]=i.useState(!1),[He,ye]=i.useState(!1),[je,ne]=i.useState(!1),[fe,Z]=i.useState(!1),[re,q]=i.useState(null),[L,xe]=i.useState(void 0),[he,B]=i.useState(void 0),[pe,ze]=i.useState(void 0),[ae,Ve]=i.useState(void 0),[Te,rt]=i.useState(void 0),[Be,ce]=i.useState(void 0),Re=i.useRef(null),Le=i.useRef(null),ct=i.useRef(null),Ue=i.useRef(null),ue=i.useRef(null),oe=i.useRef(null),Ee=i.useRef(null),ft=i.useRef(null),[ht,tt]=i.useState(null),[xt,Me]=i.useState(null),[Ye,dt]=i.useState(null),[wt,St]=i.useState(null),Fe=i.useRef(null),J=i.useRef(null),[me,Ze]=i.useState(null),[be]=i.useState(()=>typeof document<"u"?document.body:null),[gt,$t]=i.useState(!1),[Ie,ge]=i.useState(null),[st,yt]=i.useState(a??[]),[pt,vt]=i.useState([]),[Ut,Dt]=i.useState([]),[nn,on]=i.useState(null),[sn,ln]=i.useState(void 0),[xn,qt]=i.useState(!1),[Qt,hn]=i.useState(Ps),[Zt,ve]=i.useState(void 0),{nodes:Pe}=Cc(),[Ke,at]=i.useState(!1),[We,It]=i.useState(!1),Lt=i.useRef(null),Bt=i.useRef(null),[Gt,bt]=i.useState(null),Ot=d??pt,en=u??Ut,Kt=!e;i.useEffect(()=>{if(a)yt(a),$t(!1),ge(null);else{let te=!1;return $t(!0),ge(null),Ws().then(we=>{te||(yt(we.models),d||vt(we.favoriteProviders),u||Dt(we.favoriteModels))}).catch(we=>{te||ge(Se(we)||"Failed to load models")}).finally(()=>{te||$t(!1)}),kc(l).then(we=>{te||on(we)}).catch(()=>{}),()=>{te=!0}}},[a,d,u,l]);const Sn=td(L,he),dn=td(pe,ae),Jt=td(Te,Be),tn=!!(L&&he),Ne=!!(pe&&ae),W=!!(Te&&Be),Y=Number(tn)+Number(Ne)+Number(W),_e=sn?nn?.modelPresets?.find(te=>te.id===sn)?.name??"Models":Y>0?`${Y} model${Y===1?"":"s"}`:"Models",ut=i.useCallback((te,we)=>{if(!te||!we)return"Using default";const P=st.find(Ce=>Ce.provider===te&&Ce.id===we);return P?`${P.provider}/${P.id}`:`${te}/${we}`},[st]);i.useEffect(()=>{p(Gn(to,l)||"")},[l]),i.useEffect(()=>{typeof window<"u"&&fs(to,f,l)},[f,l]),i.useEffect(()=>{N.current!==l&&(N.current=l,M([]),$(void 0),se(null),X(!1),tt(null))},[l]),i.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),i.useEffect(()=>{E.current=R},[R]),i.useEffect(()=>()=>{E.current.forEach(te=>URL.revokeObjectURL(te.previewUrl))},[]);const At=i.useCallback(()=>{const te=j.current;if(!te)return;te.style.height="auto";const we=Math.min(te.scrollHeight,200);te.style.height=`${we}px`},[]);i.useEffect(()=>{v&&At()},[f,v,At]),i.useEffect(()=>{if(!g&&f===""&&j.current){const te=setTimeout(()=>{j.current?.focus()},0);return()=>clearTimeout(te)}},[g,f]),i.useEffect(()=>{U||H("")},[U]),i.useEffect(()=>{if(!Ke)return;const te=we=>{const P=we.target,Ce=Lt.current?.contains(P),qe=Bt.current?.contains(P);!Ce&&!qe&&at(!1)};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[Ke]),i.useEffect(()=>{if(!fe)return;const te=we=>{const P=we.target,Ce=Re.current?.contains(P),qe=Le.current?.contains(P),et=P instanceof Element&&P.closest?.(".model-combobox-dropdown--portal")!=null;!Ce&&!qe&&!et&&(Z(!1),q(null))};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[fe]),i.useEffect(()=>{if(!le)return;const te=we=>{const P=we.target;ue.current?.contains(P)||oe.current?.contains(P)||(ke(!1),Me(null))};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[le]),i.useEffect(()=>{if(!k)return;const te=we=>{const P=we.target;ct.current?.contains(P)||Ue.current?.contains(P)||(X(!1),tt(null))};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[k]),i.useEffect(()=>{if(!He)return;const te=we=>{const P=we.target;Ee.current?.contains(P)||ft.current?.contains(P)||(ye(!1),dt(null))};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[He]);const zt=i.useCallback(()=>{R.forEach(te=>URL.revokeObjectURL(te.previewUrl)),F([]),C.current&&(C.current.value=""),p(""),K([]),se(null),X(!1),tt(null),ke(!1),Me(null),ye(!1),dt(null),xe(void 0),B(void 0),ze(void 0),Ve(void 0),rt(void 0),ce(void 0),ln(void 0),qt(!1),hn(Ps),ve(void 0),A(!1),Z(!1),St(null),q(null),at(!1),It(!1),b(!1),S(!1),x.current=!0,j.current&&(j.current.style.height="auto"),typeof window<"u"&&Ar(to,l)},[R,l]),yn=i.useCallback(te=>{if(!te||te.length===0)return;const we=[];for(let P=0;P<te.length;P++){const Ce=te[P];BE.includes(Ce.type)&&we.push({file:Ce,previewUrl:URL.createObjectURL(Ce)})}we.length>0&&F(P=>[...P,...we])},[]),Zn=i.useCallback(te=>{g||yn(te.clipboardData?.files)},[yn,g]),vn=i.useCallback(te=>{F(we=>{const P=we[te];return P&&URL.revokeObjectURL(P.previewUrl),we.filter((Ce,qe)=>qe!==te)})},[]),Dn=i.useCallback(async()=>{const te=f.trim();if(!te||g||!e)return;const we=f;w(!0),p("");try{const P=await e({description:te,column:"triage",dependencies:_.length?_:void 0,...Q?{assignedAgentId:Q}:{},modelPresetId:sn,modelProvider:tn?L:void 0,modelId:tn?he:void 0,validatorModelProvider:Ne?pe:void 0,validatorModelId:Ne?ae:void 0,planningModelProvider:W?Te:void 0,planningModelId:W?Be:void 0,...xn?{executionMode:"fast"}:{},priority:Qt,nodeId:Zt});if(P&&R.length>0){const Ce=[];for(const qe of R)try{await jc(P.id,qe.file,l)}catch{Ce.push(qe.file.name)}Ce.length>0&&n(`Failed to upload: ${Ce.join(", ")}`,"error")}zt()}catch(P){p(we),n(Se(P)||"Failed to create task","error")}finally{w(!1)}},[f,g,e,_,Q,tn,L,he,Ne,pe,ae,W,Te,Be,R,l,n,zt,xn,Qt,Zt]),de=i.useCallback(te=>{if(te.key==="Enter"){if(te.shiftKey&&v)return;te.preventDefault(),Dn()}else if(te.key==="Escape"){if(te.preventDefault(),re){q(null);return}if(fe){Z(!1),St(null);return}if(U){A(!1);return}if(Ke){at(!1);return}if(le){ke(!1),Me(null);return}if(He){ye(!1),dt(null);return}if(k){X(!1),tt(null);return}f.trim()&&(p(""),j.current&&(j.current.style.height="auto"),typeof window<"u"&&Ar(to,l)),b(!1),S(!1),j.current?.blur()}},[Dn,f,v,U,k,le,fe,re,Ke,He,l,S]),nt=i.useCallback(()=>{x.current&&(x.current=!1)},[]),ot=i.useCallback(()=>{c&&b(!0)},[c]),_t=i.useCallback(te=>{K(we=>we.includes(te)?we.filter(P=>P!==te):[...we,te])},[]),G=i.useCallback(()=>{const te=window.visualViewport;return te&&te.width>0&&te.height>0?{width:te.width,height:te.height,offsetTop:te.offsetTop,offsetLeft:te.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),Oe=i.useCallback(()=>{const te=Re.current;if(!te)return;const we=te.getBoundingClientRect(),{width:P,height:Ce,offsetTop:qe,offsetLeft:et}=G(),mt=16,Nt=16,Pt=4,an=P<=768,Cn=Math.min(an?Ce*.6:Ce*.5,360),ie=Math.max(we.width*1.35,320),$e=an?Math.min(P-mt*2,360):ie,Qe=Math.min($e,Math.max(P-mt*2,240)),Ft=we.top-qe,cn=we.bottom-qe,pn=we.left-et,jn=Ce-cn,Un=Ft,gs=Math.max(jn-Nt-Pt,160),bs=Math.max(Un-Nt-Pt,160),is=jn<Cn&&Un>jn,ds=Math.max(Math.min(is?bs:gs,Cn),160),xs=Math.min(Math.max(pn,mt),P-mt-Qe)+et,ra=is?Math.max(Nt+qe,Ft-ds-Pt+qe):Math.min(cn+Pt+qe,Ce+qe-Nt-ds);St({top:ra,left:xs,width:Qe,maxHeight:ds})},[G]),Mt=i.useCallback(()=>{const te=Lt.current?.querySelector(".refine-button");if(!te)return;const we=te.getBoundingClientRect(),{width:P,height:Ce,offsetTop:qe,offsetLeft:et}=G(),mt=8,Nt=12,Pt=4,an=Math.min(200,Math.max(Ce-Nt*2,160)),Cn=Math.min(200,P-mt*2),ie=we.top-qe,$e=we.bottom-qe,Qe=we.left-et,Ft=Ce-$e,cn=ie,pn=Ft<an&&cn>Ft,jn=Math.min(Math.max(Qe,mt),P-mt-Cn)+et,Un=pn?Math.max(Nt+qe,ie-an-Pt+qe):Math.min($e+Pt+qe,Ce+qe-Nt-an);bt({top:Un,left:jn})},[G]),Xt=i.useCallback(()=>{const te=Fe.current;if(!te)return;const we=te.getBoundingClientRect(),{width:P,height:Ce,offsetTop:qe,offsetLeft:et}=G(),mt=16,Nt=16,Pt=4,an=P<=768,Cn=Math.min(an?Ce*.6:Ce*.5,320),ie=an?Math.min(P-mt*2,360):Math.max(we.width,280),$e=Math.min(ie,Math.max(P-mt*2,240)),Qe=we.top-qe,Ft=we.bottom-qe,cn=we.left-et,pn=Ce-Ft,jn=Qe,Un=Math.max(pn-Nt-Pt,200),gs=Math.max(jn-Nt-Pt,200),bs=pn<Cn&&jn>pn,is=Math.max(Math.min(bs?gs:Un,Cn),200),ds=Math.min(Math.max(cn,mt),P-mt-$e)+et,xs=bs?Math.max(Nt+qe,Qe-is-Pt+qe):Math.min(Ft+Pt+qe,Ce+qe-Nt-is);Ze({top:xs,left:ds,width:$e,maxHeight:is})},[G]),_n=i.useCallback(()=>{const te=ct.current?.querySelector("button");if(!te)return;const we=te.getBoundingClientRect(),{width:P,height:Ce,offsetTop:qe,offsetLeft:et}=G(),mt=16,Nt=16,Pt=4,an=P<=768,Cn=Math.min(an?Ce*.6:Ce*.5,320),ie=an?Math.min(P-mt*2,280):Math.max(we.width,240),$e=Math.min(ie,Math.max(P-mt*2,200)),Qe=we.top-qe,Ft=we.bottom-qe,cn=we.left-et,pn=Ce-Ft,jn=Qe,Un=Math.max(pn-Nt-Pt,160),gs=Math.max(jn-Nt-Pt,160),bs=pn<Cn&&jn>pn,is=Math.max(Math.min(bs?gs:Un,Cn),160),ds=Math.min(Math.max(cn,mt),P-mt-$e)+et,xs=bs?Math.max(Nt+qe,Qe-is-Pt+qe):Math.min(Ft+Pt+qe,Ce+qe-Nt-is);tt({top:xs,left:ds,width:$e,maxHeight:is})},[G]),Pn=i.useCallback(()=>{const te=ue.current?.querySelector("button");if(!te)return;const we=te.getBoundingClientRect(),{width:P,height:Ce,offsetTop:qe,offsetLeft:et}=G(),mt=16,Nt=16,Pt=4,an=P<=768,Cn=Math.min(an?Ce*.6:Ce*.5,320),ie=an?Math.min(P-mt*2,280):Math.max(we.width,240),$e=Math.min(ie,Math.max(P-mt*2,200)),Qe=we.top-qe,Ft=we.bottom-qe,cn=we.left-et,pn=Ce-Ft,jn=Qe,Un=Math.max(pn-Nt-Pt,160),gs=Math.max(jn-Nt-Pt,160),bs=pn<Cn&&jn>pn,is=Math.max(Math.min(bs?gs:Un,Cn),160),ds=Math.min(Math.max(cn,mt),P-mt-$e)+et,xs=bs?Math.max(Nt+qe,Qe-is-Pt+qe):Math.min(Ft+Pt+qe,Ce+qe-Nt-is);Me({top:xs,left:ds,width:$e,maxHeight:is})},[G]),kn=i.useCallback(()=>{const te=Ee.current?.querySelector("button");if(!te)return;const we=te.getBoundingClientRect(),{width:P,height:Ce,offsetTop:qe,offsetLeft:et}=G(),mt=16,Nt=16,Pt=4,an=220,Cn=Math.min(Math.max(we.width,200),Math.max(P-mt*2,200)),ie=we.top-qe,$e=we.bottom-qe,Qe=we.left-et,Ft=Ce-$e,cn=ie,pn=Math.max(Ft-Nt-Pt,160),jn=Math.max(cn-Nt-Pt,160),Un=Ft<an&&cn>Ft,gs=Math.max(Math.min(Un?jn:pn,an),160),bs=Math.min(Math.max(Qe,mt),P-mt-Cn)+et,is=Un?Math.max(Nt+qe,ie-gs-Pt+qe):Math.min($e+Pt+qe,Ce+qe-Nt-gs);dt({top:is,left:bs,width:Cn,maxHeight:gs})},[G]);i.useEffect(()=>{if(!fe)return;const te=()=>Oe();window.addEventListener("resize",te),window.addEventListener("scroll",te,!0);const we=window.visualViewport;return we&&(we.addEventListener("resize",te),we.addEventListener("scroll",te)),()=>{window.removeEventListener("resize",te),window.removeEventListener("scroll",te,!0),we&&(we.removeEventListener("resize",te),we.removeEventListener("scroll",te))}},[fe,Oe]),i.useEffect(()=>{if(!Ke)return;const te=()=>Mt();window.addEventListener("resize",te),window.addEventListener("scroll",te,!0);const we=window.visualViewport;return we&&(we.addEventListener("resize",te),we.addEventListener("scroll",te)),()=>{window.removeEventListener("resize",te),window.removeEventListener("scroll",te,!0),we&&(we.removeEventListener("resize",te),we.removeEventListener("scroll",te))}},[Ke,Mt]),i.useEffect(()=>{if(!U)return;const te=()=>Xt();window.addEventListener("resize",te),window.addEventListener("scroll",te,!0);const we=window.visualViewport;return we&&(we.addEventListener("resize",te),we.addEventListener("scroll",te)),()=>{window.removeEventListener("resize",te),window.removeEventListener("scroll",te,!0),we&&(we.removeEventListener("resize",te),we.removeEventListener("scroll",te))}},[U,Xt]),i.useEffect(()=>{if(!k)return;const te=()=>_n();window.addEventListener("resize",te),window.addEventListener("scroll",te,!0);const we=window.visualViewport;return we&&(we.addEventListener("resize",te),we.addEventListener("scroll",te)),()=>{window.removeEventListener("resize",te),window.removeEventListener("scroll",te,!0),we&&(we.removeEventListener("resize",te),we.removeEventListener("scroll",te))}},[k,_n]),i.useEffect(()=>{if(!le)return;const te=()=>Pn();window.addEventListener("resize",te),window.addEventListener("scroll",te,!0);const we=window.visualViewport;return we&&(we.addEventListener("resize",te),we.addEventListener("scroll",te)),()=>{window.removeEventListener("resize",te),window.removeEventListener("scroll",te,!0),we&&(we.removeEventListener("resize",te),we.removeEventListener("scroll",te))}},[le,Pn]),i.useEffect(()=>{if(!He)return;const te=()=>kn();window.addEventListener("resize",te),window.addEventListener("scroll",te,!0);const we=window.visualViewport;return we&&(we.addEventListener("resize",te),we.addEventListener("scroll",te)),()=>{window.removeEventListener("resize",te),window.removeEventListener("scroll",te,!0),we&&(we.removeEventListener("resize",te),we.removeEventListener("scroll",te))}},[He,kn]);const Vn=i.useCallback(te=>{const we=nd(te);rt(we.provider),ce(we.modelId)},[]),$s=i.useCallback(te=>{const we=nd(te);xe(we.provider),B(we.modelId)},[]),vs=i.useCallback(te=>{const we=nd(te);ze(we.provider),Ve(we.modelId)},[]),As=i.useCallback(async te=>{if(m){m(te);return}const we=pt,Ce=we.includes(te)?we.filter(qe=>qe!==te):[te,...we];vt(Ce);try{await Bn({favoriteProviders:Ce,favoriteModels:Ut})}catch{vt(we)}},[pt,Ut,m]),bn=i.useCallback(async te=>{if(h){h(te);return}const we=Ut,Ce=we.includes(te)?we.filter(qe=>qe!==te):[te,...we];Dt(Ce);try{await Bn({favoriteProviders:pt,favoriteModels:Ce})}catch{Dt(we)}},[Ut,pt,h]),Ht=i.useCallback(()=>{const te=f.trim();if(!te){n("Enter a description first","error");return}r?.(te),zt()},[f,r,n,zt]),On=i.useCallback(()=>{const te=f.trim();if(!te){n("Enter a description first","error");return}o?.(te),zt()},[f,o,n,zt]),Fn=i.useCallback(()=>{Dn()},[Dn]),as=i.useCallback(async te=>{const we=f.trim();if(!(!we||We)){at(!1),It(!0);try{const P=await fb(we,te,l);p(P),n("Description refined with AI","success"),j.current&&(j.current.style.height="auto",j.current.style.height=`${Math.min(j.current.scrollHeight,200)}px`)}catch(P){const Ce=gb(P);n(Ce,"error")}finally{It(!1)}}},[f,We,n,l]),Wn=(te,we)=>te.length>we?te.slice(0,we)+"…":te,Rs=i.useCallback(async()=>{if(a){yt(a),ge(null),$t(!1);return}$t(!0),ge(null);try{const te=await Ws();yt(te.models),d||vt(te.favoriteProviders),u||Dt(te.favoriteModels)}catch(te){ge(Se(te)||"Failed to load models")}finally{$t(!1)}},[a,d,u]),In=i.useCallback(async()=>{if(O.length>0&&D===l){X(!0),_n();return}ne(!0);try{const te=await Ur(void 0,l);M(te),$(l),X(!0),_n()}catch(te){const we=Se(te);n(we?`Failed to load agents: ${we}`:"Failed to load agents","error"),X(!1)}finally{ne(!1)}},[O.length,D,l,n,_n]),Ns=(Q?O.find(te=>te.id===Q):void 0)?.name??Q,ys=Zt?Pe.find(te=>te.id===Zt):void 0,cs=y,ss=i.useCallback(()=>{S(te=>{const we=!te;return b(we),we})},[]);return t.jsxs("div",{className:`quick-entry-box ${y?"quick-entry-box--expanded":"quick-entry-box--collapsed"}`,"data-testid":"quick-entry-box",children:[t.jsx("div",{className:"description-with-refine",children:t.jsxs("div",{className:"quick-entry-main-row",children:[t.jsx("div",{className:"quick-entry-textarea-wrap",children:t.jsx("textarea",{ref:j,className:`quick-entry-input ${v?"quick-entry-input--expanded":""}`,placeholder:g?"Creating...":"Add a task...",value:f,onChange:te=>p(te.target.value),onKeyDown:de,onPaste:Zn,onFocus:ot,onBlur:nt,disabled:g||Kt,"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(Li,{size:14}):t.jsx(gn,{size:14})})]})}),t.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!cs,"aria-hidden":!cs,children:[cs&&!g&&t.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:Ht,onMouseDown:te=>te.preventDefault(),disabled:!f.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[t.jsx(Oi,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:On,onMouseDown:te=>te.preventDefault(),disabled:!f.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[t.jsx(vc,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),t.jsxs("div",{className:"refine-trigger-wrap",ref:Lt,children:[t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${We?"refine-button--loading":""}`,onClick:()=>{at(te=>{const we=!te;return we?Mt():bt(null),we})},disabled:!f.trim()||We,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(ms,{size:12,style:{verticalAlign:"middle"}}),We?"Refining...":"Refine"]}),Ke&&be&&Gt&&$a.createPortal(t.jsxs("div",{ref:Bt,className:"refine-menu refine-menu--portal",onMouseDown:te=>te.preventDefault(),style:{position:"fixed",top:`${Gt.top}px`,left:`${Gt.left}px`},children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>as("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:()=>as("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:()=>as("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:()=>as("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"})]})]}),be)]}),t.jsx("div",{className:"dep-trigger-wrap",children:t.jsxs("button",{ref:Fe,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{A(te=>{const we=!te;return we?(Z(!1),St(null),q(null),X(!1),tt(null),ke(!1),Me(null),ye(!1),dt(null),Xt()):Ze(null),we})},children:[t.jsx(Sr,{size:12,style:{verticalAlign:"middle"}}),_.length>0?`${_.length} deps`:"Deps"]})}),U&&be&&me&&(()=>{const te=T.toLowerCase(),we=(te?s.filter(P=>P.id.toLowerCase().includes(te)||P.title&&P.title.toLowerCase().includes(te)||P.description&&P.description.toLowerCase().includes(te)):[...s]).sort((P,Ce)=>{const qe=Ce.createdAt.localeCompare(P.createdAt);if(qe!==0)return qe;const et=parseInt(P.id.slice(P.id.lastIndexOf("-")+1),10)||0;return(parseInt(Ce.id.slice(Ce.id.lastIndexOf("-")+1),10)||0)-et});return $a.createPortal(t.jsxs("div",{ref:J,className:"dep-dropdown dep-dropdown--portal",onMouseDown:P=>P.preventDefault(),style:{position:"fixed",top:`${me.top}px`,left:`${me.left}px`,width:`${me.width}px`,maxHeight:me.maxHeight?`${me.maxHeight}px`:void 0,overflowY:me.maxHeight?"auto":void 0},children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:T,onChange:P=>H(P.target.value),onClick:P=>P.stopPropagation()}),we.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):we.map(P=>t.jsxs("div",{className:`dep-dropdown-item${_.includes(P.id)?" selected":""}`,onMouseDown:Ce=>Ce.preventDefault(),onClick:()=>_t(P.id),children:[t.jsx("span",{className:"dep-dropdown-id",children:P.id}),t.jsx("span",{className:"dep-dropdown-title",children:Wn(P.title||P.description||P.id,60)})]},P.id))]}),be)})(),t.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>C.current?.click(),children:[t.jsx(ab,{size:12,style:{verticalAlign:"middle"}}),R.length>0?`Attach (${R.length})`:"Attach"]}),t.jsxs("button",{ref:Re,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{A(!1),X(!1),tt(null),ke(!1),Me(null),ye(!1),dt(null),q(null),Z(!0),Oe()},children:[t.jsx(Io,{size:12,style:{verticalAlign:"middle"}}),_e]}),t.jsx("div",{className:"node-trigger-wrap",ref:ue,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-node-button",onClick:()=>{A(!1),X(!1),tt(null),Z(!1),St(null),q(null),ye(!1),dt(null),ke(te=>{const we=!te;return we?Pn():Me(null),we})},children:[t.jsx(To,{size:12,style:{verticalAlign:"middle"}}),` ${ys?.name??"Node"}`,ys&&t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(Ua,{status:ys.status,showLabel:!0})})]})}),le&&be&&xt&&$a.createPortal(t.jsxs("div",{ref:oe,className:"dep-dropdown node-picker-dropdown node-picker-dropdown--portal",onMouseDown:te=>te.preventDefault(),style:{position:"fixed",top:`${xt.top}px`,left:`${xt.left}px`,width:`${xt.width}px`,maxHeight:xt.maxHeight?`${xt.maxHeight}px`:void 0,overflowY:xt.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${Zt==null?" selected":""}`,onMouseDown:te=>te.preventDefault(),onClick:()=>{ve(void 0),ke(!1),Me(null)},children:t.jsx("span",{className:"node-picker-item-name",children:"Project default / local"})}),Pe.map(te=>t.jsxs("div",{className:`dep-dropdown-item node-picker-item${Zt===te.id?" selected":""}`,onMouseDown:we=>we.preventDefault(),onClick:()=>{ve(te.id),ke(!1),Me(null)},children:[t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(Ua,{status:te.status})}),t.jsx("span",{className:"node-picker-item-name",children:te.name}),t.jsx("span",{className:"node-picker-item-status",children:UE(te.status)})]},te.id))]}),be),t.jsx("div",{className:"agent-trigger-wrap",ref:ct,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{k?(X(!1),tt(null)):(ke(!1),Me(null),ye(!1),dt(null),In())},"data-testid":"quick-entry-agent-button",children:[t.jsx(Qn,{size:12,style:{verticalAlign:"middle"}}),Ns?` ${Ns}`:" Agent"]})}),k&&be&&ht&&$a.createPortal(t.jsxs("div",{ref:Ue,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:te=>te.preventDefault(),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:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),je&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!je&&O.map(te=>t.jsxs("div",{className:`dep-dropdown-item${Q===te.id?" selected":""}`,onMouseDown:we=>we.preventDefault(),onClick:()=>{se(te.id===Q?null:te.id),X(!1),tt(null)},children:[t.jsx(Qn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:te.role}),t.jsx("span",{className:"dep-dropdown-title",children:te.name})]},te.id)),!je&&O.length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),Q&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:te=>te.preventDefault(),onClick:()=>{se(null),X(!1),tt(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),be),t.jsx("div",{className:"priority-trigger-wrap",ref:Ee,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-priority-button",onClick:()=>{A(!1),X(!1),tt(null),ke(!1),Me(null),Z(!1),St(null),q(null),ye(te=>{const we=!te;return we?kn():dt(null),we})},children:[t.jsx(Mw,{size:12,style:{verticalAlign:"middle"}}),` ${Qt[0].toUpperCase()}${Qt.slice(1)}`]})}),He&&be&&Ye&&$a.createPortal(t.jsxs("div",{ref:ft,className:"dep-dropdown priority-picker-dropdown priority-picker-dropdown--portal",onMouseDown:te=>te.preventDefault(),style:{position:"fixed",top:`${Ye.top}px`,left:`${Ye.left}px`,width:`${Ye.width}px`,maxHeight:Ye.maxHeight?`${Ye.maxHeight}px`:void 0,overflowY:Ye.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select priority"}),wa.map(te=>{const we=`${te[0].toUpperCase()}${te.slice(1)}`;return t.jsx("div",{className:`dep-dropdown-item${Qt===te?" selected":""}`,"data-testid":`quick-entry-priority-option-${te}`,onMouseDown:P=>P.preventDefault(),onClick:()=>{hn(te),ye(!1),dt(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:we})},te)})]}),be),t.jsx("button",{type:"button",className:`btn btn-sm ${xn?"btn-primary":""}`,onClick:()=>qt(te=>!te),onMouseDown:te=>te.preventDefault(),"aria-pressed":xn,"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:Fn,onMouseDown:te=>te.preventDefault(),disabled:!f.trim()||g,"data-testid":"quick-entry-save",title:"Create task",children:[t.jsx(ob,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),R.length>0&&t.jsx("div",{className:"inline-create-previews",children:R.map((te,we)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:te.previewUrl,alt:te.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>vn(we),disabled:g,title:"Remove image","data-testid":`quick-entry-preview-remove-${we}`,children:"×"})]},te.previewUrl))}),fe&&be&&wt&&$a.createPortal(t.jsx("div",{ref:Le,className:"model-nested-menu model-nested-menu--portal",onMouseDown:te=>te.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${wt.top}px`,left:`${wt.left}px`,width:`${wt.width}px`,maxHeight:wt.maxHeight?`${wt.maxHeight}px`:void 0,overflowY:wt.maxHeight?"auto":void 0},children:re===null?t.jsxs("div",{className:"model-menu-items",children:[t.jsxs("button",{type:"button",className:`model-menu-item ${W?"model-menu-item--active":""}`,onClick:()=>q("plan"),"data-testid":"model-menu-plan",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Oi,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),t.jsx("span",{className:"model-menu-item-value",children:W?ut(Te,Be):"Using default"}),t.jsx(qn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${tn?"model-menu-item--active":""}`,onClick:()=>q("executor"),"data-testid":"model-menu-executor",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(ms,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),t.jsx("span",{className:"model-menu-item-value",children:tn?ut(L,he):"Using default"}),t.jsx(qn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${Ne?"model-menu-item--active":""}`,onClick:()=>q("validator"),"data-testid":"model-menu-validator",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Io,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Reviewer"]}),t.jsx("span",{className:"model-menu-item-value",children:Ne?ut(pe,ae):"Using default"}),t.jsx(qn,{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:()=>q(null),"data-testid":"model-submenu-back",children:[t.jsx(gn,{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(_s,{models:st,value:re==="plan"?Jt:re==="executor"?Sn:dn,onChange:re==="plan"?Vn:re==="executor"?$s:vs,placeholder:"Using default",disabled:gt,id:`model-${re}-select`,label:`${re} model`,favoriteProviders:Ot,onToggleFavorite:As,favoriteModels:en,onToggleModelFavorite:bn}),Ie&&t.jsxs("div",{className:"model-submenu-error",children:[t.jsx("span",{children:Ie}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:Rs,children:"Retry"})]})]})}),be)]}),t.jsx("input",{ref:C,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:te=>{yn(te.target.files),te.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),t.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function HE(e){return Ju(e)||e}function qE(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 VE(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 w=g.worktree,v=o.get(w)||[];v.push(g),o.set(w,v)}const l=new Map(n.map(g=>[g.id,g])),d=n.filter(g=>g.column==="todo").filter(g=>!g.paused&&(g.dependencies||[]).every(w=>{const v=l.get(w);return v&&(v.column==="done"||v.column==="in-review"||v.column==="archived")})),m=qE(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:HE(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 Gh=100,sd=50,Kh=25;function WE({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:w,onUnarchiveTask:v,onDeleteTask:b,onArchiveAllDone:y,collapsed:S,onToggleCollapse:j,allTasks:C,availableModels:x,onPlanningMode:N,onSubtaskBreakdown:R,onOpenDetailWithTab:F,favoriteProviders:E,favoriteModels:_,onToggleFavorite:K,onToggleModelFavorite:U,isSearchActive:A,taskStuckTimeoutMs:T,onOpenMission:H,lastFetchTimeMs:Q,workflowStepNameLookup:se,blockerFanoutMap:O}){const[M,D]=i.useState(!1),[$,k]=i.useState(sd),[X,le]=i.useState(!1),[ke,He]=i.useState(!1),[ye,je]=i.useState(!1),[ne,fe]=i.useState(!1),Z=i.useRef(null),re=qC(n.length),{confirm:q}=li();i.useEffect(()=>{if(!X)return;function Ee(ht){Z.current?.contains(ht.target)||le(!1)}function ft(ht){ht.key==="Escape"&&le(!1)}return document.addEventListener("mousedown",Ee),document.addEventListener("keydown",ft),()=>{document.removeEventListener("mousedown",Ee),document.removeEventListener("keydown",ft)}},[X]);const L=e==="archived",xe=L&&S,he=!L&&!A&&e!=="in-progress"&&n.length>Gh;i.useEffect(()=>{k(Ee=>e==="in-progress"||L||n.length<=Gh?sd:Math.min(Math.max(Ee,sd),n.length))},[e,L,n.length]);const B=i.useCallback(Ee=>{L||(Ee.preventDefault(),Ee.dataTransfer.dropEffect="move",D(!0))},[L]),pe=i.useCallback(Ee=>{Ee.currentTarget.contains(Ee.relatedTarget)||D(!1)},[]),ze=i.useCallback(async Ee=>{Ee.preventDefault(),D(!1);const ft=Ee.dataTransfer.getData("text/plain");if(!ft)return;const ht=n.find(tt=>tt.id===ft);if(!(ht&&ht.column===e))try{const xt=(C?.find(dt=>dt.id===ft)??ht)?.steps.some(dt=>dt.status!=="pending")??!1,Me=(e==="todo"||e==="triage")&&xt;let Ye;if(Me){if(await q({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Ye={preserveProgress:!0};else if(!await q({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await r(ft,e,Ye)}catch(tt){c(Se(tt),"error")}},[c,C,e,q,r,n]),ae=i.useMemo(()=>e!=="in-progress"?[]:VE(n,n,a),[e,n,a]),Ve=i.useMemo(()=>he?n.slice(0,$):n,[he,n,$]),Te=Math.max(0,n.length-Ve.length),rt=i.useCallback(()=>{k(Ee=>Math.min(Ee+Kh,n.length))},[n.length]),Be=i.useCallback(async()=>{if(le(!1),!(n.length===0||!await q({title:"Replan All Tasks",message:`Move all ${n.length} todo task${n.length===1?"":"s"} back to planning to be replanned?`}))){He(!0);try{const ft=await Promise.allSettled(n.map(xt=>r(xt.id,"triage"))),ht=ft.filter(xt=>xt.status==="rejected").length,tt=ft.length-ht;ht===0?c(`Moved ${tt} task${tt===1?"":"s"} to planning for replanning`,"success"):c(`Moved ${tt} of ${ft.length} tasks; ${ht} failed`,"error")}finally{He(!1)}}},[n,r,c,q]),ce=i.useMemo(()=>n.filter(Ee=>!Ee.paused&&!Ee.assignedAgentId),[n]),Re=ce.length,Le=e==="todo"||e==="in-progress"||e==="in-review",ct=ke||ye||ne,Ue=i.useCallback(async()=>{if(!(!o||(le(!1),Re===0)||!await q({title:"Stop All Tasks",message:`Stop all ${Re} ${hs[e].toLowerCase()} task${Re===1?"":"s"}?`,danger:!0}))){je(!0);try{const ft=await Promise.allSettled(ce.map(xt=>o(xt.id))),ht=ft.filter(xt=>xt.status==="rejected").length,tt=ft.length-ht;ht===0?c(`Stopped ${tt} task${tt===1?"":"s"}`,"success"):c(`Stopped ${tt} of ${ft.length} tasks; ${ht} failed`,"error")}finally{je(!1)}}},[o,Re,e,ce,c,q]),ue=i.useCallback(async()=>{if(le(!1),n.length===0||!await q({title:"Move All to Todo",message:`Move all ${n.length} ${hs[e].toLowerCase()} task${n.length===1?"":"s"} to Todo?`}))return;const ft=n.some(tt=>tt.steps.some(xt=>xt.status!=="pending"));let ht=!1;if(ft){if(await q({title:"Preserve Progress?",message:"Some tasks have completed steps. Keep progress before moving to Todo?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))ht=!0;else if(!await q({title:"Reset Progress?",message:"Reset step progress for tasks before moving to Todo?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}fe(!0);try{const tt=await Promise.allSettled(n.map(Ye=>r(Ye.id,"todo",ht?{preserveProgress:!0}:void 0))),xt=tt.filter(Ye=>Ye.status==="rejected").length,Me=tt.length-xt;xt===0?c(`Moved ${Me} task${Me===1?"":"s"} to Todo`,"success"):c(`Moved ${Me} of ${tt.length} tasks to Todo; ${xt} failed`,"error")}finally{fe(!1)}},[n,e,r,c,q]),oe=i.useCallback(async()=>{if(!(!y||n.length===0||!await q({title:"Archive All Done",message:`Archive all ${n.length} done tasks?`,danger:!0})))try{const ft=await y();c(`Archived ${ft.length} tasks`,"success")}catch(ft){c(Se(ft)||"Failed to archive tasks","error")}},[y,n.length,c,q]);return t.jsxs("div",{className:`column${M?" drag-over":""}${L?" column-archived":""}${xe?" column-collapsed":""}`,"data-column":e,onDragOver:B,onDragLeave:pe,onDrop:ze,children:[t.jsxs("div",{className:"column-header",children:[t.jsx("div",{className:`column-dot dot-${e}`}),t.jsx("h2",{children:hs[e]}),t.jsx("span",{className:`column-count${re?" 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:oe,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:t.jsx(zo,{})}),L&&j&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:j,title:S?"Expand archived tasks":"Collapse archived tasks","aria-label":S?"Expand archived tasks":"Collapse archived tasks",children:S?t.jsx(gn,{size:16}):t.jsx(Li,{size:16})}),Le&&t.jsxs("div",{className:"column-menu",ref:Z,children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>le(Ee=>!Ee),"aria-haspopup":"menu","aria-expanded":X,"aria-label":`${hs[e]} column actions`,title:"Column actions",disabled:ct,children:t.jsx(dw,{})}),X&&t.jsxs("div",{className:"column-menu-popover",role:"menu",children:[e==="todo"&&t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Be(),disabled:n.length===0||ke,children:["Replan All",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Planning"]})]}),(e==="in-progress"||e==="in-review")&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Ue(),disabled:Re===0||ye||!o,children:["Stop All",t.jsx("span",{className:"column-menu-item-hint",children:n.length===0?"No tasks in this column":Re===0?"No manually pausable tasks":`Pause ${Re} active unassigned task${Re===1?"":"s"}`})]}),t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void ue(),disabled:n.length===0||ne,children:["Move All to Todo",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Todo"]})]})]})]})]})]}),!xe&&t.jsx("p",{className:"column-desc",children:UC[e]}),!xe&&t.jsxs("div",{className:"column-body",children:[e==="triage"&&d&&t.jsx(Qb,{onCreate:d,addToast:c,tasks:C??[],availableModels:x,onPlanningMode:N,onSubtaskBreakdown:R,projectId:s,autoExpand:!1,favoriteProviders:E,favoriteModels:_,onToggleFavorite:K,onToggleModelFavorite:U}),e==="in-progress"?ae.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):ae.map(Ee=>t.jsx(Yb,{label:Ee.label,activeTasks:Ee.activeTasks,queuedTasks:Ee.queuedTasks,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onOpenDetailWithTab:F,taskStuckTimeoutMs:T,onOpenMission:H,lastFetchTimeMs:Q,workflowStepNameLookup:se,blockerFanoutMap:O},Ee.label)):n.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):t.jsxs(t.Fragment,{children:[Ve.map(Ee=>t.jsx(Do,{task:Ee,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:w,onUnarchiveTask:v,onDeleteTask:b,onOpenDetailWithTab:F,taskStuckTimeoutMs:T,onOpenMission:H,onMoveTask:r,lastFetchTimeMs:Q,workflowStepNameLookup:se,fanout:O?.get(Ee.id)},Ee.id)),he&&Te>0&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:rt,children:["Load ",Math.min(Kh,Te)," more (",Te," remaining)"]})]}),t.jsx(pa,{slotId:"board-column-footer",projectId:s})]})]})}const Xb=i.memo(WE);Xb.displayName="Column";const GE=new Set(["in-progress","in-review"]),KE=new Set(["triage","todo","in-progress","in-review"]);function JE(e,n){return!e||e.column==="done"||e.column==="archived"||e.column==="in-review"&&e.paused===!0||e.column==="in-review"&&e.status==="failed"&&(e.mergeRetries??0)>=n}function YE(e,n){const s=Date.parse(e.columnMovedAt??e.updatedAt);return Number.isFinite(s)?Math.max(0,n-s):0}function QE(e,n,s={}){const a=s.nowMs??Date.now(),r=s.highFanoutTodoThreshold??Xu,o=s.staleHighFanoutAgeThresholdMs??Lb,l=new Map(e.map(m=>[m.id,m])),c=new Map,d=m=>{let h=c.get(m);return h||(h={dependentIds:[],blockedByDependentIds:[],activeCount:0,activeTodoCount:0},c.set(m,h)),h};for(const m of e){const h=KE.has(m.column),f=m.column==="todo";for(const p of m.dependencies??[]){if(!p)continue;const g=d(p);g.dependentIds.push(m.id),h&&(g.activeCount+=1),f&&(g.activeTodoCount+=1)}if(m.blockedBy){const p=d(m.blockedBy);p.dependentIds.push(m.id),p.blockedByDependentIds.push(m.id),h&&(p.activeCount+=1),f&&(p.activeTodoCount+=1)}}const u=new Map;for(const[m,h]of c){const f=l.get(m),p=JE(f,n)?[...h.blockedByDependentIds]:[],g=h.activeTodoCount>=r,w=f?YE(f,a):0,v=f?.column,b=v!==void 0&&g&&GE.has(v)&&w>=o;u.set(m,{totalCount:h.activeCount,activeTodoCount:h.activeTodoCount,dependentIds:h.dependentIds,staleBlockedByDependentIds:p,isHighFanout:g,escalation:b?{blockerId:m,activeTodoCount:h.activeTodoCount,totalActiveCount:h.activeCount,blockingAgeMs:w}:void 0})}return u}const XE=3;function tm(e,n={}){return QE(e,XE,{staleHighFanoutAgeThresholdMs:n.staleHighFanoutAgeThresholdMs})}function ZE(e,n={}){return i.useMemo(()=>tm(e,n),[e,n.staleHighFanoutAgeThresholdMs])}function e_(e,n){return e.length!==n.length?!1:e.every((s,a)=>s===n[a])}const Jh=new Map;function t_(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 n_({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:w,onDeleteTask:v,onArchiveAllDone:b,onLoadArchivedTasks:y,searchQuery:S="",availableModels:j,onPlanningMode:C,onSubtaskBreakdown:x,onOpenDetailWithTab:N,favoriteProviders:R,favoriteModels:F,onToggleFavorite:E,onToggleModelFavorite:_,taskStuckTimeoutMs:K,onOpenMission:U,staleHighFanoutBlockerAgeThresholdMs:A,lastFetchTimeMs:T}){const[H,Q]=i.useState(!0),se=i.useRef(!1),{fetchBatch:O}=eE(n),M=i.useRef(null),[D,$]=i.useState(Jh),k=ZE(e,{staleHighFanoutAgeThresholdMs:A}),X=S.trim()!=="",le=i.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),ke=i.useCallback(()=>{Q(je=>{const ne=!je;return!ne&&!se.current&&y&&(se.current=!0,y()),ne})},[y]),He=i.useMemo(()=>{const je={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};for(const Z of e){const re=Qu(Z.column)?Z.column:Xl;(je[re]??je[Xl]).push(Z)}const ne=le.current,fe={};for(const Z of ha){const re=Ob(je[Z],Z);fe[Z]=e_(ne[Z],re)?ne[Z]:re}return le.current=fe,fe},[e]);i.useEffect(()=>{let je=!1;return Ko(n).then(ne=>{if(je)return;const fe=new Map(ne.map(Z=>[Z.id,Z.name]));$(Z=>t_(Z,fe)?Z:fe)}).catch(()=>{je||$(ne=>ne.size===0?ne:Jh)}),()=>{je=!0}},[n]);const ye=i.useMemo(()=>e.filter(je=>je.prInfo||je.issueInfo).map(je=>je.id),[e]);return i.useEffect(()=>{if(ye.length!==0)return M.current&&clearTimeout(M.current),M.current=setTimeout(()=>{const je=[];for(let ne=0;ne<ye.length;ne+=50)je.push(ye.slice(ne,ne+50));je.forEach(ne=>{O(ne)})},500),()=>{M.current&&clearTimeout(M.current)}},[ye,O]),t.jsx(t.Fragment,{children:t.jsx("main",{className:"board",id:"board",children:ha.map(je=>t.jsx(Xb,{column:je,tasks:He[je],projectId:n,maxConcurrent:s,onMoveTask:a,onPauseTask:r,onOpenDetail:o,addToast:l,globalPaused:h,onUpdateTask:f,onRetryTask:p,onArchiveTask:g,onUnarchiveTask:w,onDeleteTask:v,allTasks:e,availableModels:j,onOpenDetailWithTab:N,favoriteProviders:R,favoriteModels:F,onToggleFavorite:E,onToggleModelFavorite:_,isSearchActive:X,taskStuckTimeoutMs:K,onOpenMission:U,lastFetchTimeMs:T,workflowStepNameLookup:D,blockerFanoutMap:k,...je==="triage"?{onQuickCreate:c,onNewTask:d,onPlanningMode:C,onSubtaskBreakdown:x}:{},...je==="in-review"?{autoMerge:u,onToggleAutoMerge:m}:{},...je==="done"?{onArchiveAllDone:b}:{},...je==="archived"?{collapsed:H,onToggleCollapse:ke}:{}},je))})})}function zi(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 s_(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let kr=0,_o=null;function i_(){if(typeof window>"u")return;if(kr>0){kr+=1;return}const e=document.documentElement,n=document.body;_o={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=`-${_o.scrollY}px`,n.style.left="0",n.style.right="0",n.style.width="100%",n.style.overflow="hidden",kr=1}function a_(){if(typeof window>"u"||kr===0||(kr-=1,kr>0||!_o))return;const e=document.documentElement,n=document.body,{htmlOverflow:s,bodyPosition:a,bodyTop:r,bodyLeft:o,bodyRight:l,bodyWidth:c,bodyOverflow:d,scrollY:u}=_o;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,_o=null,window.scrollTo(0,0)}function Mi(e){i.useEffect(()=>{if(!(!e||!s_()))return i_(),()=>{a_()}},[e])}function sa(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 r_(e,n){const s={};return(e[e.length-1]===""?[...e,""]:e).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const o_=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,l_=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,c_={};function Yh(e,n){return(c_.jsx?l_:o_).test(e)}const d_=/[ \t\n\f\r]/g;function u_(e){return typeof e=="object"?e.type==="text"?Qh(e.value):!1:Qh(e)}function Qh(e){return e.replace(d_,"")===""}class Zo{constructor(n,s,a){this.normal=s,this.property=n,a&&(this.space=a)}}Zo.prototype.normal={};Zo.prototype.property={};Zo.prototype.space=void 0;function Zb(e,n){const s={},a={};for(const r of e)Object.assign(s,r.property),Object.assign(a,r.normal);return new Zo(s,a,n)}function gu(e){return e.toLowerCase()}class Xs{constructor(n,s){this.attribute=s,this.property=n}}Xs.prototype.attribute="";Xs.prototype.booleanish=!1;Xs.prototype.boolean=!1;Xs.prototype.commaOrSpaceSeparated=!1;Xs.prototype.commaSeparated=!1;Xs.prototype.defined=!1;Xs.prototype.mustUseProperty=!1;Xs.prototype.number=!1;Xs.prototype.overloadedBoolean=!1;Xs.prototype.property="";Xs.prototype.spaceSeparated=!1;Xs.prototype.space=void 0;let m_=0;const fn=Ka(),ws=Ka(),bu=Ka(),Et=Ka(),Yn=Ka(),jr=Ka(),si=Ka();function Ka(){return 2**++m_}const xu=Object.freeze(Object.defineProperty({__proto__:null,boolean:fn,booleanish:ws,commaOrSpaceSeparated:si,commaSeparated:jr,number:Et,overloadedBoolean:bu,spaceSeparated:Yn},Symbol.toStringTag,{value:"Module"})),id=Object.keys(xu);class nm extends Xs{constructor(n,s,a,r){let o=-1;if(super(n,s),Xh(this,"space",r),typeof a=="number")for(;++o<id.length;){const l=id[o];Xh(this,id[o],(a&xu[l])===xu[l])}}}nm.prototype.defined=!0;function Xh(e,n,s){s&&(e[n]=s)}function qr(e){const n={},s={};for(const[a,r]of Object.entries(e.properties)){const o=new nm(a,e.transform(e.attributes||{},a),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(a)&&(o.mustUseProperty=!0),n[a]=o,s[gu(a)]=a,s[gu(o.attribute)]=a}return new Zo(n,s,e.space)}const ex=qr({properties:{ariaActiveDescendant:null,ariaAtomic:ws,ariaAutoComplete:null,ariaBusy:ws,ariaChecked:ws,ariaColCount:Et,ariaColIndex:Et,ariaColSpan:Et,ariaControls:Yn,ariaCurrent:null,ariaDescribedBy:Yn,ariaDetails:null,ariaDisabled:ws,ariaDropEffect:Yn,ariaErrorMessage:null,ariaExpanded:ws,ariaFlowTo:Yn,ariaGrabbed:ws,ariaHasPopup:null,ariaHidden:ws,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Yn,ariaLevel:Et,ariaLive:null,ariaModal:ws,ariaMultiLine:ws,ariaMultiSelectable:ws,ariaOrientation:null,ariaOwns:Yn,ariaPlaceholder:null,ariaPosInSet:Et,ariaPressed:ws,ariaReadOnly:ws,ariaRelevant:null,ariaRequired:ws,ariaRoleDescription:Yn,ariaRowCount:Et,ariaRowIndex:Et,ariaRowSpan:Et,ariaSelected:ws,ariaSetSize:Et,ariaSort:null,ariaValueMax:Et,ariaValueMin:Et,ariaValueNow:Et,ariaValueText:null,role:null},transform(e,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function tx(e,n){return n in e?e[n]:n}function nx(e,n){return tx(e,n.toLowerCase())}const h_=qr({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:jr,acceptCharset:Yn,accessKey:Yn,action:null,allow:null,allowFullScreen:fn,allowPaymentRequest:fn,allowUserMedia:fn,alt:null,as:null,async:fn,autoCapitalize:null,autoComplete:Yn,autoFocus:fn,autoPlay:fn,blocking:Yn,capture:null,charSet:null,checked:fn,cite:null,className:Yn,cols:Et,colSpan:null,content:null,contentEditable:ws,controls:fn,controlsList:Yn,coords:Et|jr,crossOrigin:null,data:null,dateTime:null,decoding:null,default:fn,defer:fn,dir:null,dirName:null,disabled:fn,download:bu,draggable:ws,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:fn,formTarget:null,headers:Yn,height:Et,hidden:bu,high:Et,href:null,hrefLang:null,htmlFor:Yn,httpEquiv:Yn,id:null,imageSizes:null,imageSrcSet:null,inert:fn,inputMode:null,integrity:null,is:null,isMap:fn,itemId:null,itemProp:Yn,itemRef:Yn,itemScope:fn,itemType:Yn,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:fn,low:Et,manifest:null,max:null,maxLength:Et,media:null,method:null,min:null,minLength:Et,multiple:fn,muted:fn,name:null,nonce:null,noModule:fn,noValidate:fn,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:fn,optimum:Et,pattern:null,ping:Yn,placeholder:null,playsInline:fn,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:fn,referrerPolicy:null,rel:Yn,required:fn,reversed:fn,rows:Et,rowSpan:Et,sandbox:Yn,scope:null,scoped:fn,seamless:fn,selected:fn,shadowRootClonable:fn,shadowRootDelegatesFocus:fn,shadowRootMode:null,shape:null,size:Et,sizes:null,slot:null,span:Et,spellCheck:ws,src:null,srcDoc:null,srcLang:null,srcSet:null,start:Et,step:null,style:null,tabIndex:Et,target:null,title:null,translate:null,type:null,typeMustMatch:fn,useMap:null,value:ws,width:Et,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Yn,axis:null,background:null,bgColor:null,border:Et,borderColor:null,bottomMargin:Et,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:fn,declare:fn,event:null,face:null,frame:null,frameBorder:null,hSpace:Et,leftMargin:Et,link:null,longDesc:null,lowSrc:null,marginHeight:Et,marginWidth:Et,noResize:fn,noHref:fn,noShade:fn,noWrap:fn,object:null,profile:null,prompt:null,rev:null,rightMargin:Et,rules:null,scheme:null,scrolling:ws,standby:null,summary:null,text:null,topMargin:Et,valueType:null,version:null,vAlign:null,vLink:null,vSpace:Et,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:fn,disableRemotePlayback:fn,prefix:null,property:null,results:Et,security:null,unselectable:null},space:"html",transform:nx}),p_=qr({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:si,accentHeight:Et,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:Et,amplitude:Et,arabicForm:null,ascent:Et,attributeName:null,attributeType:null,azimuth:Et,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:Et,by:null,calcMode:null,capHeight:Et,className:Yn,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:Et,diffuseConstant:Et,direction:null,display:null,dur:null,divisor:Et,dominantBaseline:null,download:fn,dx:null,dy:null,edgeMode:null,editable:null,elevation:Et,enableBackground:null,end:null,event:null,exponent:Et,externalResourcesRequired:null,fill:null,fillOpacity:Et,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:jr,g2:jr,glyphName:jr,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:Et,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:Et,horizOriginX:Et,horizOriginY:Et,id:null,ideographic:Et,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:Et,k:Et,k1:Et,k2:Et,k3:Et,k4:Et,kernelMatrix:si,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:Et,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:Et,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:Et,overlineThickness:Et,paintOrder:null,panose1:null,path:null,pathLength:Et,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Yn,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:Et,pointsAtY:Et,pointsAtZ:Et,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:si,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:si,rev:si,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:si,requiredFeatures:si,requiredFonts:si,requiredFormats:si,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:Et,specularExponent:Et,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:Et,strikethroughThickness:Et,string:null,stroke:null,strokeDashArray:si,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:Et,strokeOpacity:Et,strokeWidth:null,style:null,surfaceScale:Et,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:si,tabIndex:Et,tableValues:null,target:null,targetX:Et,targetY:Et,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:si,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:Et,underlineThickness:Et,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:Et,values:null,vAlphabetic:Et,vMathematical:Et,vectorEffect:null,vHanging:Et,vIdeographic:Et,version:null,vertAdvY:Et,vertOriginX:Et,vertOriginY:Et,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:Et,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:tx}),sx=qr({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()}}),ix=qr({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:nx}),ax=qr({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),f_={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"},g_=/[A-Z]/g,Zh=/-[a-z]/g,b_=/^data[-\w.:]+$/i;function x_(e,n){const s=gu(n);let a=n,r=Xs;if(s in e.normal)return e.property[e.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&b_.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(Zh,y_);a="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!Zh.test(o)){let l=o.replace(g_,v_);l.charAt(0)!=="-"&&(l="-"+l),n="data"+l}}r=nm}return new r(a,n)}function v_(e){return"-"+e.toLowerCase()}function y_(e){return e.charAt(1).toUpperCase()}const w_=Zb([ex,h_,sx,ix,ax],"html"),sm=Zb([ex,p_,sx,ix,ax],"svg");function k_(e){return e.join(" ").trim()}var dr={},ad,ep;function j_(){if(ep)return ad;ep=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(v,b){if(typeof v!="string")throw new TypeError("First argument must be a string");if(!v)return[];b=b||{};var y=1,S=1;function j(A){var T=A.match(n);T&&(y+=T.length);var H=A.lastIndexOf(d);S=~H?A.length-H:S+A.length}function C(){var A={line:y,column:S};return function(T){return T.position=new x(A),F(),T}}function x(A){this.start=A,this.end={line:y,column:S},this.source=b.source}x.prototype.content=v;function N(A){var T=new Error(b.source+":"+y+":"+S+": "+A);if(T.reason=A,T.filename=b.source,T.line=y,T.column=S,T.source=v,!b.silent)throw T}function R(A){var T=A.exec(v);if(T){var H=T[0];return j(H),v=v.slice(H.length),T}}function F(){R(s)}function E(A){var T;for(A=A||[];T=_();)T!==!1&&A.push(T);return A}function _(){var A=C();if(!(u!=v.charAt(0)||m!=v.charAt(1))){for(var T=2;h!=v.charAt(T)&&(m!=v.charAt(T)||u!=v.charAt(T+1));)++T;if(T+=2,h===v.charAt(T-1))return N("End of comment missing");var H=v.slice(2,T-2);return S+=2,j(H),v=v.slice(T),S+=2,A({type:f,comment:H})}}function K(){var A=C(),T=R(a);if(T){if(_(),!R(r))return N("property missing ':'");var H=R(o),Q=A({type:p,property:w(T[0].replace(e,h)),value:H?w(H[0].replace(e,h)):h});return R(l),Q}}function U(){var A=[];E(A);for(var T;T=K();)T!==!1&&(A.push(T),E(A));return A}return F(),U()}function w(v){return v?v.replace(c,h):h}return ad=g,ad}var tp;function N_(){if(tp)return dr;tp=1;var e=dr&&dr.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(dr,"__esModule",{value:!0}),dr.default=s;const n=e(j_());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 dr}var no={},np;function S_(){if(np)return no;np=1,Object.defineProperty(no,"__esModule",{value:!0}),no.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 no.camelCase=d,no}var so,sp;function C_(){if(sp)return so;sp=1;var e=so&&so.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=e(N_()),s=S_();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,so=a,so}var E_=C_();const __=Kg(E_),rx=ox("end"),im=ox("start");function ox(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 M_(e){const n=im(e),s=rx(e);if(n&&s)return{start:n,end:s}}function Mo(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?ip(e.position):"start"in e||"end"in e?ip(e):"line"in e||"column"in e?vu(e):""}function vu(e){return ap(e&&e.line)+":"+ap(e&&e.column)}function ip(e){return vu(e&&e.start)+"-"+vu(e&&e.end)}function ap(e){return e&&typeof e=="number"?e:1}class zs 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=Mo(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}}zs.prototype.file="";zs.prototype.name="";zs.prototype.reason="";zs.prototype.message="";zs.prototype.stack="";zs.prototype.column=void 0;zs.prototype.line=void 0;zs.prototype.ancestors=void 0;zs.prototype.cause=void 0;zs.prototype.fatal=void 0;zs.prototype.place=void 0;zs.prototype.ruleId=void 0;zs.prototype.source=void 0;const am={}.hasOwnProperty,A_=new Map,R_=/[A-Z]/g,I_=new Set(["table","tbody","thead","tfoot","tr"]),T_=new Set(["td","th"]),lx="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function P_(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=U_(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=B_(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"?sm:w_,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=cx(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function cx(e,n,s){if(n.type==="element")return $_(e,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return D_(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return O_(e,n,s);if(n.type==="mdxjsEsm")return L_(e,n);if(n.type==="root")return F_(e,n,s);if(n.type==="text")return z_(e,n)}function $_(e,n,s){const a=e.schema;let r=a;n.tagName.toLowerCase()==="svg"&&a.space==="html"&&(r=sm,e.schema=r),e.ancestors.push(n);const o=ux(e,n.tagName,!1),l=H_(e,n);let c=om(e,n);return I_.has(n.tagName)&&(c=c.filter(function(d){return typeof d=="string"?!u_(d):!0})),dx(e,l,o,n),rm(l,c),e.ancestors.pop(),e.schema=a,e.create(n,o,l,s)}function D_(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)}Lo(e,n.position)}function L_(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);Lo(e,n.position)}function O_(e,n,s){const a=e.schema;let r=a;n.name==="svg"&&a.space==="html"&&(r=sm,e.schema=r),e.ancestors.push(n);const o=n.name===null?e.Fragment:ux(e,n.name,!0),l=q_(e,n),c=om(e,n);return dx(e,l,o,n),rm(l,c),e.ancestors.pop(),e.schema=a,e.create(n,o,l,s)}function F_(e,n,s){const a={};return rm(a,om(e,n)),e.create(n,e.Fragment,a,s)}function z_(e,n){return n.value}function dx(e,n,s,a){typeof s!="string"&&s!==e.Fragment&&e.passNode&&(n.node=a)}function rm(e,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(e.children=s)}}function B_(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 U_(e,n){return s;function s(a,r,o,l){const c=Array.isArray(o.children),d=im(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 H_(e,n){const s={};let a,r;for(r in n.properties)if(r!=="children"&&am.call(n.properties,r)){const o=V_(e,r,n.properties[r]);if(o){const[l,c]=o;e.tableCellAlignToStyle&&l==="align"&&typeof c=="string"&&T_.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 q_(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 Lo(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 Lo(e,n.position);else o=a.value===null?!0:a.value;s[r]=o}return s}function om(e,n){const s=[];let a=-1;const r=e.passKeys?new Map:A_;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=cx(e,o,l);c!==void 0&&s.push(c)}return s}function V_(e,n,s){const a=x_(e.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=a.commaSeparated?r_(s):k_(s)),a.property==="style"){let r=typeof s=="object"?s:W_(e,String(s));return e.stylePropertyNameCase==="css"&&(r=G_(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&a.space?f_[a.property]||a.property:a.attribute,s]}}function W_(e,n){try{return __(n,{reactCompat:!0})}catch(s){if(e.ignoreInvalidStyle)return{};const a=s,r=new zs("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=lx+"#cannot-parse-style-attribute",r}}function ux(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=Yh(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=Yh(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(a.type==="Literal"){const r=a.value;return am.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(a);Lo(e)}function Lo(e,n){const s=new zs("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=lx+"#cannot-handle-mdx-estrees-without-createevaluater",s}function G_(e){const n={};let s;for(s in e)am.call(e,s)&&(n[K_(s)]=e[s]);return n}function K_(e){let n=e.replace(R_,J_);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function J_(e){return"-"+e.toLowerCase()}const rd={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"]},Y_={};function lm(e,n){const s=Y_,a=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return mx(e,a,r)}function mx(e,n,s){if(Q_(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 rp(e.children,n,s)}return Array.isArray(e)?rp(e,n,s):""}function rp(e,n,s){const a=[];let r=-1;for(;++r<e.length;)a[r]=mx(e[r],n,s);return a.join("")}function Q_(e){return!!(e&&typeof e=="object")}const op=document.createElement("i");function cm(e){const n="&"+e+";";op.innerHTML=n;const s=op.textContent;return s.charCodeAt(s.length-1)===59&&e!=="semi"||s===n?!1:s}function ai(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 gi(e,n){return e.length>0?(ai(e,e.length,0,n),e):n}const lp={}.hasOwnProperty;function hx(e){const n={};let s=-1;for(;++s<e.length;)X_(n,e[s]);return n}function X_(e,n){let s;for(s in n){const r=(lp.call(e,s)?e[s]:void 0)||(e[s]={}),o=n[s];let l;if(o)for(l in o){lp.call(r,l)||(r[l]=[]);const c=o[l];Z_(r[l],Array.isArray(c)?c:c?[c]:[])}}}function Z_(e,n){let s=-1;const a=[];for(;++s<n.length;)(n[s].add==="after"?e:a).push(n[s]);ai(e,0,0,a)}function px(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 Ei(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const qs=ka(/[A-Za-z]/),Fs=ka(/[\dA-Za-z]/),e2=ka(/[#-'*+\--9=?A-Z^-~]/);function tc(e){return e!==null&&(e<32||e===127)}const yu=ka(/\d/),t2=ka(/[\dA-Fa-f]/),n2=ka(/[!-/:-@[-`{-~]/);function Yt(e){return e!==null&&e<-2}function Kn(e){return e!==null&&(e<0||e===32)}function wn(e){return e===-2||e===-1||e===32}const Ec=ka(/\p{P}|\p{S}/u),qa=ka(/\s/);function ka(e){return n;function n(s){return s!==null&&s>-1&&e.test(String.fromCharCode(s))}}function Vr(e){const n=[];let s=-1,a=0,r=0;for(;++s<e.length;){const o=e.charCodeAt(s);let l="";if(o===37&&Fs(e.charCodeAt(s+1))&&Fs(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 Rn(e,n,s,a){const r=a?a-1:Number.POSITIVE_INFINITY;let o=0;return l;function l(d){return wn(d)?(e.enter(s),c(d)):n(d)}function c(d){return wn(d)&&o++<r?(e.consume(d),c):(e.exit(s),n(d))}}const s2={tokenize:i2};function i2(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"),Rn(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 Yt(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),l)}}const a2={tokenize:r2},cp={tokenize:o2};function r2(e){const n=this,s=[];let a=0,r,o,l;return c;function c(S){if(a<s.length){const j=s[a];return n.containerState=j[1],e.attempt(j[0].continuation,d,u)(S)}return u(S)}function d(S){if(a++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&y();const j=n.events.length;let C=j,x;for(;C--;)if(n.events[C][0]==="exit"&&n.events[C][1].type==="chunkFlow"){x=n.events[C][1].end;break}b(a);let N=j;for(;N<n.events.length;)n.events[N][1].end={...x},N++;return ai(n.events,C+1,0,n.events.slice(j)),n.events.length=N,u(S)}return c(S)}function u(S){if(a===s.length){if(!r)return f(S);if(r.currentConstruct&&r.currentConstruct.concrete)return g(S);n.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return n.containerState={},e.check(cp,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(cp,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}),w(S)}function w(S){if(S===null){v(e.exit("chunkFlow"),!0),b(0),e.consume(S);return}return Yt(S)?(e.consume(S),v(e.exit("chunkFlow")),a=0,n.interrupt=void 0,c):(e.consume(S),w)}function v(S,j){const C=n.sliceStream(S);if(j&&C.push(null),S.previous=o,o&&(o.next=S),o=S,r.defineSkip(S.start),r.write(C),n.parser.lazy[S.start.line]){let x=r.events.length;for(;x--;)if(r.events[x][1].start.offset<l&&(!r.events[x][1].end||r.events[x][1].end.offset>l))return;const N=n.events.length;let R=N,F,E;for(;R--;)if(n.events[R][0]==="exit"&&n.events[R][1].type==="chunkFlow"){if(F){E=n.events[R][1].end;break}F=!0}for(b(a),x=N;x<n.events.length;)n.events[x][1].end={...E},x++;ai(n.events,R+1,0,n.events.slice(N)),n.events.length=x}}function b(S){let j=s.length;for(;j-- >S;){const C=s[j];n.containerState=C[1],C[0].exit.call(n,e)}s.length=S}function y(){r.write([null]),o=void 0,r=void 0,n.containerState._closeFlow=void 0}}function o2(e,n,s){return Rn(e,e.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Rr(e){if(e===null||Kn(e)||qa(e))return 1;if(Ec(e))return 2}function _c(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 wu={name:"attention",resolveAll:l2,tokenize:c2};function l2(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};dp(h,-d),dp(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=gi(u,[["enter",e[a][1],n],["exit",e[a][1],n]])),u=gi(u,[["enter",r,n],["enter",l,n],["exit",l,n],["enter",o,n]]),u=gi(u,_c(n.parser.constructs.insideSpan.null,e.slice(a+1,s),n)),u=gi(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=gi(u,[["enter",e[s][1],n],["exit",e[s][1],n]])):m=0,ai(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 c2(e,n){const s=this.parser.constructs.attentionMarkers.null,a=this.previous,r=Rr(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=Rr(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 dp(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const d2={name:"autolink",tokenize:u2};function u2(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 qs(p)?(e.consume(p),l):p===64?s(p):u(p)}function l(p){return p===43||p===45||p===46||Fs(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||Fs(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||tc(p)?s(p):(e.consume(p),d)}function u(p){return p===64?(e.consume(p),m):e2(p)?(e.consume(p),u):s(p)}function m(p){return Fs(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||Fs(p))&&a++<63){const g=p===45?f:h;return e.consume(p),g}return s(p)}}const el={partial:!0,tokenize:m2};function m2(e,n,s){return a;function a(o){return wn(o)?Rn(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||Yt(o)?n(o):s(o)}}const fx={continuation:{tokenize:p2},exit:f2,name:"blockQuote",tokenize:h2};function h2(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 wn(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(l))}}function p2(e,n,s){const a=this;return r;function r(l){return wn(l)?Rn(e,o,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(fx,n,s)(l)}}function f2(e){e.exit("blockQuote")}const gx={name:"characterEscape",tokenize:g2};function g2(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 n2(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):s(o)}}const bx={name:"characterReference",tokenize:b2};function b2(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=Fs,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=t2,m):(e.enter("characterReferenceValue"),o=7,l=yu,m(h))}function m(h){if(h===59&&r){const f=e.exit("characterReferenceValue");return l===Fs&&!cm(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 up={partial:!0,tokenize:v2},mp={concrete:!0,name:"codeFenced",tokenize:x2};function x2(e,n,s){const a=this,r={partial:!0,tokenize:C};let o=0,l=0,c;return d;function d(x){return u(x)}function u(x){const N=a.events[a.events.length-1];return o=N&&N[1].type==="linePrefix"?N[2].sliceSerialize(N[1],!0).length:0,c=x,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),m(x)}function m(x){return x===c?(l++,e.consume(x),m):l<3?s(x):(e.exit("codeFencedFenceSequence"),wn(x)?Rn(e,h,"whitespace")(x):h(x))}function h(x){return x===null||Yt(x)?(e.exit("codeFencedFence"),a.interrupt?n(x):e.check(up,w,j)(x)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(x))}function f(x){return x===null||Yt(x)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(x)):wn(x)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),Rn(e,p,"whitespace")(x)):x===96&&x===c?s(x):(e.consume(x),f)}function p(x){return x===null||Yt(x)?h(x):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(x))}function g(x){return x===null||Yt(x)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),h(x)):x===96&&x===c?s(x):(e.consume(x),g)}function w(x){return e.attempt(r,j,v)(x)}function v(x){return e.enter("lineEnding"),e.consume(x),e.exit("lineEnding"),b}function b(x){return o>0&&wn(x)?Rn(e,y,"linePrefix",o+1)(x):y(x)}function y(x){return x===null||Yt(x)?e.check(up,w,j)(x):(e.enter("codeFlowValue"),S(x))}function S(x){return x===null||Yt(x)?(e.exit("codeFlowValue"),y(x)):(e.consume(x),S)}function j(x){return e.exit("codeFenced"),n(x)}function C(x,N,R){let F=0;return E;function E(T){return x.enter("lineEnding"),x.consume(T),x.exit("lineEnding"),_}function _(T){return x.enter("codeFencedFence"),wn(T)?Rn(x,K,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(T):K(T)}function K(T){return T===c?(x.enter("codeFencedFenceSequence"),U(T)):R(T)}function U(T){return T===c?(F++,x.consume(T),U):F>=l?(x.exit("codeFencedFenceSequence"),wn(T)?Rn(x,A,"whitespace")(T):A(T)):R(T)}function A(T){return T===null||Yt(T)?(x.exit("codeFencedFence"),N(T)):R(T)}}}function v2(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 od={name:"codeIndented",tokenize:w2},y2={partial:!0,tokenize:k2};function w2(e,n,s){const a=this;return r;function r(u){return e.enter("codeIndented"),Rn(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):Yt(u)?e.attempt(y2,l,d)(u):(e.enter("codeFlowValue"),c(u))}function c(u){return u===null||Yt(u)?(e.exit("codeFlowValue"),l(u)):(e.consume(u),c)}function d(u){return e.exit("codeIndented"),n(u)}}function k2(e,n,s){const a=this;return r;function r(l){return a.parser.lazy[a.now().line]?s(l):Yt(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r):Rn(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):Yt(l)?r(l):s(l)}}const j2={name:"codeText",previous:S2,resolve:N2,tokenize:C2};function N2(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 S2(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function C2(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)):Yt(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||Yt(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 E2{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&&io(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),io(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),io(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);io(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);io(this.left,s.reverse())}}}function io(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 xx(e){const n={};let s=-1,a,r,o,l,c,d,u;const m=new E2(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,_2(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 ai(e,0,Number.POSITIVE_INFINITY,m.slice(0)),!u}function _2(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,w=0;const v=[w];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&&(w=f+1,v.push(w),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(l.events=[],p?(p._tokenizer=void 0,p.previous=void 0):v.pop(),f=v.length;f--;){const b=c.slice(v[f],v[f+1]),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 M2={resolve:R2,tokenize:I2},A2={partial:!0,tokenize:T2};function R2(e){return xx(e),e}function I2(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):Yt(c)?e.check(A2,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 T2(e,n,s){const a=this;return r;function r(l){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),Rn(e,o,"linePrefix")}function o(l){if(l===null||Yt(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 vx(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||tc(b)?s(b):(e.enter(a),e.enter(l),e.enter(c),e.enter("chunkString",{contentType:"string"}),w(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||Yt(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 w(b){return!m&&(b===null||b===41||Kn(b))?(e.exit("chunkString"),e.exit(c),e.exit(l),e.exit(a),n(b)):m<u&&b===40?(e.consume(b),m++,w):b===41?(e.consume(b),m--,w):b===null||b===32||b===40||tc(b)?s(b):(e.consume(b),b===92?v:w)}function v(b){return b===40||b===41||b===92?(e.consume(b),w):w(b)}}function yx(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):Yt(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||Yt(p)||c++>999?(e.exit("chunkString"),m(p)):(e.consume(p),d||(d=!wn(p)),p===92?f:h)}function f(p){return p===91||p===92||p===93?(e.consume(p),c++,h):h(p)}}function wx(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):Yt(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),Rn(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),m(f))}function m(f){return f===l||f===null||Yt(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 Yt(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s=!0,a):wn(r)?Rn(e,a,s?"linePrefix":"lineSuffix")(r):n(r)}}const P2={name:"definition",tokenize:D2},$2={partial:!0,tokenize:L2};function D2(e,n,s){const a=this;let r;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return yx.call(a,e,c,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function c(p){return r=Ei(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 Kn(p)?Ao(e,u)(p):u(p)}function u(p){return vx(e,m,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function m(p){return e.attempt($2,h,h)(p)}function h(p){return wn(p)?Rn(e,f,"whitespace")(p):f(p)}function f(p){return p===null||Yt(p)?(e.exit("definition"),a.parser.defined.push(r),n(p)):s(p)}}function L2(e,n,s){return a;function a(c){return Kn(c)?Ao(e,r)(c):s(c)}function r(c){return wx(e,o,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return wn(c)?Rn(e,l,"whitespace")(c):l(c)}function l(c){return c===null||Yt(c)?n(c):s(c)}}const O2={name:"hardBreakEscape",tokenize:F2};function F2(e,n,s){return a;function a(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return Yt(o)?(e.exit("hardBreakEscape"),n(o)):s(o)}}const z2={name:"headingAtx",resolve:B2,tokenize:U2};function B2(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"},ai(e,a,s-a+1,[["enter",r,n],["enter",o,n],["exit",o,n],["exit",r,n]])),e}function U2(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||Kn(m)?(e.exit("atxHeadingSequence"),c(m)):s(m)}function c(m){return m===35?(e.enter("atxHeadingSequence"),d(m)):m===null||Yt(m)?(e.exit("atxHeading"),n(m)):wn(m)?Rn(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||Kn(m)?(e.exit("atxHeadingText"),c(m)):(e.consume(m),u)}}const H2=["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"],hp=["pre","script","style","textarea"],q2={concrete:!0,name:"htmlFlow",resolveTo:G2,tokenize:K2},V2={partial:!0,tokenize:Y2},W2={partial:!0,tokenize:J2};function G2(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 K2(e,n,s){const a=this;let r,o,l,c,d;return u;function u(k){return m(k)}function m(k){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(k),h}function h(k){return k===33?(e.consume(k),f):k===47?(e.consume(k),o=!0,w):k===63?(e.consume(k),r=3,a.interrupt?n:M):qs(k)?(e.consume(k),l=String.fromCharCode(k),v):s(k)}function f(k){return k===45?(e.consume(k),r=2,p):k===91?(e.consume(k),r=5,c=0,g):qs(k)?(e.consume(k),r=4,a.interrupt?n:M):s(k)}function p(k){return k===45?(e.consume(k),a.interrupt?n:M):s(k)}function g(k){const X="CDATA[";return k===X.charCodeAt(c++)?(e.consume(k),c===X.length?a.interrupt?n:K:g):s(k)}function w(k){return qs(k)?(e.consume(k),l=String.fromCharCode(k),v):s(k)}function v(k){if(k===null||k===47||k===62||Kn(k)){const X=k===47,le=l.toLowerCase();return!X&&!o&&hp.includes(le)?(r=1,a.interrupt?n(k):K(k)):H2.includes(l.toLowerCase())?(r=6,X?(e.consume(k),b):a.interrupt?n(k):K(k)):(r=7,a.interrupt&&!a.parser.lazy[a.now().line]?s(k):o?y(k):S(k))}return k===45||Fs(k)?(e.consume(k),l+=String.fromCharCode(k),v):s(k)}function b(k){return k===62?(e.consume(k),a.interrupt?n:K):s(k)}function y(k){return wn(k)?(e.consume(k),y):E(k)}function S(k){return k===47?(e.consume(k),E):k===58||k===95||qs(k)?(e.consume(k),j):wn(k)?(e.consume(k),S):E(k)}function j(k){return k===45||k===46||k===58||k===95||Fs(k)?(e.consume(k),j):C(k)}function C(k){return k===61?(e.consume(k),x):wn(k)?(e.consume(k),C):S(k)}function x(k){return k===null||k===60||k===61||k===62||k===96?s(k):k===34||k===39?(e.consume(k),d=k,N):wn(k)?(e.consume(k),x):R(k)}function N(k){return k===d?(e.consume(k),d=null,F):k===null||Yt(k)?s(k):(e.consume(k),N)}function R(k){return k===null||k===34||k===39||k===47||k===60||k===61||k===62||k===96||Kn(k)?C(k):(e.consume(k),R)}function F(k){return k===47||k===62||wn(k)?S(k):s(k)}function E(k){return k===62?(e.consume(k),_):s(k)}function _(k){return k===null||Yt(k)?K(k):wn(k)?(e.consume(k),_):s(k)}function K(k){return k===45&&r===2?(e.consume(k),H):k===60&&r===1?(e.consume(k),Q):k===62&&r===4?(e.consume(k),D):k===63&&r===3?(e.consume(k),M):k===93&&r===5?(e.consume(k),O):Yt(k)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(V2,$,U)(k)):k===null||Yt(k)?(e.exit("htmlFlowData"),U(k)):(e.consume(k),K)}function U(k){return e.check(W2,A,$)(k)}function A(k){return e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),T}function T(k){return k===null||Yt(k)?U(k):(e.enter("htmlFlowData"),K(k))}function H(k){return k===45?(e.consume(k),M):K(k)}function Q(k){return k===47?(e.consume(k),l="",se):K(k)}function se(k){if(k===62){const X=l.toLowerCase();return hp.includes(X)?(e.consume(k),D):K(k)}return qs(k)&&l.length<8?(e.consume(k),l+=String.fromCharCode(k),se):K(k)}function O(k){return k===93?(e.consume(k),M):K(k)}function M(k){return k===62?(e.consume(k),D):k===45&&r===2?(e.consume(k),M):K(k)}function D(k){return k===null||Yt(k)?(e.exit("htmlFlowData"),$(k)):(e.consume(k),D)}function $(k){return e.exit("htmlFlow"),n(k)}}function J2(e,n,s){const a=this;return r;function r(l){return Yt(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 Y2(e,n,s){return a;function a(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(el,n,s)}}const Q2={name:"htmlText",tokenize:X2};function X2(e,n,s){const a=this;let r,o,l;return c;function c(M){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(M),d}function d(M){return M===33?(e.consume(M),u):M===47?(e.consume(M),C):M===63?(e.consume(M),S):qs(M)?(e.consume(M),R):s(M)}function u(M){return M===45?(e.consume(M),m):M===91?(e.consume(M),o=0,g):qs(M)?(e.consume(M),y):s(M)}function m(M){return M===45?(e.consume(M),p):s(M)}function h(M){return M===null?s(M):M===45?(e.consume(M),f):Yt(M)?(l=h,Q(M)):(e.consume(M),h)}function f(M){return M===45?(e.consume(M),p):h(M)}function p(M){return M===62?H(M):M===45?f(M):h(M)}function g(M){const D="CDATA[";return M===D.charCodeAt(o++)?(e.consume(M),o===D.length?w:g):s(M)}function w(M){return M===null?s(M):M===93?(e.consume(M),v):Yt(M)?(l=w,Q(M)):(e.consume(M),w)}function v(M){return M===93?(e.consume(M),b):w(M)}function b(M){return M===62?H(M):M===93?(e.consume(M),b):w(M)}function y(M){return M===null||M===62?H(M):Yt(M)?(l=y,Q(M)):(e.consume(M),y)}function S(M){return M===null?s(M):M===63?(e.consume(M),j):Yt(M)?(l=S,Q(M)):(e.consume(M),S)}function j(M){return M===62?H(M):S(M)}function C(M){return qs(M)?(e.consume(M),x):s(M)}function x(M){return M===45||Fs(M)?(e.consume(M),x):N(M)}function N(M){return Yt(M)?(l=N,Q(M)):wn(M)?(e.consume(M),N):H(M)}function R(M){return M===45||Fs(M)?(e.consume(M),R):M===47||M===62||Kn(M)?F(M):s(M)}function F(M){return M===47?(e.consume(M),H):M===58||M===95||qs(M)?(e.consume(M),E):Yt(M)?(l=F,Q(M)):wn(M)?(e.consume(M),F):H(M)}function E(M){return M===45||M===46||M===58||M===95||Fs(M)?(e.consume(M),E):_(M)}function _(M){return M===61?(e.consume(M),K):Yt(M)?(l=_,Q(M)):wn(M)?(e.consume(M),_):F(M)}function K(M){return M===null||M===60||M===61||M===62||M===96?s(M):M===34||M===39?(e.consume(M),r=M,U):Yt(M)?(l=K,Q(M)):wn(M)?(e.consume(M),K):(e.consume(M),A)}function U(M){return M===r?(e.consume(M),r=void 0,T):M===null?s(M):Yt(M)?(l=U,Q(M)):(e.consume(M),U)}function A(M){return M===null||M===34||M===39||M===60||M===61||M===96?s(M):M===47||M===62||Kn(M)?F(M):(e.consume(M),A)}function T(M){return M===47||M===62||Kn(M)?F(M):s(M)}function H(M){return M===62?(e.consume(M),e.exit("htmlTextData"),e.exit("htmlText"),n):s(M)}function Q(M){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(M),e.exit("lineEnding"),se}function se(M){return wn(M)?Rn(e,O,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(M):O(M)}function O(M){return e.enter("htmlTextData"),l(M)}}const dm={name:"labelEnd",resolveAll:nM,resolveTo:sM,tokenize:iM},Z2={tokenize:aM},eM={tokenize:rM},tM={tokenize:oM};function nM(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&&ai(e,0,e.length,s),e}function sM(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=gi(c,e.slice(o+1,o+a+3)),c=gi(c,[["enter",m,n]]),c=gi(c,_c(n.parser.constructs.insideSpan.null,e.slice(o+a+4,l-3),n)),c=gi(c,[["exit",m,n],e[l-2],e[l-1],["exit",u,n]]),c=gi(c,e.slice(l+1)),c=gi(c,[["exit",d,n]]),ai(e,o,e.length,c),e}function iM(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(Ei(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(Z2,m,l?m:h)(f):f===91?e.attempt(eM,m,l?u:h)(f):l?m(f):h(f)}function u(f){return e.attempt(tM,m,h)(f)}function m(f){return n(f)}function h(f){return o._balanced=!0,s(f)}}function aM(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 Kn(h)?Ao(e,o)(h):o(h)}function o(h){return h===41?m(h):vx(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function l(h){return Kn(h)?Ao(e,d)(h):m(h)}function c(h){return s(h)}function d(h){return h===34||h===39||h===40?wx(e,u,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):m(h)}function u(h){return Kn(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 rM(e,n,s){const a=this;return r;function r(c){return yx.call(a,e,o,l,"reference","referenceMarker","referenceString")(c)}function o(c){return a.parser.defined.includes(Ei(a.sliceSerialize(a.events[a.events.length-1][1]).slice(1,-1)))?n(c):s(c)}function l(c){return s(c)}}function oM(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 lM={name:"labelStartImage",resolveAll:dm.resolveAll,tokenize:cM};function cM(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 dM={name:"labelStartLink",resolveAll:dm.resolveAll,tokenize:uM};function uM(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 ld={name:"lineEnding",tokenize:mM};function mM(e,n){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),Rn(e,n,"linePrefix")}}const Bl={name:"thematicBreak",tokenize:hM};function hM(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||Yt(u))?(e.exit("thematicBreak"),n(u)):s(u)}function d(u){return u===r?(e.consume(u),a++,d):(e.exit("thematicBreakSequence"),wn(u)?Rn(e,c,"whitespace")(u):c(u))}}const Ks={continuation:{tokenize:bM},exit:vM,name:"list",tokenize:gM},pM={partial:!0,tokenize:yM},fM={partial:!0,tokenize:xM};function gM(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:yu(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(Bl,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 yu(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(el,a.interrupt?s:m,e.attempt(pM,f,h))}function m(p){return a.containerState.initialBlankLine=!0,o++,f(p)}function h(p){return wn(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 bM(e,n,s){const a=this;return a.containerState._closeFlow=void 0,e.check(el,r,o);function r(c){return a.containerState.furtherBlankLines=a.containerState.furtherBlankLines||a.containerState.initialBlankLine,Rn(e,n,"listItemIndent",a.containerState.size+1)(c)}function o(c){return a.containerState.furtherBlankLines||!wn(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(fM,n,l)(c))}function l(c){return a.containerState._closeFlow=!0,a.interrupt=void 0,Rn(e,e.attempt(Ks,n,s),"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function xM(e,n,s){const a=this;return Rn(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 vM(e){e.exit(this.containerState.type)}function yM(e,n,s){const a=this;return Rn(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!wn(o)&&l&&l[1].type==="listItemPrefixWhitespace"?n(o):s(o)}}const pp={name:"setextUnderline",resolveTo:wM,tokenize:kM};function wM(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 kM(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"),wn(u)?Rn(e,d,"lineSuffix")(u):d(u))}function d(u){return u===null||Yt(u)?(e.exit("setextHeadingLine"),n(u)):s(u)}}const jM={tokenize:NM};function NM(e){const n=this,s=e.attempt(el,a,e.attempt(this.parser.constructs.flowInitial,r,Rn(e,e.attempt(this.parser.constructs.flow,r,e.attempt(M2,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 SM={resolveAll:jx()},CM=kx("string"),EM=kx("text");function kx(e){return{resolveAll:jx(e==="text"?_M: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 jx(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 _M(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 MM={42:Ks,43:Ks,45:Ks,48:Ks,49:Ks,50:Ks,51:Ks,52:Ks,53:Ks,54:Ks,55:Ks,56:Ks,57:Ks,62:fx},AM={91:P2},RM={[-2]:od,[-1]:od,32:od},IM={35:z2,42:Bl,45:[pp,Bl],60:q2,61:pp,95:Bl,96:mp,126:mp},TM={38:bx,92:gx},PM={[-5]:ld,[-4]:ld,[-3]:ld,33:lM,38:bx,42:wu,60:[d2,Q2],91:dM,92:[O2,gx],93:dm,95:wu,96:j2},$M={null:[wu,SM]},DM={null:[42,95]},LM={null:[]},OM=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:DM,contentInitial:AM,disable:LM,document:MM,flow:IM,flowInitial:RM,insideSpan:$M,string:TM,text:PM},Symbol.toStringTag,{value:"Module"}));function FM(e,n,s){let a={_bufferIndex:-1,_index:0,line:s&&s.line||1,column:s&&s.column||1,offset:s&&s.offset||0};const r={},o=[];let l=[],c=[];const d={attempt:N(C),check:N(x),consume:y,enter:S,exit:j,interrupt:N(x,{interrupt:!0})},u={code:null,containerState:{},defineSkip:w,events:[],now:g,parser:e,previous:null,sliceSerialize:f,sliceStream:p,write:h};let m=n.tokenize.call(u,d);return n.resolveAll&&o.push(n),u;function h(_){return l=gi(l,_),v(),l[l.length-1]!==null?[]:(R(n,0),u.events=_c(o,u.events,u),u.events)}function f(_,K){return BM(p(_),K)}function p(_){return zM(l,_)}function g(){const{_bufferIndex:_,_index:K,line:U,column:A,offset:T}=a;return{_bufferIndex:_,_index:K,line:U,column:A,offset:T}}function w(_){r[_.line]=_.column,E()}function v(){let _;for(;a._index<l.length;){const K=l[a._index];if(typeof K=="string")for(_=a._index,a._bufferIndex<0&&(a._bufferIndex=0);a._index===_&&a._bufferIndex<K.length;)b(K.charCodeAt(a._bufferIndex));else b(K)}}function b(_){m=m(_)}function y(_){Yt(_)?(a.line++,a.column=1,a.offset+=_===-3?2:1,E()):_!==-1&&(a.column++,a.offset++),a._bufferIndex<0?a._index++:(a._bufferIndex++,a._bufferIndex===l[a._index].length&&(a._bufferIndex=-1,a._index++)),u.previous=_}function S(_,K){const U=K||{};return U.type=_,U.start=g(),u.events.push(["enter",U,u]),c.push(U),U}function j(_){const K=c.pop();return K.end=g(),u.events.push(["exit",K,u]),K}function C(_,K){R(_,K.from)}function x(_,K){K.restore()}function N(_,K){return U;function U(A,T,H){let Q,se,O,M;return Array.isArray(A)?$(A):"tokenize"in A?$([A]):D(A);function D(ke){return He;function He(ye){const je=ye!==null&&ke[ye],ne=ye!==null&&ke.null,fe=[...Array.isArray(je)?je:je?[je]:[],...Array.isArray(ne)?ne:ne?[ne]:[]];return $(fe)(ye)}}function $(ke){return Q=ke,se=0,ke.length===0?H:k(ke[se])}function k(ke){return He;function He(ye){return M=F(),O=ke,ke.partial||(u.currentConstruct=ke),ke.name&&u.parser.constructs.disable.null.includes(ke.name)?le():ke.tokenize.call(K?Object.assign(Object.create(u),K):u,d,X,le)(ye)}}function X(ke){return _(O,M),T}function le(ke){return M.restore(),++se<Q.length?k(Q[se]):H}}}function R(_,K){_.resolveAll&&!o.includes(_)&&o.push(_),_.resolve&&ai(u.events,K,u.events.length-K,_.resolve(u.events.slice(K),u)),_.resolveTo&&(u.events=_.resolveTo(u.events,u))}function F(){const _=g(),K=u.previous,U=u.currentConstruct,A=u.events.length,T=Array.from(c);return{from:A,restore:H};function H(){a=_,u.previous=K,u.currentConstruct=U,u.events.length=A,c=T,E()}}function E(){a.line in r&&a.column<2&&(a.column=r[a.line],a.offset+=r[a.line]-1)}}function zM(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 BM(e,n){let s=-1;const a=[];let r;for(;++s<e.length;){const o=e[s];let l;if(typeof o=="string")l=o;else switch(o){case-5:{l="\r";break}case-4:{l=`
|
|
653
|
+
`;break}case-3:{l=`\r
|
|
654
|
+
`;break}case-2:{l=n?" ":" ";break}case-1:{if(!n&&r)continue;l=" ";break}default:l=String.fromCharCode(o)}r=o===-2,a.push(l)}return a.join("")}function UM(e){const a={constructs:hx([OM,...(e||{}).extensions||[]]),content:r(s2),defined:[],document:r(a2),flow:r(jM),lazy:{},string:r(CM),text:r(EM)};return a;function r(o){return l;function l(c){return FM(a,o,c)}}}function HM(e){for(;!xx(e););return e}const fp=/[\0\t\n\r]/g;function qM(){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(fp.lastIndex=h,u=fp.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 VM=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function WM(e){return e.replace(VM,GM)}function GM(e,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),o=r===120||r===88;return px(s.slice(o?2:1),o?16:10)}return cm(s)||e}const Nx={}.hasOwnProperty;function KM(e,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),JM(s)(HM(UM(s).document().write(qM()(e,n,!0))))}function JM(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(pe),autolinkProtocol:F,autolinkEmail:F,atxHeading:o(L),blockQuote:o(ne),characterEscape:F,characterReference:F,codeFenced:o(fe),codeFencedFenceInfo:l,codeFencedFenceMeta:l,codeIndented:o(fe,l),codeText:o(Z,l),codeTextData:F,data:F,codeFlowValue:F,definition:o(re),definitionDestinationString:l,definitionLabelString:l,definitionTitleString:l,emphasis:o(q),hardBreakEscape:o(xe),hardBreakTrailing:o(xe),htmlFlow:o(he,l),htmlFlowData:F,htmlText:o(he,l),htmlTextData:F,image:o(B),label:l,link:o(pe),listItem:o(ae),listItemValue:f,listOrdered:o(ze,h),listUnordered:o(ze),paragraph:o(Ve),reference:k,referenceString:l,resourceDestinationString:l,resourceTitleString:l,setextHeading:o(L),strong:o(Te),thematicBreak:o(Be)},exit:{atxHeading:d(),atxHeadingSequence:C,autolink:d(),autolinkEmail:je,autolinkProtocol:ye,blockQuote:d(),characterEscapeValue:E,characterReferenceMarkerHexadecimal:le,characterReferenceMarkerNumeric:le,characterReferenceValue:ke,characterReference:He,codeFenced:d(v),codeFencedFence:w,codeFencedFenceInfo:p,codeFencedFenceMeta:g,codeFlowValue:E,codeIndented:d(b),codeText:d(T),codeTextData:E,data:E,definition:d(),definitionDestinationString:j,definitionLabelString:y,definitionTitleString:S,emphasis:d(),hardBreakEscape:d(K),hardBreakTrailing:d(K),htmlFlow:d(U),htmlFlowData:E,htmlText:d(A),htmlTextData:E,image:d(Q),label:O,labelText:se,lineEnding:_,link:d(H),listItem:d(),listOrdered:d(),listUnordered:d(),paragraph:d(),referenceString:X,resourceDestinationString:M,resourceTitleString:D,resource:$,setextHeading:d(R),setextHeadingLineSequence:N,setextHeadingText:x,strong:d(),thematicBreak:d()}};Sx(n,(e||{}).mdastExtensions||[]);const s={};return a;function a(ce){let Re={type:"root",children:[]};const Le={stack:[Re],tokenStack:[],config:n,enter:c,exit:u,buffer:l,resume:m,data:s},ct=[];let Ue=-1;for(;++Ue<ce.length;)if(ce[Ue][1].type==="listOrdered"||ce[Ue][1].type==="listUnordered")if(ce[Ue][0]==="enter")ct.push(Ue);else{const ue=ct.pop();Ue=r(ce,ue,Ue)}for(Ue=-1;++Ue<ce.length;){const ue=n[ce[Ue][0]];Nx.call(ue,ce[Ue][1].type)&&ue[ce[Ue][1].type].call(Object.assign({sliceSerialize:ce[Ue][2].sliceSerialize},Le),ce[Ue][1])}if(Le.tokenStack.length>0){const ue=Le.tokenStack[Le.tokenStack.length-1];(ue[1]||gp).call(Le,void 0,ue[0])}for(Re.position={start:ca(ce.length>0?ce[0][1].start:{line:1,column:1,offset:0}),end:ca(ce.length>0?ce[ce.length-2][1].end:{line:1,column:1,offset:0})},Ue=-1;++Ue<n.transforms.length;)Re=n.transforms[Ue](Re)||Re;return Re}function r(ce,Re,Le){let ct=Re-1,Ue=-1,ue=!1,oe,Ee,ft,ht;for(;++ct<=Le;){const tt=ce[ct];switch(tt[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{tt[0]==="enter"?Ue++:Ue--,ht=void 0;break}case"lineEndingBlank":{tt[0]==="enter"&&(oe&&!ht&&!Ue&&!ft&&(ft=ct),ht=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:ht=void 0}if(!Ue&&tt[0]==="enter"&&tt[1].type==="listItemPrefix"||Ue===-1&&tt[0]==="exit"&&(tt[1].type==="listUnordered"||tt[1].type==="listOrdered")){if(oe){let xt=ct;for(Ee=void 0;xt--;){const Me=ce[xt];if(Me[1].type==="lineEnding"||Me[1].type==="lineEndingBlank"){if(Me[0]==="exit")continue;Ee&&(ce[Ee][1].type="lineEndingBlank",ue=!0),Me[1].type="lineEnding",Ee=xt}else if(!(Me[1].type==="linePrefix"||Me[1].type==="blockQuotePrefix"||Me[1].type==="blockQuotePrefixWhitespace"||Me[1].type==="blockQuoteMarker"||Me[1].type==="listItemIndent"))break}ft&&(!Ee||ft<Ee)&&(oe._spread=!0),oe.end=Object.assign({},Ee?ce[Ee][1].start:tt[1].end),ce.splice(Ee||ct,0,["exit",oe,tt[2]]),ct++,Le++}if(tt[1].type==="listItemPrefix"){const xt={type:"listItem",_spread:!1,start:Object.assign({},tt[1].start),end:void 0};oe=xt,ce.splice(ct,0,["enter",xt,tt[2]]),ct++,Le++,ft=void 0,ht=!0}}}return ce[Re][1]._spread=ue,Le}function o(ce,Re){return Le;function Le(ct){c.call(this,ce(ct),ct),Re&&Re.call(this,ct)}}function l(){this.stack.push({type:"fragment",children:[]})}function c(ce,Re,Le){this.stack[this.stack.length-1].children.push(ce),this.stack.push(ce),this.tokenStack.push([Re,Le||void 0]),ce.position={start:ca(Re.start),end:void 0}}function d(ce){return Re;function Re(Le){ce&&ce.call(this,Le),u.call(this,Le)}}function u(ce,Re){const Le=this.stack.pop(),ct=this.tokenStack.pop();if(ct)ct[0].type!==ce.type&&(Re?Re.call(this,ce,ct[0]):(ct[1]||gp).call(this,ce,ct[0]));else throw new Error("Cannot close `"+ce.type+"` ("+Mo({start:ce.start,end:ce.end})+"): it’s not open");Le.position.end=ca(ce.end)}function m(){return lm(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function f(ce){if(this.data.expectingFirstListItemValue){const Re=this.stack[this.stack.length-2];Re.start=Number.parseInt(this.sliceSerialize(ce),10),this.data.expectingFirstListItemValue=void 0}}function p(){const ce=this.resume(),Re=this.stack[this.stack.length-1];Re.lang=ce}function g(){const ce=this.resume(),Re=this.stack[this.stack.length-1];Re.meta=ce}function w(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function v(){const ce=this.resume(),Re=this.stack[this.stack.length-1];Re.value=ce.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function b(){const ce=this.resume(),Re=this.stack[this.stack.length-1];Re.value=ce.replace(/(\r?\n|\r)$/g,"")}function y(ce){const Re=this.resume(),Le=this.stack[this.stack.length-1];Le.label=Re,Le.identifier=Ei(this.sliceSerialize(ce)).toLowerCase()}function S(){const ce=this.resume(),Re=this.stack[this.stack.length-1];Re.title=ce}function j(){const ce=this.resume(),Re=this.stack[this.stack.length-1];Re.url=ce}function C(ce){const Re=this.stack[this.stack.length-1];if(!Re.depth){const Le=this.sliceSerialize(ce).length;Re.depth=Le}}function x(){this.data.setextHeadingSlurpLineEnding=!0}function N(ce){const Re=this.stack[this.stack.length-1];Re.depth=this.sliceSerialize(ce).codePointAt(0)===61?1:2}function R(){this.data.setextHeadingSlurpLineEnding=void 0}function F(ce){const Le=this.stack[this.stack.length-1].children;let ct=Le[Le.length-1];(!ct||ct.type!=="text")&&(ct=rt(),ct.position={start:ca(ce.start),end:void 0},Le.push(ct)),this.stack.push(ct)}function E(ce){const Re=this.stack.pop();Re.value+=this.sliceSerialize(ce),Re.position.end=ca(ce.end)}function _(ce){const Re=this.stack[this.stack.length-1];if(this.data.atHardBreak){const Le=Re.children[Re.children.length-1];Le.position.end=ca(ce.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(Re.type)&&(F.call(this,ce),E.call(this,ce))}function K(){this.data.atHardBreak=!0}function U(){const ce=this.resume(),Re=this.stack[this.stack.length-1];Re.value=ce}function A(){const ce=this.resume(),Re=this.stack[this.stack.length-1];Re.value=ce}function T(){const ce=this.resume(),Re=this.stack[this.stack.length-1];Re.value=ce}function H(){const ce=this.stack[this.stack.length-1];if(this.data.inReference){const Re=this.data.referenceType||"shortcut";ce.type+="Reference",ce.referenceType=Re,delete ce.url,delete ce.title}else delete ce.identifier,delete ce.label;this.data.referenceType=void 0}function Q(){const ce=this.stack[this.stack.length-1];if(this.data.inReference){const Re=this.data.referenceType||"shortcut";ce.type+="Reference",ce.referenceType=Re,delete ce.url,delete ce.title}else delete ce.identifier,delete ce.label;this.data.referenceType=void 0}function se(ce){const Re=this.sliceSerialize(ce),Le=this.stack[this.stack.length-2];Le.label=WM(Re),Le.identifier=Ei(Re).toLowerCase()}function O(){const ce=this.stack[this.stack.length-1],Re=this.resume(),Le=this.stack[this.stack.length-1];if(this.data.inReference=!0,Le.type==="link"){const ct=ce.children;Le.children=ct}else Le.alt=Re}function M(){const ce=this.resume(),Re=this.stack[this.stack.length-1];Re.url=ce}function D(){const ce=this.resume(),Re=this.stack[this.stack.length-1];Re.title=ce}function $(){this.data.inReference=void 0}function k(){this.data.referenceType="collapsed"}function X(ce){const Re=this.resume(),Le=this.stack[this.stack.length-1];Le.label=Re,Le.identifier=Ei(this.sliceSerialize(ce)).toLowerCase(),this.data.referenceType="full"}function le(ce){this.data.characterReferenceType=ce.type}function ke(ce){const Re=this.sliceSerialize(ce),Le=this.data.characterReferenceType;let ct;Le?(ct=px(Re,Le==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):ct=cm(Re);const Ue=this.stack[this.stack.length-1];Ue.value+=ct}function He(ce){const Re=this.stack.pop();Re.position.end=ca(ce.end)}function ye(ce){E.call(this,ce);const Re=this.stack[this.stack.length-1];Re.url=this.sliceSerialize(ce)}function je(ce){E.call(this,ce);const Re=this.stack[this.stack.length-1];Re.url="mailto:"+this.sliceSerialize(ce)}function ne(){return{type:"blockquote",children:[]}}function fe(){return{type:"code",lang:null,meta:null,value:""}}function Z(){return{type:"inlineCode",value:""}}function re(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function q(){return{type:"emphasis",children:[]}}function L(){return{type:"heading",depth:0,children:[]}}function xe(){return{type:"break"}}function he(){return{type:"html",value:""}}function B(){return{type:"image",title:null,url:"",alt:null}}function pe(){return{type:"link",title:null,url:"",children:[]}}function ze(ce){return{type:"list",ordered:ce.type==="listOrdered",start:null,spread:ce._spread,children:[]}}function ae(ce){return{type:"listItem",spread:ce._spread,checked:null,children:[]}}function Ve(){return{type:"paragraph",children:[]}}function Te(){return{type:"strong",children:[]}}function rt(){return{type:"text",value:""}}function Be(){return{type:"thematicBreak"}}}function ca(e){return{line:e.line,column:e.column,offset:e.offset}}function Sx(e,n){let s=-1;for(;++s<n.length;){const a=n[s];Array.isArray(a)?Sx(e,a):YM(e,a)}}function YM(e,n){let s;for(s in n)if(Nx.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 gp(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+Mo({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+Mo({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+Mo({start:n.start,end:n.end})+") is still open")}function QM(e){const n=this;n.parser=s;function s(a){return KM(a,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function XM(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 ZM(e,n){const s={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,s),[e.applyData(n,s),{type:"text",value:`
|
|
655
|
+
`}]}function eA(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 tA(e,n){const s={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function nA(e,n){const s={type:"element",tagName:"em",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function sA(e,n){const s=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",a=String(n.identifier).toUpperCase(),r=Vr(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 iA(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 aA(e,n){if(e.options.allowDangerousHtml){const s={type:"raw",value:n.value};return e.patch(n,s),e.applyData(n,s)}}function Cx(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 rA(e,n){const s=String(n.identifier).toUpperCase(),a=e.definitionById.get(s);if(!a)return Cx(e,n);const r={src:Vr(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 oA(e,n){const s={src:Vr(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 lA(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 cA(e,n){const s=String(n.identifier).toUpperCase(),a=e.definitionById.get(s);if(!a)return Cx(e,n);const r={href:Vr(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 dA(e,n){const s={href:Vr(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 uA(e,n,s){const a=e.all(n),r=s?mA(s):Ex(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 mA(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=Ex(s[a])}return n}function Ex(e){const n=e.spread;return n??e.children.length>1}function hA(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 pA(e,n){const s={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function fA(e,n){const s={type:"root",children:e.wrap(e.all(n))};return e.patch(n,s),e.applyData(n,s)}function gA(e,n){const s={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function bA(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=im(n.children[1]),d=rx(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 xA(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 vA(e,n){const s={type:"element",tagName:"td",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}const bp=9,xp=32;function yA(e){const n=String(e),s=/\r?\n|\r/g;let a=s.exec(n),r=0;const o=[];for(;a;)o.push(vp(n.slice(r,a.index),r>0,!0),a[0]),r=a.index+a[0].length,a=s.exec(n);return o.push(vp(n.slice(r),r>0,!1)),o.join("")}function vp(e,n,s){let a=0,r=e.length;if(n){let o=e.codePointAt(a);for(;o===bp||o===xp;)a++,o=e.codePointAt(a)}if(s){let o=e.codePointAt(r-1);for(;o===bp||o===xp;)r--,o=e.codePointAt(r-1)}return r>a?e.slice(a,r):""}function wA(e,n){const s={type:"text",value:yA(String(n.value))};return e.patch(n,s),e.applyData(n,s)}function kA(e,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,s),e.applyData(n,s)}const jA={blockquote:XM,break:ZM,code:eA,delete:tA,emphasis:nA,footnoteReference:sA,heading:iA,html:aA,imageReference:rA,image:oA,inlineCode:lA,linkReference:cA,link:dA,listItem:uA,list:hA,paragraph:pA,root:fA,strong:gA,table:bA,tableCell:vA,tableRow:xA,text:wA,thematicBreak:kA,toml:ul,yaml:ul,definition:ul,footnoteDefinition:ul};function ul(){}const _x=-1,Mc=0,Ro=1,nc=2,um=3,mm=4,hm=5,pm=6,Mx=7,Ax=8,yp=typeof self=="object"?self:globalThis,NA=(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 Mc:case _x:return s(l,r);case Ro:{const c=s([],r);for(const d of l)c.push(a(d));return c}case nc:{const c=s({},r);for(const[d,u]of l)c[a(d)]=a(u);return c}case um:return s(new Date(l),r);case mm:{const{source:c,flags:d}=l;return s(new RegExp(c,d),r)}case hm:{const c=s(new Map,r);for(const[d,u]of l)c.set(a(d),a(u));return c}case pm:{const c=s(new Set,r);for(const d of l)c.add(a(d));return c}case Mx:{const{name:c,message:d}=l;return s(new yp[c](d),r)}case Ax: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 yp[o](l),r)};return a},wp=e=>NA(new Map,e)(0),ur="",{toString:SA}={},{keys:CA}=Object,ao=e=>{const n=typeof e;if(n!=="object"||!e)return[Mc,n];const s=SA.call(e).slice(8,-1);switch(s){case"Array":return[Ro,ur];case"Object":return[nc,ur];case"Date":return[um,ur];case"RegExp":return[mm,ur];case"Map":return[hm,ur];case"Set":return[pm,ur];case"DataView":return[Ro,s]}return s.includes("Array")?[Ro,s]:s.includes("Error")?[Mx,s]:[nc,s]},ml=([e,n])=>e===Mc&&(n==="function"||n==="symbol"),EA=(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]=ao(l);switch(c){case Mc:{let m=l;switch(d){case"bigint":c=Ax,m=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+d);m=null;break;case"undefined":return r([_x],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 nc:{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 CA(l))(e||!ml(ao(l[f])))&&m.push([o(f),o(l[f])]);return h}case um:return r([c,l.toISOString()],l);case mm:{const{source:m,flags:h}=l;return r([c,{source:m,flags:h}],l)}case hm:{const m=[],h=r([c,m],l);for(const[f,p]of l)(e||!(ml(ao(f))||ml(ao(p))))&&m.push([o(f),o(p)]);return h}case pm:{const m=[],h=r([c,m],l);for(const f of l)(e||!ml(ao(f)))&&m.push(o(f));return h}}const{message:u}=l;return r([c,{name:d,message:u}],l)};return o},kp=(e,{json:n,lossy:s}={})=>{const a=[];return EA(!(n||s),!!n,new Map,a)(e),a},sc=typeof structuredClone=="function"?(e,n)=>n&&("json"in n||"lossy"in n)?wp(kp(e,n)):structuredClone(e):(e,n)=>wp(kp(e,n));function _A(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 MA(e,n){return"Back to reference "+(e+1)+(n>1?"-"+n:"")}function AA(e){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=e.options.footnoteBackContent||_A,a=e.options.footnoteBackLabel||MA,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=Vr(h.toLowerCase());let p=0;const g=[],w=e.footnoteCounts.get(h);for(;w!==void 0&&++p<=w;){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 v=m[m.length-1];if(v&&v.type==="element"&&v.tagName==="p"){const y=v.children[v.children.length-1];y&&y.type==="text"?y.value+=" ":v.children.push({type:"text",value:" "}),v.children.push(...g)}else m.push(...g);const b={type:"element",tagName:"li",properties:{id:n+"fn-"+f},children:e.wrap(m,!0)};e.patch(u,b),c.push(b)}if(c.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...sc(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 PA;if(typeof e=="function")return Rc(e);if(typeof e=="object")return Array.isArray(e)?RA(e):IA(e);if(typeof e=="string")return TA(e);throw new Error("Expected function, string, or object as test")});function RA(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 IA(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 TA(e){return Rc(n);function n(s){return s&&s.type===e}}function Rc(e){return n;function n(s,a,r){return!!($A(s)&&e.call(this,s,typeof a=="number"?a:void 0,r||void 0))}}function PA(){return!0}function $A(e){return e!==null&&typeof e=="object"&&"type"in e}const Rx=[],DA=!0,ku=!1,LA="skip";function Ix(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=Rx,g,w,v;if((!n||o(d,u,m[m.length-1]||void 0))&&(p=OA(s(d,m)),p[0]===ku))return p;if("children"in d&&d.children){const b=d;if(b.children&&p[0]!==LA)for(w=(a?b.children.length:-1)+l,v=m.concat(b);w>-1&&w<b.children.length;){const y=b.children[w];if(g=c(y,w,v)(),g[0]===ku)return g;w=typeof g[1]=="number"?g[1]:w+l}}return p}}}function OA(e){return Array.isArray(e)?e:typeof e=="number"?[DA,e]:e==null?Rx:[e]}function fm(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),Ix(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 ju={}.hasOwnProperty,FA={};function zA(e,n){const s=n||FA,a=new Map,r=new Map,o=new Map,l={...jA,...s.handlers},c={all:u,applyData:UA,definitionById:a,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:l,one:d,options:s,patch:BA,wrap:qA};return fm(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(ju.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:w,...v}=m,b=sc(v);return b.children=c.all(m),b}return sc(m)}return(c.options.unknownHandler||HA)(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=jp(g.value)),!Array.isArray(g)&&g.type==="element")){const w=g.children[0];w&&w.type==="text"&&(w.value=jp(w.value))}Array.isArray(g)?h.push(...g):h.push(g)}}}return h}}function BA(e,n){e.position&&(n.position=M_(e))}function UA(e,n){let s=n;if(e&&e.data){const a=e.data.hName,r=e.data.hChildren,o=e.data.hProperties;if(typeof a=="string")if(s.type==="element")s.tagName=a;else{const l="children"in s?s.children:[s];s={type:"element",tagName:a,properties:{},children:l}}s.type==="element"&&o&&Object.assign(s.properties,sc(o)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function HA(e,n){const s=n.data||{},a="value"in n&&!(ju.call(s,"hProperties")||ju.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 qA(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 jp(e){let n=0,s=e.charCodeAt(n);for(;s===9||s===32;)n++,s=e.charCodeAt(n);return e.slice(n)}function Np(e,n){const s=zA(e,n),a=s.one(e,void 0),r=AA(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 VA(e,n){return e&&"run"in e?async function(s,a){const r=Np(s,{file:a,...n});await e.run(r,a)}:function(s,a){return Np(s,{file:a,...e||n})}}function Sp(e){if(e)throw e}var cd,Cp;function WA(){if(Cp)return cd;Cp=1;var e=Object.prototype.hasOwnProperty,n=Object.prototype.toString,s=Object.defineProperty,a=Object.getOwnPropertyDescriptor,r=function(u){return typeof Array.isArray=="function"?Array.isArray(u):n.call(u)==="[object Array]"},o=function(u){if(!u||n.call(u)!=="[object Object]")return!1;var m=e.call(u,"constructor"),h=u.constructor&&u.constructor.prototype&&e.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!m&&!h)return!1;var f;for(f in u);return typeof f>"u"||e.call(u,f)},l=function(u,m){s&&m.name==="__proto__"?s(u,m.name,{enumerable:!0,configurable:!0,value:m.newValue,writable:!0}):u[m.name]=m.newValue},c=function(u,m){if(m==="__proto__")if(e.call(u,m)){if(a)return a(u,m).value}else return;return u[m]};return cd=function d(){var u,m,h,f,p,g,w=arguments[0],v=1,b=arguments.length,y=!1;for(typeof w=="boolean"&&(y=w,w=arguments[1]||{},v=2),(w==null||typeof w!="object"&&typeof w!="function")&&(w={});v<b;++v)if(u=arguments[v],u!=null)for(m in u)h=c(w,m),f=c(u,m),w!==f&&(y&&f&&(o(f)||(p=r(f)))?(p?(p=!1,g=h&&r(h)?h:[]):g=h&&o(h)?h:{},l(w,{name:m,newValue:d(y,g,f)})):typeof f<"u"&&l(w,{name:m,newValue:f}));return w},cd}var GA=WA();const dd=Kg(GA);function Nu(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 KA(){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?JA(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 JA(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 Pi={basename:YA,dirname:QA,extname:XA,join:ZA,sep:"/"};function YA(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');tl(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 QA(e){if(tl(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 XA(e){tl(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 ZA(...e){let n=-1,s;for(;++n<e.length;)tl(e[n]),e[n]&&(s=s===void 0?e[n]:s+"/"+e[n]);return s===void 0?".":eR(s)}function eR(e){tl(e);const n=e.codePointAt(0)===47;let s=tR(e,!n);return s.length===0&&!n&&(s="."),s.length>0&&e.codePointAt(e.length-1)===47&&(s+="/"),n?"/"+s:s}function tR(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 tl(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const nR={cwd:sR};function sR(){return"/"}function Su(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function iR(e){if(typeof e=="string")e=new URL(e);else if(!Su(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 aR(e)}function aR(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 ud=["history","path","basename","stem","extname","dirname"];class Tx{constructor(n){let s;n?Su(n)?s={path:n}:typeof n=="string"||rR(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":nR.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let a=-1;for(;++a<ud.length;){const o=ud[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)ud.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?Pi.basename(this.path):void 0}set basename(n){hd(n,"basename"),md(n,"basename"),this.path=Pi.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?Pi.dirname(this.path):void 0}set dirname(n){Ep(this.basename,"dirname"),this.path=Pi.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?Pi.extname(this.path):void 0}set extname(n){if(md(n,"extname"),Ep(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=Pi.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){Su(n)&&(n=iR(n)),hd(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?Pi.basename(this.path,this.extname):void 0}set stem(n){hd(n,"stem"),md(n,"stem"),this.path=Pi.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 zs(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 md(e,n){if(e&&e.includes(Pi.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+Pi.sep+"`")}function hd(e,n){if(!e)throw new Error("`"+n+"` cannot be empty")}function Ep(e,n){if(!e)throw new Error("Setting `"+n+"` requires `path` to be set too")}function rR(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const oR=(function(e){const a=this.constructor.prototype,r=a[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,a),o}),lR={}.hasOwnProperty;class gm extends oR{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=KA()}copy(){const n=new gm;let s=-1;for(;++s<this.attachers.length;){const a=this.attachers[s];n.use(...a)}return n.data(dd(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(gd("data",this.frozen),this.namespace[n]=s,this):lR.call(this.namespace,n)&&this.namespace[n]||void 0:n?(gd("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=hl(n),a=this.parser||this.Parser;return pd("parse",a),a(String(s),s)}process(n,s){const a=this;return this.freeze(),pd("process",this.parser||this.Parser),fd("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(o,l){const c=hl(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);uR(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(),pd("processSync",this.parser||this.Parser),fd("processSync",this.compiler||this.Compiler),this.process(n,r),Mp("processSync","process",s),a;function r(o,l){s=!0,Sp(o),a=l}}run(n,s,a){_p(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=hl(s);r.run(n,d,u);function u(m,h,f){const p=h||n;m?c(m):l?l(p):a(void 0,p,f)}}}runSync(n,s){let a=!1,r;return this.run(n,s,o),Mp("runSync","run",a),r;function o(l,c){Sp(l),r=c,a=!0}}stringify(n,s){this.freeze();const a=hl(s),r=this.compiler||this.Compiler;return fd("stringify",r),_p(n),r(n,a)}use(n,...s){const a=this.attachers,r=this.namespace;if(gd("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=dd(!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 w=a[f][1];Nu(w)&&Nu(p)&&(p=dd(!0,w,p)),a[f]=[u,p,...g]}}}}const cR=new gm().freeze();function pd(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function fd(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function gd(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 _p(e){if(!Nu(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Mp(e,n,s){if(!s)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function hl(e){return dR(e)?e:new Tx(e)}function dR(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function uR(e){return typeof e=="string"||mR(e)}function mR(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const hR="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Ap=[],Rp={allowDangerousHtml:!0},pR=/^(https?|ircs?|mailto|xmpp)$/i,fR=[{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 xi(e){const n=gR(e),s=bR(e);return xR(n.runSync(n.parse(s),s),e)}function gR(e){const n=e.rehypePlugins||Ap,s=e.remarkPlugins||Ap,a=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Rp}:Rp;return cR().use(QM).use(s).use(VA,a).use(n)}function bR(e){const n=e.children||"",s=new Tx;return typeof n=="string"&&(s.value=n),s}function xR(e,n){const s=n.allowedElements,a=n.allowElement,r=n.components,o=n.disallowedElements,l=n.skipHtml,c=n.unwrapDisallowed,d=n.urlTransform||vR;for(const m of fR)Object.hasOwn(n,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+hR+m.id,void 0);return fm(e,u),P_(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 rd)if(Object.hasOwn(rd,p)&&Object.hasOwn(m.properties,p)){const g=m.properties[p],w=rd[p];(w===null||w.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 vR(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||pR.test(e.slice(0,n))?e:""}function Ip(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 yR(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function wR(e,n,s){const r=Ac((s||{}).ignore||[]),o=kR(n);let l=-1;for(;++l<o.length;)Ix(e,"text",c);function c(u,m){let h=-1,f;for(;++h<m.length;){const p=m[h],g=f?f.children:void 0;if(r(p,g?g.indexOf(p):void 0,f))return;f=p}if(f)return d(u,m)}function d(u,m){const h=m[m.length-1],f=o[l][0],p=o[l][1];let g=0;const v=h.children.indexOf(u);let b=!1,y=[];f.lastIndex=0;let S=f.exec(u.value);for(;S;){const j=S.index,C={index:S.index,input:S.input,stack:[...m,u]};let x=p(...S,C);if(typeof x=="string"&&(x=x.length>0?{type:"text",value:x}:void 0),x===!1?f.lastIndex=j+1:(g!==j&&y.push({type:"text",value:u.value.slice(g,j)}),Array.isArray(x)?y.push(...x):x&&y.push(x),g=j+S[0].length,b=!0),!f.global)break;S=f.exec(u.value)}return b?(g<u.value.length&&y.push({type:"text",value:u.value.slice(g)}),h.children.splice(v,1,...y)):y=[u],v+y.length}}function kR(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([jR(r[0]),NR(r[1])])}return n}function jR(e){return typeof e=="string"?new RegExp(yR(e),"g"):e}function NR(e){return typeof e=="function"?e:function(){return e}}const bd="phrasing",xd=["autolink","link","image","label"];function SR(){return{transforms:[IR],enter:{literalAutolink:ER,literalAutolinkEmail:vd,literalAutolinkHttp:vd,literalAutolinkWww:vd},exit:{literalAutolink:RR,literalAutolinkEmail:AR,literalAutolinkHttp:_R,literalAutolinkWww:MR}}}function CR(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:bd,notInConstruct:xd},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:bd,notInConstruct:xd},{character:":",before:"[ps]",after:"\\/",inConstruct:bd,notInConstruct:xd}]}}function ER(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function vd(e){this.config.enter.autolinkProtocol.call(this,e)}function _R(e){this.config.exit.autolinkProtocol.call(this,e)}function MR(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 AR(e){this.config.exit.autolinkEmail.call(this,e)}function RR(e){this.exit(e)}function IR(e){wR(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,TR],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,PR]],{ignore:["link","linkReference"]})}function TR(e,n,s,a,r){let o="";if(!Px(r)||(/^w/i.test(n)&&(s=n+s,n="",o="http://"),!$R(s)))return!1;const l=DR(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 PR(e,n,s,a){return!Px(a,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function $R(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 DR(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=Ip(e,"(");let o=Ip(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 Px(e,n){const s=e.input.charCodeAt(e.index-1);return(e.index===0||qa(s)||Ec(s))&&(!n||s!==47)}$x.peek=VR;function LR(){this.buffer()}function OR(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function FR(){this.buffer()}function zR(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function BR(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=Ei(this.sliceSerialize(e)).toLowerCase(),s.label=n}function UR(e){this.exit(e)}function HR(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=Ei(this.sliceSerialize(e)).toLowerCase(),s.label=n}function qR(e){this.exit(e)}function VR(){return"["}function $x(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 WR(){return{enter:{gfmFootnoteCallString:LR,gfmFootnoteCall:OR,gfmFootnoteDefinitionLabelString:FR,gfmFootnoteDefinition:zR},exit:{gfmFootnoteCallString:BR,gfmFootnoteCall:UR,gfmFootnoteDefinitionLabelString:HR,gfmFootnoteDefinition:qR}}}function GR(e){let n=!1;return e&&e.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:$x},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?Dx:KR))),u(),d}}function KR(e,n,s){return n===0?e:Dx(e,n,s)}function Dx(e,n,s){return(s?"":" ")+e}const JR=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Lx.peek=eI;function YR(){return{canContainEols:["delete"],enter:{strikethrough:XR},exit:{strikethrough:ZR}}}function QR(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:JR}],handlers:{delete:Lx}}}function XR(e){this.enter({type:"delete",children:[]},e)}function ZR(e){this.exit(e)}function Lx(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 eI(){return"~"}function tI(e){return e.length}function nI(e,n){const s=n||{},a=(s.align||[]).concat(),r=s.stringLength||tI,o=[],l=[],c=[],d=[];let u=0,m=-1;for(;++m<e.length;){const w=[],v=[];let b=-1;for(e[m].length>u&&(u=e[m].length);++b<e[m].length;){const y=sI(e[m][b]);if(s.alignDelimiters!==!1){const S=r(y);v[b]=S,(d[b]===void 0||S>d[b])&&(d[b]=S)}w.push(y)}l[m]=w,c[m]=v}let h=-1;if(typeof a=="object"&&"length"in a)for(;++h<u;)o[h]=Tp(a[h]);else{const w=Tp(a);for(;++h<u;)o[h]=w}h=-1;const f=[],p=[];for(;++h<u;){const w=o[h];let v="",b="";w===99?(v=":",b=":"):w===108?v=":":w===114&&(b=":");let y=s.alignDelimiters===!1?1:Math.max(1,d[h]-v.length-b.length);const S=v+"-".repeat(y)+b;s.alignDelimiters!==!1&&(y=v.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 w=l[m],v=c[m];h=-1;const b=[];for(;++h<u;){const y=w[h]||"";let S="",j="";if(s.alignDelimiters!==!1){const C=d[h]-(v[h]||0),x=o[h];x===114?S=" ".repeat(C):x===99?C%2?(S=" ".repeat(C/2+.5),j=" ".repeat(C/2-.5)):(S=" ".repeat(C/2),j=S):j=" ".repeat(C)}s.delimiterStart!==!1&&!h&&b.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&y==="")&&(s.delimiterStart!==!1||h)&&b.push(" "),s.alignDelimiters!==!1&&b.push(S),b.push(y),s.alignDelimiters!==!1&&b.push(j),s.padding!==!1&&b.push(" "),(s.delimiterEnd!==!1||h!==u-1)&&b.push("|")}g.push(s.delimiterEnd===!1?b.join("").replace(/ +$/,""):b.join(""))}return g.join(`
|
|
666
|
+
`)}function sI(e){return e==null?"":String(e)}function Tp(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 iI(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()),aI);return r(),l}function aI(e,n,s){return">"+(s?"":" ")+e}function rI(e,n){return Pp(e,n.inConstruct,!0)&&!Pp(e,n.notInConstruct,!1)}function Pp(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 $p(e,n,s,a){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
|
|
667
|
+
`&&rI(s.stack,s.unsafe[r]))return/[ \t]/.test(a.before)?"":" ";return`\\
|
|
668
|
+
`}function oI(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 lI(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 cI(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 dI(e,n,s,a){const r=cI(s),o=e.value||"",l=r==="`"?"GraveAccent":"Tilde";if(lI(e,s)){const h=s.enter("codeIndented"),f=s.indentLines(o,uI);return h(),f}const c=s.createTracker(a),d=r.repeat(Math.max(oI(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 uI(e,n,s){return(s?"":" ")+e}function bm(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 mI(e,n,s,a){const r=bm(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 hI(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 Oo(e){return"&#x"+e.toString(16).toUpperCase()+";"}function ic(e,n,s){const a=Rr(e),r=Rr(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}}Ox.peek=pI;function Ox(e,n,s,a){const r=hI(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=ic(a.before.charCodeAt(a.before.length-1),u,r);m.inside&&(d=Oo(u)+d.slice(1));const h=d.charCodeAt(d.length-1),f=ic(a.after.charCodeAt(0),h,r);f.inside&&(d=d.slice(0,-1)+Oo(h));const p=l.move(r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+d+p}function pI(e,n,s){return s.options.emphasis||"*"}function fI(e,n){let s=!1;return fm(e,function(a){if("value"in a&&/\r?\n|\r/.test(a.value)||a.type==="break")return s=!0,ku}),!!((!e.depth||e.depth<3)&&lm(e)&&(n.options.setext||s))}function gI(e,n,s,a){const r=Math.max(Math.min(6,e.depth||1),1),o=s.createTracker(a);if(fI(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=Oo(u.charCodeAt(0))+u.slice(1)),u=u?l+" "+u:l,s.options.closeAtx&&(u+=" "+l),d(),c(),u}Fx.peek=bI;function Fx(e){return e.value||""}function bI(){return"<"}zx.peek=xI;function zx(e,n,s,a){const r=bm(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 xI(){return"!"}Bx.peek=vI;function Bx(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 vI(){return"!"}Ux.peek=yI;function Ux(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 yI(){return"`"}function Hx(e,n){const s=lm(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))}qx.peek=wI;function qx(e,n,s,a){const r=bm(s),o=r==='"'?"Quote":"Apostrophe",l=s.createTracker(a);let c,d;if(Hx(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 wI(e,n,s){return Hx(e,s)?"<":"["}Vx.peek=kI;function Vx(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 kI(){return"["}function xm(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 jI(e){const n=xm(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 NI(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 Wx(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 SI(e,n,s,a){const r=s.enter("list"),o=s.bulletCurrent;let l=e.ordered?NI(s):xm(s);const c=e.ordered?l==="."?")":".":jI(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),Wx(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 CI(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 EI(e,n,s,a){const r=CI(s);let o=s.bulletCurrent||xm(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 _I(e,n,s,a){const r=s.enter("paragraph"),o=s.enter("phrasing"),l=s.containerPhrasing(e,a);return o(),r(),l}const MI=Ac(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function AI(e,n,s,a){return(e.children.some(function(l){return MI(l)})?s.containerPhrasing:s.containerFlow).call(s,e,a)}function RI(e){const n=e.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}Gx.peek=II;function Gx(e,n,s,a){const r=RI(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=ic(a.before.charCodeAt(a.before.length-1),u,r);m.inside&&(d=Oo(u)+d.slice(1));const h=d.charCodeAt(d.length-1),f=ic(a.after.charCodeAt(0),h,r);f.inside&&(d=d.slice(0,-1)+Oo(h));const p=l.move(r+r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+d+p}function II(e,n,s){return s.options.strong||"*"}function TI(e,n,s,a){return s.safe(e.value,a)}function PI(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 $I(e,n,s){const a=(Wx(s)+(s.options.ruleSpaces?" ":"")).repeat(PI(s));return s.options.ruleSpaces?a.slice(0,-1):a}const Kx={blockquote:iI,break:$p,code:dI,definition:mI,emphasis:Ox,hardBreak:$p,heading:gI,html:Fx,image:zx,imageReference:Bx,inlineCode:Ux,link:qx,linkReference:Vx,list:SI,listItem:EI,paragraph:_I,root:AI,strong:Gx,text:TI,thematicBreak:$I};function DI(){return{enter:{table:LI,tableData:Dp,tableHeader:Dp,tableRow:FI},exit:{codeText:zI,table:OI,tableData:yd,tableHeader:yd,tableRow:yd}}}function LI(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 OI(e){this.exit(e),this.data.inTable=void 0}function FI(e){this.enter({type:"tableRow",children:[]},e)}function yd(e){this.exit(e)}function Dp(e){this.enter({type:"tableCell",children:[]},e)}function zI(e){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,BI));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(e)}function BI(e,n){return n==="|"?n:e}function UI(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,w,v){return u(m(p,w,v),p.align)}function c(p,g,w,v){const b=h(p,w,v),y=u([b]);return y.slice(0,y.indexOf(`
|
|
679
|
+
`))}function d(p,g,w,v){const b=w.enter("tableCell"),y=w.enter("phrasing"),S=w.containerPhrasing(p,{...v,before:o,after:o});return y(),b(),S}function u(p,g){return nI(p,{align:g,alignDelimiters:a,padding:s,stringLength:r})}function m(p,g,w){const v=p.children;let b=-1;const y=[],S=g.enter("table");for(;++b<v.length;)y[b]=h(v[b],g,w);return S(),y}function h(p,g,w){const v=p.children;let b=-1;const y=[],S=g.enter("tableRow");for(;++b<v.length;)y[b]=d(v[b],p,g,w);return S(),y}function f(p,g,w){let v=Kx.inlineCode(p,g,w);return w.stack.includes("tableCell")&&(v=v.replace(/\|/g,"\\$&")),v}}function HI(){return{exit:{taskListCheckValueChecked:Lp,taskListCheckValueUnchecked:Lp,paragraph:VI}}}function qI(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:WI}}}function Lp(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function VI(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 WI(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=Kx.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 GI(){return[SR(),WR(),YR(),DI(),HI()]}function KI(e){return{extensions:[CR(),GR(e),QR(),UI(e),qI()]}}const JI={tokenize:tT,partial:!0},Jx={tokenize:nT,partial:!0},Yx={tokenize:sT,partial:!0},Qx={tokenize:iT,partial:!0},YI={tokenize:aT,partial:!0},Xx={name:"wwwAutolink",tokenize:ZI,previous:ev},Zx={name:"protocolAutolink",tokenize:eT,previous:tv},ia={name:"emailAutolink",tokenize:XI,previous:nv},Bi={};function QI(){return{text:Bi}}let Pa=48;for(;Pa<123;)Bi[Pa]=ia,Pa++,Pa===58?Pa=65:Pa===91&&(Pa=97);Bi[43]=ia;Bi[45]=ia;Bi[46]=ia;Bi[95]=ia;Bi[72]=[ia,Zx];Bi[104]=[ia,Zx];Bi[87]=[ia,Xx];Bi[119]=[ia,Xx];function XI(e,n,s){const a=this;let r,o;return l;function l(h){return!Cu(h)||!nv.call(a,a.previous)||vm(a.events)?s(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(h))}function c(h){return Cu(h)?(e.consume(h),c):h===64?(e.consume(h),d):s(h)}function d(h){return h===46?e.check(YI,m,u)(h):h===45||h===95||Fs(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&&qs(a.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),n(h)):s(h)}}function ZI(e,n,s){const a=this;return r;function r(l){return l!==87&&l!==119||!ev.call(a,a.previous)||vm(a.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(JI,e.attempt(Jx,e.attempt(Yx,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function eT(e,n,s){const a=this;let r="",o=!1;return l;function l(h){return(h===72||h===104)&&tv.call(a,a.previous)&&!vm(a.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),e.consume(h),c):s(h)}function c(h){if(qs(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||tc(h)||Kn(h)||qa(h)||Ec(h)?s(h):e.attempt(Jx,e.attempt(Yx,m),s)(h)}function m(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(h)}}function tT(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 nT(e,n,s){let a,r,o;return l;function l(u){return u===46||u===95?e.check(Qx,d,c)(u):u===null||Kn(u)||qa(u)||u!==45&&Ec(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 sT(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(Qx,n,o)(l):l===null||Kn(l)||qa(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&a++,e.consume(l),r}}function iT(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||Kn(c)||qa(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||Kn(c)||qa(c)?n(c):a(c)}function o(c){return qs(c)?l(c):s(c)}function l(c){return c===59?(e.consume(c),a):qs(c)?(e.consume(c),l):s(c)}}function aT(e,n,s){return a;function a(o){return e.consume(o),r}function r(o){return Fs(o)?s(o):n(o)}}function ev(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||Kn(e)}function tv(e){return!qs(e)}function nv(e){return!(e===47||Cu(e))}function Cu(e){return e===43||e===45||e===46||e===95||Fs(e)}function vm(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 rT={tokenize:pT,partial:!0};function oT(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:uT,continuation:{tokenize:mT},exit:hT}},text:{91:{name:"gfmFootnoteCall",tokenize:dT},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:lT,resolveTo:cT}}}}function lT(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=Ei(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 cT(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 dT(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||Kn(h))return s(h);if(h===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return r.includes(Ei(a.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),n):s(h)}return Kn(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 uT(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||Kn(g))return s(g);if(g===93){e.exit("chunkString");const w=e.exit("gfmFootnoteDefinitionLabelString");return o=Ei(a.sliceSerialize(w)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return Kn(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),Rn(e,p,"gfmFootnoteDefinitionWhitespace")):s(g)}function p(g){return n(g)}}function mT(e,n,s){return e.check(el,n,e.attempt(rT,n,s))}function hT(e){e.exit("gfmFootnoteDefinition")}function pT(e,n,s){const a=this;return Rn(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 fT(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&&ai(f,f.length,0,_c(p,l.slice(u+1,d),c)),ai(f,f.length,0,[["exit",h,c],["enter",l[d][1],c],["exit",l[d][1],c],["exit",m,c]]),ai(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 w=Rr(u);if(g===126)return h>1?d(g):(l.consume(g),h++,p);if(h<2&&!s)return d(g);const v=l.exit("strikethroughSequenceTemporary"),b=Rr(g);return v._open=!b||b===2&&!!w,v._close=!w||w===2&&!!b,c(g)}}}class gT{constructor(){this.map=[]}add(n,s,a){bT(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 bT(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 xT(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 vT(){return{flow:{null:{name:"table",tokenize:yT,resolveAll:wT}}}}function yT(e,n,s){const a=this;let r=0,o=0,l;return c;function c(E){let _=a.events.length-1;for(;_>-1;){const A=a.events[_][1].type;if(A==="lineEnding"||A==="linePrefix")_--;else break}const K=_>-1?a.events[_][1].type:null,U=K==="tableHead"||K==="tableRow"?x:d;return U===x&&a.parser.lazy[a.now().line]?s(E):U(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):Yt(E)?o>1?(o=0,a.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(E),e.exit("lineEnding"),p):s(E):wn(E)?Rn(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||Kn(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,wn(E)?Rn(e,g,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(E):g(E))}function g(E){return E===45||E===58?v(E):E===124?(l=!0,e.enter("tableCellDivider"),e.consume(E),e.exit("tableCellDivider"),w):C(E)}function w(E){return wn(E)?Rn(e,v,"whitespace")(E):v(E)}function v(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||Yt(E)?j(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 wn(E)?Rn(e,j,"whitespace")(E):j(E)}function j(E){return E===124?g(E):E===null||Yt(E)?!l||r!==o?C(E):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(E)):C(E)}function C(E){return s(E)}function x(E){return e.enter("tableRow"),N(E)}function N(E){return E===124?(e.enter("tableCellDivider"),e.consume(E),e.exit("tableCellDivider"),N):E===null||Yt(E)?(e.exit("tableRow"),n(E)):wn(E)?Rn(e,N,"whitespace")(E):(e.enter("data"),R(E))}function R(E){return E===null||E===124||Kn(E)?(e.exit("data"),N(E)):(e.consume(E),E===92?F:R)}function F(E){return E===92||E===124?(e.consume(E),R):R(E)}}function wT(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 gT;for(;++s<e.length;){const p=e[s],g=p[1];p[0]==="enter"?g.type==="tableHead"?(c=!1,d!==0&&(Op(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=pl(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=pl(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=pl(f,n,o,r,s,h)):l[1]!==0&&(h=pl(f,n,l,r,s,h)),r=0):r&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(l[3]=s)}for(d!==0&&Op(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=xT(n.events,s))}return e}function pl(e,n,s,a,r,o){const l=a===1?"tableHeader":a===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},xr(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const d=xr(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=xr(n.events,s[2]),m=xr(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,w=s[3]-s[2]-1;e.add(g,w,[])}}e.add(s[3]+1,0,[["exit",h,n]])}return r!==void 0&&(o.end=Object.assign({},xr(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function Op(e,n,s,a,r){const o=[],l=xr(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 xr(e,n){const s=e[n],a=s[0]==="enter"?"start":"end";return s[1][a]}const kT={name:"tasklistCheck",tokenize:NT};function jT(){return{text:{91:kT}}}function NT(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 Kn(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 Yt(d)?n(d):wn(d)?e.check({tokenize:ST},n,s)(d):s(d)}}function ST(e,n,s){return Rn(e,a,"whitespace");function a(r){return r===null?s(r):n(r)}}function CT(e){return hx([QI(),oT(),fT(e),vT(),jT()])}const ET={};function vi(e){const n=this,s=e||ET,a=n.data(),r=a.micromarkExtensions||(a.micromarkExtensions=[]),o=a.fromMarkdownExtensions||(a.fromMarkdownExtensions=[]),l=a.toMarkdownExtensions||(a.toMarkdownExtensions=[]);r.push(CT(s)),o.push(GI()),l.push(KI(s))}const _T=45e3,MT=3e3,AT=2e3,RT=1500,Fp="fusion:sse-client-id";let mr=null;const fa=new Map;function zp(){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 sv(){if(!(typeof window>"u")){if(mr)return mr;try{const e=window.sessionStorage.getItem(Fp);if(e)return mr=e,e;const n=zp();return window.sessionStorage.setItem(Fp,n),mr=n,n}catch{return mr=zp(),mr}}}function iv(e){if(!(typeof window>"u"))try{return{parsed:new URL(e,window.location.origin),preserveRelativePath:e.startsWith("/")}}catch{return}}function av(e){return e.origin===window.location.origin&&e.pathname==="/api/events"}function IT(e){const n=sv();if(!n)return e;const s=iv(e);return!s||!av(s.parsed)?e:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function ym(e,n){const s=sv();if(!s)return;const a=iv(e);if(!a||!av(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),Fi(`${r.pathname}${r.search}${r.hash}`)}function TT(e){if(typeof window>"u")return;const n=ym(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 Ic(e){e.keepaliveTimer&&(clearInterval(e.keepaliveTimer),e.keepaliveTimer=null)}function Bp(e){if(typeof window>"u"||typeof window.fetch!="function")return;const n=ym(e.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,a=s?window.setTimeout(()=>s.abort(),RT):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{a!==null&&window.clearTimeout(a)})}function PT(e){Ic(e),ym(e.url,"keepalive")&&(Bp(e),e.keepaliveTimer=window.setInterval(()=>{Bp(e)},AT))}if(typeof window<"u"){const e=()=>{for(const s of Array.from(fa.values()))if(!s.closed){if(Ic(s),TT(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(fa.values()))a.subscribers.size!==0&&(a.closed=!1,wm(a))};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("pageshow",n)}function wo(e){e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),e.heartbeatTimer=setTimeout(()=>{rv(e)},_T)}function rv(e){if(e.heartbeatTimer&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=null),e.es&&(e.es.close(),e.es=null),Ic(e),e.nativeListeners.clear(),e.closed||e.subscribers.size===0||e.reconnectTimer)return;const n=fa.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=fa.get(e.url);s&&s===e&&e.subscribers.size>0&&wm(e)},MT)}}function wm(e){if(e.es||e.closed)return;e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);const n=new EventSource(Fi(IT(e.url)));e.es=n,PT(e),n.addEventListener("open",()=>{wo(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);rv(e)}),n.addEventListener("message",()=>wo(e)),n.addEventListener("heartbeat",()=>wo(e)),ov(e),wo(e)}function ov(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=>{wo(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 $T(e){e.closed=!0,e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),Ic(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.es&&e.es.close(),e.es=null,e.nativeListeners.clear(),fa.delete(e.url)}function yi(e,n={}){let s=fa.get(e);s||(s={url:e,es:null,subscribers:new Set,nativeListeners:new Map,heartbeatTimer:null,keepaliveTimer:null,reconnectTimer:null,hasOpenedOnce:!1,closed:!1},fa.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;wm(s),ov(s),r&&queueMicrotask(()=>{s.subscribers.has(a)&&a.onOpen?.()});let o=!0;return()=>{if(!o)return;o=!1;const l=fa.get(e);l&&(l.subscribers.delete(a),l.subscribers.size===0&&$T(l))}}const Up=100;function lv(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),w=i.useRef(0),v=i.useRef(e),b=i.useRef(s),y=i.useRef(n),S=i.useRef(0);(v.current!==e||b.current!==s||y.current!==n)&&(v.current=e,b.current=s,y.current=n,w.current++,g.current=!0,r([]),l(!1),d(!1),m(null),f(!1),p.current&&(p.current(),p.current=null)),i.useEffect(()=>{if(!e||!n){p.current&&(p.current(),p.current=null);return}const N=w.current,R=++S.current;g.current=!1;const F=e,E=s;async function _(){if(!F)return;l(!0),f(!1);try{const U=await qm(F,E,{limit:Up});if(g.current||w.current!==N||S.current!==R)return;r(U.entries),d(U.hasMore),m(U.total)}catch{if(g.current||w.current!==N||S.current!==R)return;r([]),d(!1),m(null)}finally{!g.current&&w.current===N&&S.current===R&&l(!1)}const K=E?`?projectId=${encodeURIComponent(E)}`:"";p.current=yi(`/api/tasks/${F}/logs/stream${K}`,{events:{"agent:log":U=>{if(!(g.current||w.current!==N))try{const A=JSON.parse(U.data);r(T=>[...T,A]),m(T=>T!==null?T+1:null)}catch{}}}})}return _(),()=>{g.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const C=i.useCallback(async()=>{if(!e||h)return;const N=w.current,R=a.length,F=e;f(!0);try{const E=await qm(F,s,{limit:Up,offset:R});if(g.current||w.current!==N)return;r(_=>[...E.entries,..._]),d(E.hasMore),m(E.total)}catch{}finally{f(!1)}},[e,s,a.length,h]),x=i.useCallback(()=>r([]),[]);return{entries:a,loading:o,clear:x,loadMore:C,hasMore:c,total:u,loadingMore:h}}const cv=i.createContext(null);function DT({openFile:e,children:n}){return t.jsx(cv.Provider,{value:{openFile:e},children:n})}function LT(){return i.useContext(cv)}const OT=/(?<![\w@-])((?:[A-Za-z0-9_./@-]+\/)+[A-Za-z0-9_./@-]+\.[A-Za-z0-9]{1,8}(?::\d+(?::\d+)?)?|(?:Dockerfile|Makefile|AGENTS\.md|README\.md|README)(?::\d+(?::\d+)?)?)(?![\w-])/g,FT=["http://","https://","mailto:","git@","ftp://"],zT=new Set(["Dockerfile","Makefile","AGENTS.md","README.md","README"]);function dv(e){const n=/^(.*?)(?::(\d+)(?::(\d+))?)?$/.exec(e);return n?{path:n[1]??e,line:n[2]?Number.parseInt(n[2],10):void 0,col:n[3]?Number.parseInt(n[3],10):void 0}:{path:e}}function BT(e){return/^v?\d+(?:\.\d+)+$/.test(e)}function UT(e){return e.includes("/")||zT.has(e)}function HT(e,n,s){const a=e.slice(Math.max(0,n-16),n).toLowerCase();if(s.startsWith("//")||FT.some(o=>a.endsWith(o)))return!0;const{path:r}=dv(s);return!!(BT(r)||!UT(r))}function qT({path:e,line:n,col:s,children:a}){const r=LT();return r?t.jsx("button",{type:"button",className:"file-path-link",onClick:()=>r.openFile(e,{line:n,col:s}),children:a??e}):t.jsx("span",{children:a??e})}function Cs(e,n){if(!e)return[e];const s=[];let a=0,r=0;for(const o of e.matchAll(OT)){const l=o[0],c=o.index??0,d=c+l.length;if(HT(e,c,l))continue;c>a&&s.push(e.slice(a,c));const{path:u,line:m,col:h}=dv(l);s.push(t.jsx(qT,{path:u,line:m,col:h,children:l},`file-path-${c}-${r}`)),a=d,r+=1}return a===0?[e]:(a<e.length&&s.push(e.slice(a)),s)}function Ys(e){if(typeof e=="string"){const n=Cs(e);return n.length===1?n[0]:t.jsx(t.Fragment,{children:n})}return Array.isArray(e)?ga.Children.map(e,n=>Ys(n)):!i.isValidElement(e)||typeof e.type=="string"&&["button","code","pre"].includes(e.type)||e.props.children===void 0?e:i.cloneElement(e,void 0,ga.Children.map(e.props.children,n=>Ys(n)))}const Hp="fn-agent-log-markdown",qp="fn-agent-log-tool-output";function Vp(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 Wp(e,n){if(!(typeof window>"u"))try{window.localStorage.setItem(e,n?"true":"false")}catch{}}function VT(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 Gp={p:({children:e,...n})=>t.jsx("p",{...n,children:Ys(e)}),li:({children:e,...n})=>t.jsx("li",{...n,children:Ys(e)}),code:({children:e,...n})=>{const s=typeof e=="string"?e:ga.Children.toArray(e).join(""),a=Cs(s);return a.length===1&&typeof a[0]=="string"?t.jsx("code",{...n,children:e}):t.jsx("code",{...n,children:a})},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})},uv=50,WT={triage:"Plan"};function Kp(e){return e.scrollHeight-(e.scrollTop+e.clientHeight)<=uv}function Eu(e){return[e.taskId,e.timestamp,e.agent??"",e.type,e.text,e.detail??""].join("|")}function GT(e){const n=new Map;return e.map(s=>{const a=Eu(s),r=n.get(a)??0;return n.set(a,r+1),`${a}|${r}`})}function mv(e){return e==="tool"||e==="tool_result"||e==="tool_error"}function wd({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(gn,{size:14}):t.jsx(qn,{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:Cs(e)})})]})}function KT(e,n){return e.agent?mv(e.type)?!0:!n||n.agent!==e.agent||n.type!==e.type:!1}function JT(e,n){const s=[];for(let a=0;a<e.length;a+=1){const{entry:r,hiddenToolBoundaryId:o}=e[a],l=n[a]??`${Eu(r)}|fallback`,c=a>0?e[a-1]:void 0,d=c?.entry,u=KT(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]??`${Eu(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 YT({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,w]=i.useState(()=>Vp(Hp,!0)),[v,b]=i.useState(()=>Vp(qp,!0)),[y,S]=i.useState(!1),[j,C]=i.useState(!1),[x,N]=i.useState(!0);i.useEffect(()=>{Wp(Hp,g)},[g]),i.useEffect(()=>{Wp(qp,v)},[v]);const R=i.useMemo(()=>{if(v)return e.map(D=>({entry:D,hiddenToolBoundaryId:0}));const O=[];let M=0;for(const D of e){if(mv(D.type)){M+=1;continue}O.push({entry:D,hiddenToolBoundaryId:M})}return O},[e,v]),F=i.useMemo(()=>R.map(O=>O.entry),[R]),E=i.useMemo(()=>GT(F),[F]),_=i.useMemo(()=>JT(R,E),[R,E]);i.useLayoutEffect(()=>{const O=u.current;if(!O)return;const M=e.length,D=m.current,$=h.current||O.scrollHeight,k=E[0]??null,X=E[E.length-1]??null,le=f.current!==k,ke=p.current!==X;if(M>D)if(D===0)O.scrollTop=O.scrollHeight;else{const He=$-(O.scrollTop+O.clientHeight)<=uv,ye=ke&&!le,je=le&&!ke;if(ye&&He&&(O.scrollTop=O.scrollHeight),je){const ne=O.scrollHeight-$;ne>0&&(O.scrollTop+=ne)}}m.current=M,h.current=O.scrollHeight,f.current=k,p.current=X,N(Kp(O))},[e,E]);const K=i.useCallback(()=>{const O=u.current;O&&N(Kp(O))},[]),U=i.useCallback(()=>{const O=u.current;O&&(O.scrollTop=O.scrollHeight,N(!0))},[]),A=i.useCallback(O=>{O.key==="Escape"&&y&&S(!1)},[y]);i.useEffect(()=>{if(y)return document.addEventListener("keydown",A),()=>{document.removeEventListener("keydown",A)}},[y,A]);const T=s?.provider&&s?.modelId,H=a?.provider&&a?.modelId,Q=r?.provider&&r?.modelId,se=i.useMemo(()=>{const O=[];return T&&O.push({role:"Executor",provider:s.provider,modelId:s.modelId}),H&&O.push({role:"Reviewer",provider:a.provider,modelId:a.modelId}),Q&&O.push({role:"Planning",provider:r.provider,modelId:r.modelId}),O},[T,s,H,a,Q,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:[se.map(O=>t.jsx(zn,{provider:O.provider,size:"sm"},`${O.role}-${O.provider}-${O.modelId??"default"}`)),t.jsx("button",{className:"agent-log-model-expand-btn",onClick:()=>C(O=>!O),"aria-label":j?"Collapse model details":"Expand model details","aria-expanded":j,"aria-controls":"agent-log-model-details","data-testid":"agent-log-model-expand",children:j?t.jsx(gn,{size:14}):t.jsx(qn,{size:14})})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>w(O=>!O),"aria-label":g?"Switch to plain text mode":"Switch to markdown mode","aria-pressed":g,"data-testid":"agent-log-mode-toggle",title:g?"Show raw text":"Show formatted markdown",children:g?"Markdown":"Plain"}),t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>b(O=>!O),"aria-label":v?"Hide tool output":"Show tool output","aria-pressed":v,"data-testid":"agent-log-tool-output-toggle",title:v?"Hide tool calls and results":"Show tool calls and results",children:v?"Tools: On":"Tools: Off"}),t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>S(O=>!O),"aria-label":y?"Exit full screen":"Expand agent log to full screen","data-testid":"agent-log-fullscreen-toggle",title:y?"Exit full screen":"Expand agent log to full screen",children:y?t.jsx(qo,{size:14}):t.jsx(wc,{size:14})})]}),j&&t.jsxs("div",{id:"agent-log-model-details",className:"agent-log-model-details",children:[t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Executor:"}),T?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(zn,{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:"}),H?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(zn,{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:"}),Q?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(zn,{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:K,children:[d!==null&&t.jsxs("div",{className:"agent-log-summary","data-testid":"agent-log-summary",children:["Showing ",F.length," of ",d," entries",!v&&e.length!==F.length?` (${e.length-F.length} tool entries hidden)`:""]}),o&&l&&t.jsx("div",{className:"agent-log-load-more","data-testid":"agent-log-load-more",children:t.jsx("button",{className:"agent-log-mode-toggle",onClick:l,disabled:c,"data-testid":"agent-log-load-more-button",children:c?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})}),_.map(O=>{const M=O.kind==="single"?O.entry:O.entries[0],D=O.showBadge?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:VT(M.timestamp)}):null,$=O.showBadge?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",WT[M.agent]??M.agent,"]"]}),D]}):null;if(O.kind==="single"){const{entry:X}=O;if(X.type==="tool")return t.jsxs("div",{className:"agent-log-tool",children:[$,t.jsxs("div",{className:"agent-log-tool-title",children:["⚡ ",X.text]}),X.detail?t.jsx(wd,{detail:X.detail,type:"tool"}):null]},O.key);if(X.type==="tool_result")return t.jsxs("div",{className:"agent-log-tool-result",children:[$,t.jsxs("div",{className:"agent-log-tool-title",children:["✓ ",X.text]}),X.detail?t.jsx(wd,{detail:X.detail,type:"tool_result"}):null]},O.key);if(X.type==="tool_error")return t.jsxs("div",{className:"agent-log-tool-error",children:[$,t.jsxs("div",{className:"agent-log-tool-title",children:["✗ ",X.text]}),X.detail?t.jsx(wd,{detail:X.detail,type:"tool_error"}):null]},O.key)}const k=O.kind==="single"?M.text:O.entries.map(X=>X.text).join("");return O.kind==="thinking"?t.jsxs("div",{className:"agent-log-thinking",children:[$,g?t.jsx("div",{className:"markdown-body",children:t.jsx(xi,{remarkPlugins:[vi],components:Gp,children:k})}):t.jsx("pre",{className:"agent-log-plain-block",children:Cs(k)})]},O.key):t.jsxs("div",{className:"agent-log-text",children:[$,g?t.jsx("div",{className:"markdown-body",children:t.jsx(xi,{remarkPlugins:[vi],components:Gp,children:k})}):t.jsx("pre",{className:"agent-log-plain-block",children:Cs(k)})]},O.key)}),!x&&t.jsxs("button",{type:"button",className:"agent-log-return-to-live",onClick:U,"data-testid":"agent-log-return-to-live",children:[t.jsx(gn,{size:12}),t.jsx("span",{children:"Live"})]})]})]})}function Ir(e){return e??void 0}function fl(e){return{provider:Ir(e.modelProvider),modelId:Ir(e.modelId)}}function gl(e){return{provider:Ir(e.validatorModelProvider),modelId:Ir(e.validatorModelId)}}function bl(e){return{provider:Ir(e.planningModelProvider),modelId:Ir(e.planningModelId)}}function QT(e,n){return Tb(e,n)}function XT(e,n){return Pb(e,n)}function ZT(e,n){return $b(e,n)}function kd(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 jd(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function Nd(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function eP(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 tP({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,w]=i.useState(()=>fl(e)),[v,b]=i.useState(()=>fl(e)),[y,S]=i.useState(()=>gl(e)),[j,C]=i.useState(()=>gl(e)),[x,N]=i.useState(()=>bl(e)),[R,F]=i.useState(()=>bl(e)),[E,_]=i.useState(()=>e.thinkingLevel??null),[K,U]=i.useState(()=>e.thinkingLevel??null),[A,T]=i.useState(null),H=i.useRef(e.id);i.useEffect(()=>{h(!0),p(null),Ws().then(q=>{o(q.models),c(q.favoriteProviders),u(q.favoriteModels)}).catch(q=>{p(q.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const Q=i.useCallback(async q=>{const L=l,he=L.includes(q)?L.filter(B=>B!==q):[q,...L];c(he);try{await Bn({favoriteProviders:he,favoriteModels:d})}catch{c(L),n("Failed to update favorites","error")}},[l,d,n]),se=i.useCallback(async q=>{const L=d,he=L.includes(q)?L.filter(B=>B!==q):[q,...L];u(he);try{await Bn({favoriteProviders:l,favoriteModels:he})}catch{u(L),n("Failed to update model favorites","error")}},[d,l,n]);i.useEffect(()=>{H.current=e.id;const q=fl(e),L=gl(e),xe=bl(e);w(q),b(q),S(L),C(L),N(xe),F(xe);const he=e.thinkingLevel??null;_(he),U(he),T(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const O=i.useMemo(()=>jd(g),[g]),M=i.useMemo(()=>jd(y),[y]),D=i.useMemo(()=>jd(x),[x]),$=i.useMemo(()=>QT(e,a),[e,a]),k=i.useMemo(()=>XT(e,a),[e,a]),X=i.useMemo(()=>ZT(e,a),[e,a]),le=A!==null,ke=i.useCallback(async(q,L)=>{const xe=e.id,he=v,B=j,pe=R;T(q);try{const ze=s?q==="executor"?{modelProvider:L.provider??null,modelId:L.modelId??null}:q==="validator"?{validatorModelProvider:L.provider??null,validatorModelId:L.modelId??null}:{planningModelProvider:L.provider??null,planningModelId:L.modelId??null}:{modelProvider:(q==="executor"?L:v).provider??null,modelId:(q==="executor"?L:v).modelId??null,validatorModelProvider:(q==="validator"?L:j).provider??null,validatorModelId:(q==="validator"?L:j).modelId??null,planningModelProvider:(q==="planning"?L:R).provider??null,planningModelId:(q==="planning"?L:R).modelId??null},ae=await Us(xe,ze);if(H.current!==xe)return;const Ve=fl(ae),Te=gl(ae),rt=bl(ae);b(Ve),w(Ve),C(Te),S(Te),F(rt),N(rt),s?.(ae),n(eP(q,{executor:Ve,validator:Te,planning:rt}[q]),"success")}catch(ze){if(H.current!==xe)return;q==="executor"?w(he):q==="validator"?S(B):N(pe),n(Se(ze)||"Failed to save model settings","error")}finally{H.current===xe&&T(null)}},[e.id,v,j,R,n,s]),He=i.useCallback(q=>{const L=kd(q);w(L),!Nd(L,v)&&ke("executor",L)},[v,ke]),ye=i.useCallback(q=>{const L=kd(q);S(L),!Nd(L,j)&&ke("validator",L)},[j,ke]),je=i.useCallback(q=>{const L=kd(q);N(L),!Nd(L,R)&&ke("planning",L)},[R,ke]),ne=i.useCallback(async q=>{const L=e.id,xe=K,he=q===""?null:q;_(he),T("thinking");try{const B=await Us(L,{thinkingLevel:he});if(H.current!==L)return;const pe=B.thinkingLevel??null;U(pe),_(pe),s?.(B);const ze=a?.defaultThinkingLevel??"off";n(pe===null?`Thinking level set to default (${ze})`:`Thinking level set to ${pe}`,"success")}catch(B){if(H.current!==L)return;_(xe),n(Se(B)||"Failed to save thinking level","error")}finally{H.current===L&&T(null)}},[e.id,K,a,n,s]),fe=!v.provider&&!v.modelId,Z=!j.provider&&!j.modelId,re=!R.provider&&!R.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),Ws().then(q=>{o(q.models),c(q.favoriteProviders),u(q.favoriteModels)}).catch(q=>p(q.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:fe?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:[v.provider&&t.jsx(zn,{provider:v.provider,size:"sm"}),v.provider,"/",v.modelId]})}),t.jsx(_s,{id:"executorModel",label:"Executor Model",value:O,onChange:He,models:r,disabled:le,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:Q,favoriteModels:d,onToggleModelFavorite:se}),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:Z?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",k.provider&&k.modelId?` (${k.provider}/${k.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[j.provider&&t.jsx(zn,{provider:j.provider,size:"sm"}),j.provider,"/",j.modelId]})}),t.jsx(_s,{id:"validatorModel",label:"Reviewer Model",value:M,onChange:ye,models:r,disabled:le,placeholder:"Select reviewer model…",favoriteProviders:l,onToggleFavorite:Q,favoriteModels:d,onToggleModelFavorite:se}),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",X.provider&&X.modelId?` (${X.provider}/${X.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[R.provider&&t.jsx(zn,{provider:R.provider,size:"sm"}),R.provider,"/",R.modelId]})}),t.jsx(_s,{id:"planningModel",label:"Planning Model",value:D,onChange:je,models:r,disabled:le,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:Q,favoriteModels:d,onToggleModelFavorite:se}),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:K===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:K})}),t.jsxs("select",{id:"thinkingLevel",value:E??"",onChange:q=>ne(q.target.value),disabled:le,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:fe&&Z&&re&&K===null?"Using project or global default models.":"Model settings are up to date."})]})]})}const nP={open:t.jsx(fc,{size:16}),closed:t.jsx(Ho,{size:16}),merged:t.jsx(sb,{size:16})};function sP({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,w]=i.useState(""),[v,b]=i.useState(!1),[y,S]=i.useState(!1),[j,C]=i.useState(null),x=i.useCallback(async()=>{if(f.trim()){b(!0);try{const E=await zN(e,{title:f.trim(),body:g.trim()||void 0},n);c(E),h(!1),p(""),w(""),u(`Created PR #${E.number}`,"success")}catch(E){u(Se(E)||"Failed to create PR","error")}finally{b(!1)}}},[e,f,g,n,c,u]),N=i.useCallback(async()=>{if(s){S(!0);try{const E=await BN(e,n);C(E),d(E.prInfo),u("PR status refreshed","success")}catch(E){u(Se(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(ii,{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(ii,{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(ii,{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:v,className:"pr-input"}),t.jsx("textarea",{placeholder:"PR description (optional)",value:g,onChange:E=>w(E.target.value),disabled:v,className:"pr-textarea",rows:3}),t.jsxs("div",{className:"pr-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>h(!1),disabled:v,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:x,disabled:!f.trim()||v,children:v?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(ii,{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($n,{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 R=nP[s.status]??t.jsx(fc,{size:16}),F=j?.blockingReasons??[];return t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(ii,{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:R}),t.jsx("span",{className:`pr-status-badge pr-status-badge--${s.status}`,children:s.status}),t.jsxs("span",{className:"pr-number",children:["#",s.number]}),t.jsx("div",{className:"pr-spacer"}),t.jsx("button",{className:"btn btn-sm pr-refresh-btn",onClick:N,disabled:y,title:"Refresh PR status",children:t.jsx(ps,{size:14,style:{verticalAlign:"middle",opacity:y?.5:1}})})]}),t.jsx("div",{className:"pr-title",children:s.title}),t.jsxs("div",{className:"pr-meta",children:[t.jsx("span",{children:s.headBranch}),t.jsx("span",{className:"pr-meta-arrow",children:"→"}),t.jsx("span",{children:s.baseBranch})]}),a==="merging-pr"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:"fn is merging this pull request automatically."}),a==="awaiting-pr-checks"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:F.length>0?`Waiting for: ${F.join("; ")}`:"Waiting for required checks or review feedback before auto-merge."}),s.status==="merged"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:"This PR is merged. fn will finish local cleanup and move the task to Done."}),t.jsxs("div",{className:"pr-footer",children:[s.commentCount>0&&t.jsxs("span",{className:"pr-comments",children:[t.jsx(Zi,{size:14}),s.commentCount]}),t.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[t.jsx(eb,{size:14}),"View on GitHub"]})]})]})]})}const Jp=2e3;function iP(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function aP(e){return e==="agent"||e==="system"}function rP({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),w=i.useMemo(()=>[...e.comments||[]].sort((N,R)=>new Date(R.createdAt).getTime()-new Date(N.createdAt).getTime()),[e.comments]),v=o.length>Jp;async function b(){const N=o.trim();if(N){f(!0);try{const R=await rN(e.id,N,r);l(""),n?.(R),s("Comment added","success")}catch(R){s(Se(R)||"Failed to add comment","error")}finally{f(!1)}}}async function y(N){const R=u.trim();if(R){f(!0);try{const F=await tN(e.id,N,R,r);d(null),m(""),n?.(F),s("Comment updated","success")}catch(F){s(Se(F)||"Failed to update comment","error")}finally{f(!1)}}}async function S(N){g(N);try{const R=await nN(e.id,N,r);n?.(R),s("Comment deleted","success")}catch(R){s(Se(R)||"Failed to delete comment","error")}finally{g(null)}}function j(N){N.key==="Enter"&&(N.ctrlKey||N.metaKey)&&(N.preventDefault(),b())}return t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Comments"}),w.length===0?t.jsx("div",{className:"detail-log-empty",children:"No comments yet."}):t.jsx("div",{className:"detail-activity-list",children:w.map(N=>{const R=N.author===a,F=c===N.id,E=aP(N.author);return t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header comments-header-row",children:[t.jsxs("div",{className:"comments-author-row",children:[E?t.jsx("span",{className:"ai-guidance-badge","data-testid":"ai-guidance-badge",children:"AI Guidance"}):t.jsx("strong",{children:N.author}),t.jsx("span",{className:"detail-log-timestamp",children:iP(N)})]}),R&&!F?t.jsxs("div",{className:"comments-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{d(N.id),m(N.text)},children:"Edit"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void S(N.id),disabled:p===N.id,children:p===N.id?"Deleting…":"Delete"})]}):null]}),F?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:u,onChange:_=>m(_.target.value),rows:3,className:"comments-textarea"}),t.jsxs("div",{className:"comments-edit-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{d(null),m("")},disabled:h,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void y(N.id),disabled:h||!u.trim(),children:"Save"})]})]}):t.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:N.text})]},N.id)})}),t.jsxs("div",{className:"comments-compose-form",children:[t.jsx("textarea",{value:o,onChange:N=>l(N.target.value),onKeyDown:j,rows:3,placeholder:"Add a comment",className:"comments-textarea"}),t.jsxs("div",{className:"comments-footer-row",children:[t.jsxs("span",{className:`comments-char-count${v?" comments-char-count--over":""}`,children:[o.length," / ",Jp]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void b(),disabled:h||!o.trim()||v,children:h?"Posting…":"Add Comment"})]})]})]})}const Yp="Failed to load review data.",oP="No reviewer feedback yet — this task has not produced reviewer-agent feedback in direct mode.",Qp="fn-task-review-markdown";function lP(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 cP(e,n){if(!(typeof window>"u"))try{window.localStorage.setItem(e,n?"true":"false")}catch{}}const dP={p:({children:e,...n})=>t.jsx("p",{...n,children:Ys(e)}),li:({children:e,...n})=>t.jsx("li",{...n,children:Ys(e)}),code:({children:e,...n})=>t.jsx("code",{...n,children:Ys(e)}),pre:({children:e,...n})=>t.jsx("pre",{...n,style:{overflowX:"auto",maxWidth:"100%",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:Ys(e)}),table:({children:e,...n})=>t.jsx("table",{...n,style:{display:"block",overflowX:"auto",maxWidth:"100%"},children:e})};function ro(e){return e?new Date(e).toLocaleString():"Never"}function uP(e){return e==="manual"?"Manual":e==="auto"?"Background":"Initial load"}function mP(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 hP({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,w]=i.useState(null),[v,b]=i.useState(e.reviewState??null),[y,S]=i.useState(()=>lP(Qp,!0)),j=r.length>0&&!d,C=v?.source==="pull-request",x=i.useMemo(()=>v?mP(v):[],[v]);i.useEffect(()=>{cP(Qp,y)},[y]),i.useEffect(()=>{let A=!1;return h(!0),p(null),o1(e.id,n).then(T=>{A||(b(T.reviewState),w(T.emptyMessage??null))}).catch(()=>{A||p(Yp)}).finally(()=>{A||h(!1)}),()=>{A=!0}},[e.id,n]);const N=i.useMemo(()=>v?v.source==="pull-request"?`${v.summary?.reviewDecision??"REVIEW_REQUIRED"} · ${x.length} review item(s)`:`${v.summary?.summary??"reviewer-agent"} · ${x.length} review item(s)`:"No review feedback captured yet.",[v,x.length]),R=v?v.source==="pull-request"?v.summary?.reviewDecision:v.summary?.verdict:void 0,F=l?"refreshing":v?.refreshStatus??"ready",E=F==="error"?"status-dot status-dot--error":F==="refreshing"?"status-dot status-dot--pending":"status-dot status-dot--online",_=A=>o(T=>T.includes(A)?T.filter(H=>H!==A):[...T,A]),K=async()=>{try{p(null),c(!0);const A=await l1(e.id,n);if(b(A.reviewState),s?.({...e,reviewState:A.reviewState,prInfo:A.prInfo??e.prInfo}),A.reviewState.refreshStatus==="error"){const T=A.reviewState.refreshError??"Failed to refresh review data.";p(T),a(T,"error");return}a("Review refreshed","success")}catch(A){const T=A instanceof Error?A.message:Yp;p(T),a(T,"error")}finally{c(!1)}},U=async()=>{try{if(!v)return;p(null),u(!0);const A=x.filter(H=>r.includes(H.id)).map(H=>{if(!H.item)return{id:H.id,source:v.source==="pull-request"?"pr-review":"reviewer-agent",threadId:H.addressing?.snapshot?.threadId,filePath:H.addressing?.snapshot?.filePath,lineNumber:H.addressing?.snapshot?.lineNumber,author:H.addressing?.snapshot?.authorLogin,summary:H.summary,body:H.body,url:H.addressing?.snapshot?.url};const Q=H.item;return{id:H.item.id,source:v.source==="pull-request"?"pr-review":"reviewer-agent",threadId:typeof Q.threadId=="string"?Q.threadId:void 0,filePath:H.item.path,lineNumber:typeof Q.line=="number"?Q.line:void 0,author:H.item.author?.login,summary:H.item.summary??H.item.body.slice(0,120),body:H.item.body,url:typeof Q.url=="string"?Q.url:void 0}}),T=await c1(e.id,A,n);b(T.reviewState),s?.({...T.task,reviewState:T.reviewState}),o([]),a("Same-task AI revision started from selected review feedback","success")}catch(A){const T=A instanceof Error?A.message:"Failed to queue revision";p(T),a(T,"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:N}),R?t.jsx("span",{className:`task-review-tab__decision task-review-tab__decision--${R}`,children:R}):null]}),t.jsxs("div",{className:"task-review-tab__actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>S(A=>!A),"aria-pressed":y,"data-testid":"task-review-markdown-toggle",title:y?"Show raw text":"Show formatted markdown",children:y?"Markdown":"Plain"}),t.jsx("button",{className:"btn btn-sm",onClick:K,disabled:l||m,children:l?"Refreshing…":"Refresh"}),t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!j,onClick:U,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:E,"aria-hidden":"true"}),t.jsxs("span",{children:[F==="error"?"Refresh failed":F==="refreshing"?"Refreshing":"Up to date"," · Last refreshed: ",ro(v?.lastRefreshedAt)," · ",uP(v?.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&&!C&&x.length===0?t.jsx("div",{className:"task-review-tab__empty",children:g??oP}):null,!m&&!f&&x.length>0?t.jsx("ul",{className:"task-review-tab__list",children:x.map(A=>{const T=`task-review-item-${A.id}`;return t.jsx("li",{className:"task-review-tab__item card",children:t.jsxs("div",{className:"task-review-tab__item-inner",children:[t.jsxs("label",{htmlFor:T,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",{id:T,type:"checkbox",checked:r.includes(A.id),onChange:()=>_(A.id)}),t.jsxs("span",{className:"task-review-tab__item-summary",children:[A.path?`${A.path}: `:"",A.summary]}),t.jsx("span",{className:`task-review-tab__status task-review-tab__status--${A.status}`,children:A.status})]}),t.jsx("div",{className:"task-review-tab__meta",children:ro(A.createdAt)}),A.addressing?t.jsxs("div",{className:"task-review-tab__meta",children:["Selected: ",ro(A.addressing.selectedAt),A.addressing.startedAt?` · Started: ${ro(A.addressing.startedAt)}`:"",A.addressing.completedAt?` · Completed: ${ro(A.addressing.completedAt)}`:"",A.addressing.error?` · Error: ${A.addressing.error}`:""]}):null]}),y?t.jsx("div",{className:"task-review-tab__body markdown-body",children:t.jsx(xi,{remarkPlugins:[vi],components:dP,children:A.body})}):t.jsx("pre",{className:"task-review-tab__body",children:Cs(A.body)})]})},A.id)})}):null,C&&!m&&!f&&x.length===0?t.jsx("div",{className:"task-review-tab__empty",children:"No review items yet."}):null]})}function pP(e){return e?e.slice(0,7):"Unknown"}function fP({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:pP(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 hv(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(ga.Fragment,{children:`${s}
|
|
683
|
+
`},a)})}function gP(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function bP({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);zi(f,e,"fusion:changes-diff-modal-size");const p=sa(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)},[]),w=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(),w())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[e,l,g,w]),!e)return null;const v=d!==null?s[d]:null,b=o==="done";return t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal changes-diff-modal",ref:f,children:[t.jsxs("div",{className:"modal-header changes-diff-modal-header",children:[t.jsxs("div",{className:"changes-diff-header-title",children:[t.jsx(Si,{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(pc,{})}),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:w,disabled:d===null||d>=s.length-1,title:"Next file (Ctrl+↓)","aria-label":"Next file",children:t.jsx(qn,{})})]}),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(Vl,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx(ps,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(mn,{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(Nr,{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:gP(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:v?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"changes-diff-file-header-bar",children:[t.jsx("span",{className:"changes-diff-file-header-name",children:v.path}),t.jsxs("span",{className:"changes-diff-file-header-stats",children:["+",v.additions," -",v.deletions]})]}),v.patch?t.jsx("div",{className:"changes-diff-viewer",children:t.jsx("pre",{className:`changes-diff-patch ${m?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:hv(v.patch)})})}):t.jsx("div",{className:"changes-diff-empty",children:"No diff available for this file."})]}):t.jsxs("div",{className:"changes-diff-empty",children:[t.jsx(Si,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function pv(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function Sd(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(Nr,{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(Si,{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:pv("unknown")}),t.jsx("span",{className:"changes-file-path",title:a,children:t.jsx("bdo",{dir:"ltr",children:a})})]})},a))})]})}function xP({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,w]=i.useState([]),[v,b]=i.useState(null),[y,S]=i.useState(new Set),[j,C]=i.useState(null),[x,N]=i.useState(!0),[R,F]=i.useState(!1),E=a==="done",_=E&&!!r?.commitSha,K=a==="in-progress"||a==="in-review"||_,U=i.useCallback(async()=>{if(!K&&!E){h(!1);return}try{h(!0),p(null);const O=await C1(e,s);if(b(O.lineageId),w(O.associations),!K){c([]),u({filesChanged:0,additions:0,deletions:0});return}const M=await yb(e,void 0,s),D=M.files.map($=>({path:$.path,status:$.status,additions:$.additions,deletions:$.deletions,patch:$.patch}));c(D),u(M.stats),D.length>0&&(S(new Set([D[0].path])),C(0))}catch(O){p(Se(O)||"Failed to load task changes")}finally{h(!1)}},[e,s,K,E]);i.useEffect(()=>{U()},[U]);const A=O=>{S(M=>{const D=new Set(M);if(D.has(O))D.delete(O);else{D.add(O);const $=l.findIndex(k=>k.path===O);$!==-1&&C($)}return D})},T=O=>{if(O<0||O>=l.length)return;const M=l[O].path;S(new Set([M])),C(O)},H=j!==null&&j>0,Q=j!==null&&j<l.length-1;if(m)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--loading",children:[t.jsx("div",{className:"loading-spinner"}),t.jsx("span",{children:"Loading changes..."})]})});if(f)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--error",children:[t.jsx(Vs,{size:16}),t.jsxs("span",{children:["Error loading changes: ",f]})]})});if(!E&&!n)return o&&o.length>0?Sd(o,!1):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Si,{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(E&&!_){if(o&&o.length>0)return Sd(o,!0,r);const O=r?.filesChanged,M=r?.insertions,D=r?.deletions,$=O!=null||M!=null||D!=null;return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Si,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:$?`Merge summary: ${O??0} file${(O??0)===1?"":"s"} changed, +${M??0} additions, -${D??0} deletions.`:"No merge commit was recorded for this task."})]})})}const se=()=>t.jsxs("section",{className:"task-lineage-associations","aria-label":"Task commit associations",children:[t.jsxs("div",{className:"task-lineage-associations-header",children:[t.jsxs("h4",{children:[t.jsx(Nr,{size:16}),"Lineage commit associations"]}),v&&t.jsx("code",{className:"task-lineage-id",children:v})]}),g.length===0?t.jsx("p",{className:"task-lineage-associations-empty",children:"No associated commits recorded yet."}):t.jsx("div",{className:"task-lineage-associations-list",children:g.map(O=>{const M=O.matchedBy.replace(/-/g," ");return t.jsxs("article",{className:`task-lineage-association task-lineage-association--${O.confidence}`,children:[t.jsxs("div",{className:"task-lineage-association-main",children:[t.jsx("code",{className:"task-lineage-sha",children:O.commitSha.slice(0,7)}),t.jsx("span",{className:"task-lineage-subject",children:O.commitSubject})]}),t.jsxs("div",{className:"task-lineage-association-meta",children:[t.jsx("span",{children:new Date(O.authoredAt).toLocaleString()}),t.jsxs("span",{children:["Confidence: ",O.confidence]}),t.jsxs("span",{children:["Match: ",M]}),t.jsxs("span",{children:["Task snapshot: ",O.taskIdSnapshot]})]}),O.note&&t.jsx("p",{className:"task-lineage-note",children:O.note})]},`${O.commitSha}-${O.matchedBy}`)})})]});return l.length===0?o&&o.length>0?Sd(o,E,r):t.jsxs("div",{className:"detail-section task-changes-tab",children:[se(),t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Si,{size:24}),t.jsx("p",{children:"No files modified."}),t.jsx("span",{className:"task-changes-state-hint",children:E?"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:[se(),E&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Nr,{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(Si,{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:()=>H&&T(j-1),disabled:!H,title:"Previous file","aria-label":"Previous file",children:t.jsx(pc,{})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:j!==null?`${j+1}/${l.length}`:`—/${l.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>Q&&T(j+1),disabled:!Q,title:"Next file","aria-label":"Next file",children:t.jsx(qn,{})})]}),t.jsx("button",{className:`btn btn-sm ${x?"btn-primary":""}`,onClick:()=>N(O=>!O),title:x?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(Vl,{size:14})})]}),t.jsxs("div",{className:"changes-header-actions-secondary",children:[t.jsx("button",{className:"btn btn-sm",onClick:U,disabled:m,children:"Refresh"}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>F(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:t.jsx(wc,{})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map(O=>{const M=y.has(O.path);return t.jsxs("div",{className:`changes-file-item ${M?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>A(O.path),children:[t.jsx("span",{className:"changes-file-toggle",children:M?t.jsx(gn,{size:14}):t.jsx(qn,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${O.status}`,title:O.status,children:pv(O.status)}),t.jsx("span",{className:"changes-file-path",title:O.path,children:t.jsx("bdo",{dir:"ltr",children:O.path})}),t.jsxs("span",{className:"changes-file-stat",title:`+${O.additions} -${O.deletions}`,children:["+",O.additions," -",O.deletions]})]}),M&&O.patch&&t.jsx("div",{className:"changes-file-content",children:t.jsx("pre",{className:`changes-diff-patch ${x?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:hv(O.patch)})})})]},O.path)})}),t.jsx(bP,{isOpen:R,taskId:e,files:l,stats:d,mergeDetails:r,column:a,onClose:()=>F(!1),onRefresh:U})]})}function Xp(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function vP(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function T8(e,n){const s=vP(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 Zp(e){const n=e?.trim()??"";return Sc.test(n)?n:""}function fv(e,n){const s=Zp(e?.githubTrackingDefaultRepo);return s||Zp(n?.githubTrackingDefaultRepo)}function yP(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}const ef=["image/png","image/jpeg","image/gif","image/webp"];function wP(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 gv({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:w,priority:v,onPriorityChange:b,executorModel:y,onExecutorModelChange:S,validatorModel:j,onValidatorModelChange:C,planningModel:x,onPlanningModelChange:N,thinkingLevel:R,onThinkingLevelChange:F,presetMode:E,onPresetModeChange:_,selectedPresetId:K,onSelectedPresetIdChange:U,selectedWorkflowSteps:A,onWorkflowStepsChange:T,onDefaultOnApplied:H,pendingImages:Q,onImagesChange:se,tasks:O,projectId:M,disabled:D=!1,addToast:$,isActive:k=!0,onAutoSaveDescription:X,onPlanningMode:le,onSubtaskBreakdown:ke,onClose:He,renderBelowPrimary:ye,renderBelowModelConfiguration:je,hideDependencies:ne,autoExpandMoreOptionsOnSelection:fe=!0,reviewLevel:Z,onReviewLevelChange:re,executionMode:q,onExecutionModeChange:L,githubTrackingEnabled:xe,onGithubTrackingEnabledChange:he,githubRepoOverride:B,onGithubRepoOverrideChange:pe}){const ze=(ne?!1:o.length>0)||Q.length>0||A.length>0||E!=="default"||(v??Ps)!==Ps||y!==""||j!==""||(x||"")!==""||(R||"")!==""||Z!==void 0||q==="fast"||(c||"")!==""||(u||"")!==""||(h||"")!==""||xe===!0||(B||"")!=="",[ae,Ve]=i.useState(!1),[Te,rt]=i.useState(fe?ze:!1),[Be,ce]=i.useState(""),[Re,Le]=i.useState([]),[ct,Ue]=i.useState([]),[ue,oe]=i.useState([]),[Ee,ft]=i.useState(!1),[ht,tt]=i.useState(null),[xt,Me]=i.useState(null),[Ye,dt]=i.useState([]),[wt,St]=i.useState("idle"),[Fe,J]=i.useState(!1),[me,Ze]=i.useState(!1),[be,gt]=i.useState(!1),$t=i.useRef(null),Ie=i.useRef(null),ge=i.useRef(null),st=i.useRef(null),yt=i.useRef(null),pt=i.useRef(null),vt=i.useRef(null),Ut=i.useRef(!1),Dt=i.useRef(ze),nn=i.useRef(n.trim()),on=i.useRef(n.trim());i.useEffect(()=>{k&&(ft(!0),Ws().then(W=>{Le(W.models),Ue(W.favoriteProviders),oe(W.favoriteModels)}).catch(()=>{}).finally(()=>ft(!1)),kc(M).then(W=>tt(W)).catch(()=>tt(null)),Ko(M).then(W=>dt(W.filter(Y=>Y.enabled))).catch(()=>dt([])),na().then(W=>Me(W)).catch(()=>Me(null)))},[k,M]);const sn=ht?.modelPresets||[],ln=sn.find(W=>W.id===K),xn=fv(ht,xt),qt=(B||"").trim(),Qt=qt.length>0&&!Sc.test(qt),hn=(ne?!1:o.length>0)||Q.length>0||A.length>0||E!=="default"||(v??Ps)!==Ps||y!==""||j!==""||(x||"")!==""||(R||"")!==""||Z!==void 0||q==="fast"||(c||"")!==""||(u||"")!==""||(h||"")!==""||xe===!0||(B||"")!=="";i.useEffect(()=>{if(e!=="create"||!k||!ht?.autoSelectModelPreset)return;const W=(ht.defaultPresetBySize,void 0);if(W){const Y=Xp(W);U(W.id),_("preset"),S(Y.executorValue),C(Y.validatorValue)}},[k,ht,sn,e]);const Zt=i.useRef(!1),ve=i.useRef(!1);i.useEffect(()=>{if(e!=="create"||!k||Zt.current||Ye.length===0)return;const W=Ye.filter(_e=>_e.defaultOn);if(W.length===0)return;Zt.current=!0;const Y=W.map(_e=>_e.id);T(Y),H?.(Y)},[e,k,Ye]),i.useEffect(()=>{k||(Zt.current=!1)},[k]),i.useEffect(()=>{e!=="create"||!k||he&&(ve.current||ht&&(he(ht.githubTrackingEnabledByDefault??!1),ve.current=!0))},[e,k,ht,he]),i.useEffect(()=>{k||(ve.current=!1)},[k]),i.useEffect(()=>{if(!fe){Dt.current=hn;return}hn&&!Dt.current&&rt(!0),Dt.current=hn},[hn,fe]),i.useEffect(()=>{Te||(Ve(!1),ce(""))},[Te]),i.useEffect(()=>{e!=="edit"||!k||st.current&&(st.current.focus(),st.current.select())},[e,k]),i.useEffect(()=>{if(!ae)return;const W=Y=>{Ie.current&&!Ie.current.contains(Y.target)&&Ve(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[ae]),i.useEffect(()=>{(e!=="edit"||D)&>(!1)},[e,D]),i.useEffect(()=>{if(e!=="edit"){St("idle");return}const W=n.trim();nn.current=W,on.current=W,St("idle")},[e]),i.useEffect(()=>{if(e!=="edit"||!X||!k)return;const W=n.trim(),Y=nn.current;if(W===Y||W===on.current){pt.current&&(clearTimeout(pt.current),pt.current=null),Ut.current||St("idle");return}return pt.current&&clearTimeout(pt.current),pt.current=setTimeout(async()=>{if(!Ut.current){Ut.current=!0,St("saving");try{await X(W),on.current=W,St("saved"),vt.current&&clearTimeout(vt.current),vt.current=setTimeout(()=>{St("idle"),vt.current=null},2e3)}catch{St("idle")}finally{Ut.current=!1,pt.current=null}}},1500),()=>{pt.current&&(clearTimeout(pt.current),pt.current=null)}},[e,n,X,k]),i.useEffect(()=>()=>{pt.current&&clearTimeout(pt.current),vt.current&&clearTimeout(vt.current)},[]),i.useEffect(()=>{if(!Fe)return;const W=Y=>{$t.current&&!$t.current.contains(Y.target)&&J(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[Fe]);const Pe=i.useCallback(W=>{const Y=W.clipboardData?.items;if(Y)for(let _e=0;_e<Y.length;_e++){const ut=Y[_e];if(ut.type.startsWith("image/")){const At=ut.getAsFile();if(At&&ef.includes(At.type)){W.preventDefault(),se([...Q,{file:At,previewUrl:URL.createObjectURL(At)}]);return}}}},[Q,se]),Ke=i.useCallback(W=>{W.preventDefault();const Y=W.dataTransfer.files;for(let _e=0;_e<Y.length;_e++){const ut=Y[_e];if(ef.includes(ut.type)){se([...Q,{file:ut,previewUrl:URL.createObjectURL(ut)}]);return}}},[Q,se]),at=i.useCallback(W=>{const Y=Q[W];Y&&URL.revokeObjectURL(Y.previewUrl),se(Q.filter((_e,ut)=>ut!==W))},[Q,se]),We=i.useCallback(W=>{l(o.includes(W)?o.filter(Y=>Y!==W):[...o,W])},[o,l]),It=(W,Y)=>W.length>Y?W.slice(0,Y)+"…":W,Lt=i.useCallback(W=>{s(W.target.value);const Y=W.target;Y.style.height="auto",Y.style.height=Y.scrollHeight+"px"},[s]),Bt=i.useCallback(()=>{gt(W=>!W)},[]),Gt=i.useCallback(W=>{!be||W.key!=="Escape"||(W.preventDefault(),W.stopPropagation(),gt(!1))},[be]),bt=i.useCallback(async W=>{const Y=n.trim();if(!(!Y||me)){Ze(!0);try{const _e=await fb(Y,W,M);s(_e),J(!1),$("Description refined with AI","success"),ge.current&&(ge.current.style.height="auto",ge.current.style.height=ge.current.scrollHeight+"px")}catch(_e){const ut=gb(_e);$(ut,"error")}finally{Ze(!1)}}},[n,me,$,s,M]),Ot=i.useCallback(async W=>{const Y=ct,ut=Y.includes(W)?Y.filter(At=>At!==W):[W,...Y];Ue(ut);try{await Bn({favoriteProviders:ut,favoriteModels:ue})}catch{Ue(Y)}},[ct,ue]),en=i.useCallback(async W=>{const Y=ue,ut=Y.includes(W)?Y.filter(At=>At!==W):[W,...Y];oe(ut);try{await Bn({favoriteProviders:ct,favoriteModels:ut})}catch{oe(Y)}},[ue,ct]),Kt=i.useCallback(W=>{if(W<=0)return;const Y=[...A];[Y[W-1],Y[W]]=[Y[W],Y[W-1]],T(Y)},[A,T]),Sn=i.useCallback(W=>{if(W>=A.length-1)return;const Y=[...A];[Y[W],Y[W+1]]=[Y[W+1],Y[W]],T(Y)},[A,T]),dn=i.useCallback(W=>{T(A.filter(Y=>Y!==W))},[A,T]),Jt=new Map;for(const W of Ye)Jt.set(W.id,{name:W.name,description:W.description});const tn=O.filter(W=>!o.includes(W.id)).sort((W,Y)=>{const _e=Y.createdAt.localeCompare(W.createdAt);if(_e!==0)return _e;const ut=parseInt(W.id.slice(W.id.lastIndexOf("-")+1),10)||0;return(parseInt(Y.id.slice(Y.id.lastIndexOf("-")+1),10)||0)-ut}),Ne=Be?tn.filter(W=>W.id.toLowerCase().includes(Be.toLowerCase())||W.title&&W.title.toLowerCase().includes(Be.toLowerCase())||W.description&&W.description.toLowerCase().includes(Be.toLowerCase())):tn;return t.jsxs("div",{className:"task-form",onDrop:Ke,onDragOver:W=>W.preventDefault(),onPaste:Pe,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:st,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:a||"",onChange:W=>r(W.target.value),disabled:D})]}),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${wt==="idle"?"":" is-visible"}`,"aria-live":"polite",children:wt==="saving"?"Saving...":wt==="saved"?"Saved":""})]}),t.jsxs("div",{className:`description-with-refine${be?" description--fullscreen":""}`,ref:$t,onKeyDown:Gt,children:[be&&t.jsxs("div",{className:"description-fullscreen-header",children:[t.jsx("span",{children:"Editing Description"}),t.jsx("button",{type:"button",className:"btn btn-sm description-expand-btn",onClick:Bt,"aria-label":"Collapse description",title:"Collapse description",children:t.jsx(qo,{size:14})})]}),t.jsx("textarea",{ref:ge,autoFocus:e==="create",id:"task-form-description",value:n,onChange:Lt,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:D||me}),(()=>{const W=!!n.trim()&&!D;return t.jsxs(t.Fragment,{children:[!be&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${W?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:Bt,"aria-label":"Expand description",title:"Expand description",children:t.jsx(wc,{size:14})}),W&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${me?"refine-button--loading":""}`,onClick:()=>J(Y=>!Y),disabled:me,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(ms,{size:12,style:{verticalAlign:"middle"}}),me?"Refining...":"Refine"]})]})})(),Fe&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:W=>W.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>bt("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:()=>bt("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:()=>bt("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:()=>bt("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"&&(le||ke)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[le&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const W=n.trim();if(!W){$("Enter a description first","error");return}He?.(),le(W)},disabled:D||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),ke&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const W=n.trim();if(!W){$("Enter a description first","error");return}He?.(),ke(W)},disabled:D||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),ye,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>rt(W=>!W),"aria-expanded":Te,"aria-controls":"task-form-more-options",disabled:D,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),Te?t.jsx(Li,{size:14}):t.jsx(gn,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${Te?"":" collapsed"}`,"aria-hidden":!Te,hidden:!Te,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Attachments"}),Q.length>0&&t.jsx("div",{className:"inline-create-previews",children:Q.map((W,Y)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:W.previewUrl,alt:W.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>at(Y),disabled:D,title:"Remove image",children:"×"})]},W.previewUrl))}),t.jsx("input",{ref:yt,type:"file",accept:"image/*",onChange:W=>{const Y=W.target.files?.[0];Y&&(se([...Q,{file:Y,previewUrl:URL.createObjectURL(Y)}]),W.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>yt.current?.click(),disabled:D,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:W=>f(W.target.value||void 0),disabled:D||g,children:[t.jsx("option",{value:"",children:"Use project default / local"}),(p??[]).map(W=>t.jsxs("option",{value:W.id,children:[W.name," (",yP(W.status),")"]},W.id))]}),(()=>{const W=(p??[]).find(Y=>Y.id===h);return W?t.jsx("div",{className:"task-form-node-status",children:t.jsx(Ua,{status:W.status,showLabel:!0})}):null})(),t.jsx("small",{children:w??"Task override takes priority over project default node routing."})]}),!ne&&t.jsx(t.Fragment,{children:t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"dep-trigger-wrap",ref:Ie,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>Ve(W=>!W),disabled:D,children:o.length>0?`${o.length} selected`:"Add dependencies"}),ae&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Be,onChange:W=>ce(W.target.value),onClick:W=>W.stopPropagation()}),Ne.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Ne.map(W=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(W.id)?" selected":""}`,onClick:()=>We(W.id),onMouseDown:Y=>Y.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:W.id}),t.jsx("span",{className:"dep-dropdown-title",children:It(W.title||W.description||W.id,30)})]},W.id))]})]}),o.length>0&&t.jsx("div",{className:"selected-deps",children:o.map(W=>t.jsxs("span",{className:"dep-chip",children:[W,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>We(W),disabled:D,children:"×"})]},W))})]})}),(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:W=>d(W.target.value),placeholder:"e.g. feature/my-task",disabled:D})]}),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:W=>m(W.target.value),placeholder:"e.g. main",disabled:D})]})]}),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:v??Ps,onChange:W=>b(W.target.value),disabled:D,children:wa.map(W=>t.jsx("option",{value:W,children:W[0].toUpperCase()+W.slice(1)},W))})]}),L&&q!==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:q,onChange:W=>L(W.target.value),disabled:D,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),Ee?t.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):Re.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"?K:E,onChange:W=>{const Y=W.target.value;if(Y==="default"){_("default"),U(""),S(""),C("");return}if(Y==="custom"){_("custom"),U("");return}const _e=sn.find(At=>At.id===Y),ut=Xp(_e);_("preset"),U(Y),S(ut.executorValue),C(ut.validatorValue)},disabled:D,children:[t.jsx("option",{value:"default",children:"Use default"}),sn.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,sn.map(W=>t.jsx("option",{value:W.id,children:W.name},W.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),E==="preset"&&ln?t.jsxs("small",{children:["Using preset: ",ln.name]}):null,E==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>_("custom"),disabled:D,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(_s,{id:"executor-model",label:"Executor Model",value:y,onChange:W=>{_("custom"),U(""),S(W)},models:Re,disabled:D||E==="preset",favoriteProviders:ct,onToggleFavorite:Ot,favoriteModels:ue,onToggleModelFavorite:en})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Reviewer"}),t.jsx(_s,{id:"validator-model",label:"Reviewer Model",value:j,onChange:W=>{_("custom"),U(""),C(W)},models:Re,disabled:D||E==="preset",favoriteProviders:ct,onToggleFavorite:Ot,favoriteModels:ue,onToggleModelFavorite:en})]}),N&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),t.jsx(_s,{id:"planning-model",label:"Planning Model",value:x||"",onChange:W=>{_("custom"),U(""),N(W)},models:Re,disabled:D||E==="preset",favoriteProviders:ct,onToggleFavorite:Ot,favoriteModels:ue,onToggleModelFavorite:en})]}),F&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"thinking-level",className:"model-select-label",children:"Thinking"}),t.jsxs("select",{id:"thinking-level",value:R||"",onChange:W=>F(W.target.value),disabled:D||E==="preset",children:[t.jsxs("option",{value:"",children:["Default (",ht?.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:Z??"",onChange:W=>re(W.target.value===""?void 0:parseInt(W.target.value,10)),disabled:D,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"})]})]})]})]}),je,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:Ye.length>0&&Ye.map(W=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${W.id}`,children:[t.jsx("input",{type:"checkbox",checked:A.includes(W.id),onChange:Y=>{T(Y.target.checked?[...A,W.id]:A.filter(_e=>_e!==W.id))},disabled:D}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[W.name,wP(W.phase||"pre-merge",W.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:W.description})]})]},W.id))})]}),A.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:"}),A.map((W,Y)=>{const _e=Jt.get(W);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${W}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:Y+1}),t.jsx("span",{className:"workflow-step-order-name",children:_e?.name||W}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Kt(Y),disabled:D||Y===0,"data-testid":`workflow-step-move-up-${W}`,title:"Move up",children:t.jsx(Li,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Sn(Y),disabled:D||Y===A.length-1,"data-testid":`workflow-step-move-down-${W}`,title:"Move down",children:t.jsx(gn,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>dn(W),disabled:D,"data-testid":`workflow-step-remove-${W}`,title:"Remove",children:t.jsx(mn,{})})]})]},W)})]})]}),(he||pe)&&t.jsxs("div",{className:"form-group","data-testid":"task-form-github-tracking",children:[t.jsx("label",{children:"GitHub Tracking"}),he&&t.jsxs("label",{className:"checkbox-label",htmlFor:"task-github-tracking-enabled",children:[t.jsx("input",{id:"task-github-tracking-enabled",type:"checkbox",checked:xe===!0,onChange:W=>{ve.current=!0,he(W.target.checked)},disabled:D}),"Enable GitHub issue tracking for this task"]}),pe&&t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"task-github-repo-override",className:"model-select-label",children:"Repository (owner/repo)"}),t.jsx("input",{id:"task-github-repo-override",className:"input",value:B||"",onChange:W=>pe(W.target.value),placeholder:xn||"owner/repo",disabled:D}),Qt?t.jsx("div",{className:"form-error",children:"Repository must be in owner/repo format."}):null]})]})]})]})}const tf={p:({children:e,...n})=>t.jsx("p",{...n,children:Ys(e)}),li:({children:e,...n})=>t.jsx("li",{...n,children:Ys(e)}),code:({children:e,...n})=>t.jsx("code",{...n,children:Ys(e)}),pre:({children:e,className:n,...s})=>t.jsx("pre",{...s,className:["workflow-markdown-pre",n].filter(Boolean).join(" "),children:Ys(e)}),table:({children:e,className:n,...s})=>t.jsx("table",{...s,className:["workflow-markdown-table",n].filter(Boolean).join(" "),children:e})};function kP(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function jP(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 NP(e){return e?new Date(e).toLocaleString():null}function SP(e){const n=e.split(`
|
|
684
|
+
`);return n.length<=1?e:`${n.length} lines`}function xl(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 CP({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]),o.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:["⚡ ",Cs(l.text),l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",Cs(l.detail)]})]},c):l.type==="tool_result"?t.jsxs("div",{className:"workflow-live-log-tool-result",children:["✓ ",Cs(l.text),l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",Cs(l.detail)]})]},c):l.type==="tool_error"?t.jsxs("div",{className:"workflow-live-log-tool-error",children:["✗ ",Cs(l.text),l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",Cs(l.detail)]})]},c):l.type==="thinking"?t.jsx("div",{className:"workflow-live-log-thinking",children:Cs(l.text)},c):t.jsx("span",{className:"workflow-live-log-text",children:Cs(l.text)},c))})}function EP({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,w]=i.useState([]),[v,b]=i.useState(!1),y=n.some(k=>k.status==="pending"),{entries:S}=lv(e,!!l&&y,o);i.useEffect(()=>{let k=!1;return Ko(o).then(X=>{k||w(X.filter(le=>le.enabled))}).catch(()=>{k||w([])}),()=>{k=!0}},[o]);const j=a??[],C=i.useMemo(()=>g.map(k=>({id:k.id,name:k.name,description:k.description,phase:k.phase||"pre-merge"})),[g]),x=i.useMemo(()=>new Map(C.map(k=>[k.id,k])),[C]),N=k=>{u(X=>({...X,[k]:!X[k]}))},R=k=>{h(X=>{const le=X[k]??"markdown";return{...X,[k]:le==="markdown"?"plain":"markdown"}})},F=k=>{p(k)},E=()=>{p(null)};i.useEffect(()=>{if(!f)return;const k=X=>{X.key==="Escape"&&E()};return document.addEventListener("keydown",k),()=>{document.removeEventListener("keydown",k)}},[f]);const _=i.useCallback((k,X)=>{if(c){if(X){if(j.includes(k)){c(j);return}c([...j,k]);return}c(j.filter(le=>le!==k))}},[c,j]),K=i.useCallback(k=>{if(!c||k<=0)return;const X=[...j];[X[k-1],X[k]]=[X[k],X[k-1]],c(X)},[c,j]),U=i.useCallback(k=>{if(!c||k>=j.length-1)return;const X=[...j];[X[k],X[k+1]]=[X[k+1],X[k]],c(X)},[c,j]),A=i.useCallback(k=>{c&&c(j.filter(X=>X!==k))},[c,j]),T=n.length>0,H=j.length>0;i.useEffect(()=>{r||b(!1)},[r]);const Q=i.useMemo(()=>j.map(k=>{const X=x.get(k);return{id:k,name:X?.name||k,description:X?.description||"Step definition not found.",phase:X?.phase||"pre-merge"}}),[j,x]),se=()=>!r||!v||s?null:t.jsxs("div",{className:"workflow-results-editor","data-testid":"workflow-steps-editor",children:[t.jsxs("div",{className:"workflow-steps-section",children:[t.jsx("small",{className:"workflow-steps-description",children:"Select steps to run after task implementation completes"}),t.jsx("div",{className:"workflow-steps-list",children:C.map(k=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${k.id}`,children:[t.jsx("input",{type:"checkbox",checked:j.includes(k.id),onChange:X=>_(k.id,X.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[k.name,xl(k.phase,k.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:k.description})]})]},k.id))})]}),j.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),j.map((k,X)=>{const le=x.get(k);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${k}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:X+1}),t.jsx("span",{className:"workflow-step-order-name",children:le?.name||k}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>K(X),disabled:X===0,"data-testid":`workflow-step-move-up-${k}`,title:"Move up",children:t.jsx(Li,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>U(X),disabled:X===j.length-1,"data-testid":`workflow-step-move-down-${k}`,title:"Move down",children:t.jsx(gn,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>A(k),"data-testid":`workflow-step-remove-${k}`,title:"Remove",children:t.jsx(mn,{})})]})]},k)})]})]}),O=()=>{if(s)return t.jsxs("div",{className:"workflow-results-loading","data-testid":"workflow-results-loading",children:[t.jsx("div",{className:"workflow-results-spinner"}),t.jsx("span",{children:"Loading workflow results…"})]});if(!T)return t.jsxs("div",{className:"workflow-results-empty","data-testid":"workflow-results-empty",children:[t.jsx("p",{children:"No workflow steps configured for this task."}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."})]});const k=n.filter(ye=>ye.status==="passed").length,X=n.filter(ye=>ye.status==="failed").length,le=n.filter(ye=>ye.status==="skipped").length,ke=n.filter(ye=>ye.status==="pending").length,He=[`${n.length} step${n.length!==1?"s":""}`];return k>0&&He.push(`${k} passed`),X>0&&He.push(`${X} failed`),le>0&&He.push(`${le} skipped`),ke>0&&He.push(`${ke} running`),t.jsxs("div",{className:"workflow-results-list","data-testid":"workflow-results-list",children:[t.jsx("div",{className:"workflow-results-summary-bar","data-testid":"workflow-results-summary",children:He.join(" · ")}),n.map((ye,je)=>{const ne=ye.phase||"pre-merge",fe=d[ye.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${ye.status}`,"data-testid":`workflow-result-item-${ye.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[ye.workflowStepName,xl(ne,ye.workflowStepId,"workflow-result-phase")]}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${ye.status}`,"data-testid":`workflow-result-badge-${ye.workflowStepId}`,children:kP(ye.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[ye.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",NP(ye.startedAt)]}),ye.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:jP(ye.startedAt,ye.completedAt)})]}),ye.status==="pending"&&ye.startedAt?t.jsx(CP,{entries:S,startedAt:ye.startedAt,stepId:ye.workflowStepId}):ye.output?t.jsxs("div",{className:"workflow-result-output-section",children:[t.jsxs("div",{className:"workflow-result-output-header",children:[t.jsx("span",{className:"workflow-result-output-label",children:"Output:"}),t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-toggle",onClick:()=>N(ye.workflowStepId),"data-testid":`workflow-result-toggle-${ye.workflowStepId}`,children:fe?"Hide output":"Show output"}),!fe&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${ye.workflowStepId}`,children:SP(ye.output)}),fe&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-mode-toggle",onClick:()=>R(ye.workflowStepId),"data-testid":`workflow-result-mode-toggle-${ye.workflowStepId}`,title:(m[ye.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(m[ye.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm workflow-result-expand-toggle",onClick:()=>F(ye.workflowStepId),"data-testid":`workflow-result-expand-${ye.workflowStepId}`,title:"Expand output",children:t.jsx(wc,{size:12})})]})]}),fe&&t.jsx("div",{className:`workflow-result-output${(m[ye.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${ye.workflowStepId}`,children:(m[ye.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(xi,{remarkPlugins:[vi],components:tf,children:ye.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:Cs(ye.output)})})]}):null]},`${ye.workflowStepId}-${je}`)})]})},M=r?t.jsx("button",{type:"button",className:"btn btn-sm workflow-results-edit-toggle",onClick:()=>b(k=>!k),"data-testid":"workflow-steps-edit-toggle","aria-label":v?"Done editing workflow steps":"Edit workflow steps",title:v?"Done":"Edit",children:v?t.jsxs(t.Fragment,{children:[t.jsx(ks,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(Hs,{size:14}),"Edit"]})}):null,D=!s&&!T&&H,$=r&&T;return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[D?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:[Q.length," step",Q.length===1?"":"s"]})]}),M]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:Q.map(k=>t.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${k.id}`,children:[t.jsxs("div",{className:"workflow-configured-name",children:[t.jsx("span",{className:"workflow-configured-name-text",children:k.name}),xl(k.phase,k.id,"workflow-configured-phase")]}),t.jsx("p",{className:"workflow-configured-description",children:k.description})]},k.id))}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."}),se()]}):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"}),M]}),O(),se()]}),f&&(()=>{const k=n.find(ke=>ke.workflowStepId===f);if(!k)return null;const X=m[k.workflowStepId]??"markdown",le=k.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:ke=>{ke.target===ke.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:k.workflowStepName}),xl(le,k.workflowStepId,"workflow-output-modal-phase")]}),t.jsxs("div",{className:"workflow-output-modal-controls",children:[t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-mode-toggle",onClick:()=>R(k.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:X==="markdown"?"Switch to plain text":"Switch to markdown",children:X==="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(mn,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${X==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:X==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(xi,{remarkPlugins:[vi],components:tf,children:k.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:Cs(k.output)})})})]})})})()]})}function _P(e){return e==="block"?"Block execution":e==="fallback-local"?"Fall back to local":"Not configured"}const MP=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function AP(e){return e!==void 0&&e!=="online"}function RP({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),Yl().then(E=>{o(E)}).catch(E=>{u(Se(E)||"Failed to load nodes")}).finally(()=>{c(!1)})},[]);const w=i.useMemo(()=>new Map(r.map(E=>[E.id,E])),[r]),v=i.useMemo(()=>[...r].sort((E,_)=>E.name.localeCompare(_.name)),[r]),b=n,y=e.nodeId??b?.defaultNodeId??null,S=e.nodeId?"Per-task override":b?.defaultNodeId?"Project default":"No routing",j=y?w.get(y):void 0,C=j?`${j.name} (${j.type})`:y?`${y} (node unavailable or unknown)`:"Local (no routing configured)",x=e.column==="in-progress"||MP.has(e.status),N=x||f||l,R=i.useCallback(async E=>{if(E===m)return;const _=e.id,K=m;h(E),p(!0);try{const U=await Us(_,{nodeId:E||null});if(g.current!==_)return;h(U.nodeId??""),a?.(U),s(E?"Node override updated":"Node override cleared","success")}catch(U){if(g.current!==_)return;h(K),s(Se(U)||"Failed to update node override","error")}finally{g.current===_&&p(!1)}},[s,a,m,e.id]),F=i.useCallback(()=>{R("")},[R]);return t.jsxs("div",{className:"routing-tab",children:[t.jsx("h4",{children:"Task Routing"}),t.jsx("p",{className:"routing-tab__intro",children:"View the effective execution node and control per-task node override."}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Routing Summary"}),t.jsxs("div",{className:"routing-summary-grid",role:"list",children:[t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Effective node"}),t.jsxs("span",{className:"routing-summary-value",children:[j?t.jsx(Ua,{status:j.status,compact:!0}):null,C,AP(j?.status)?t.jsx("span",{className:"routing-summary-warning",children:"Unhealthy"}):null]})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Routing source"}),t.jsx("span",{className:"routing-summary-value",children:S})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Unavailable-node policy"}),t.jsx("span",{className:"routing-summary-value",children:_P(b?.unavailableNodePolicy)})]})]}),x&&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"}),x?t.jsx("div",{className:"routing-tab__warning-banner",children:"Node override cannot be changed while the task is active."}):null,t.jsx("label",{className:"routing-tab__selector-label",htmlFor:`routing-node-${e.id}`,children:"Select execution node"}),t.jsxs("select",{id:`routing-node-${e.id}`,className:"select routing-tab__selector",value:m,disabled:N,onChange:E=>{R(E.target.value)},children:[t.jsx("option",{value:"",children:"Use project default"}),v.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: ",w.get(e.nodeId)?.name??e.nodeId]}),t.jsx("button",{type:"button",className:"btn btn-sm",disabled:x||f,onClick:F,children:"Clear override"})]}):null]})]})}const IP=/^[a-zA-Z0-9_-]{1,64}$/,TP=200;function nf(e){return e?new Date(e).toLocaleString():""}function PP(e,n=TP){return e.length<=n?e:e.substring(0,n)+"…"}function $P({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),[w,v]=i.useState(""),[b,y]=i.useState(null),[S,j]=i.useState([]),[C,x]=i.useState(!1),[N,R]=i.useState(!1),[F,E]=i.useState(""),[_,K]=i.useState(""),[U,A]=i.useState(!1),[T,H]=i.useState(null),[Q,se]=i.useState(null),[O,M]=i.useState(!1),D=i.useCallback(async()=>{try{const ne=await sN(e,a);l(ne)}catch(ne){n(Se(ne)||"Failed to load documents","error")}finally{d(!1)}},[e,a,n]);i.useEffect(()=>{D()},[D]);async function $(ne){u===ne.key?(m(null),f(""),g(null),v(""),y(null),j([]),M(!1)):(m(ne.key),f(ne.content),g(null),v(""),y(null),j([]),M(!1))}async function k(ne){if(b===ne)y(null),j([]);else{y(ne),x(!0);try{const fe=await iN(e,ne,a);j(fe)}catch(fe){n(Se(fe)||"Failed to load revisions","error")}finally{x(!1)}}}function X(){u&&(g(u),v(h))}function le(){g(null),v("")}async function ke(){if(!(!p||!w.trim())){A(!0);try{await Vm(e,p,w,{},a),g(null),v(""),await D();const ne=o.find(fe=>fe.key===p);ne&&f(ne.content),n("Document saved","success")}catch(ne){n(Se(ne)||"Failed to save document","error")}finally{A(!1)}}}async function He(){const ne=F.trim(),fe=_.trim();if(!ne){n("Document key is required","error");return}if(!IP.test(ne)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!fe){n("Content is required","error");return}A(!0);try{await Vm(e,ne,fe,{},a),R(!1),E(""),K(""),await D(),n("Document created","success")}catch(Z){n(Se(Z)||"Failed to create document","error")}finally{A(!1)}}async function ye(ne){H(ne);try{await aN(e,ne,a),se(null),H(null),u===ne&&(m(null),f("")),b===ne&&(y(null),j([])),await D(),n("Document deleted","success")}catch(fe){n(Se(fe)||"Failed to delete document","error")}finally{H(null)}}function je(ne){f(ne.content),g(null),v("")}return c?t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),t.jsx("div",{className:"detail-log-empty",children:"Loading documents…"})]}):t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),N&&t.jsxs("div",{className:"task-document-create-form",children:[t.jsx("h5",{children:"New Document"}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-key",children:"Key"}),t.jsx("input",{id:"doc-key",type:"text",className:"task-document-key-input",value:F,onChange:ne=>E(ne.target.value),placeholder:"e.g., plan, notes, research",disabled:U}),t.jsx("span",{className:"form-hint",children:"Alphanumeric, hyphens, underscores (1-64 chars)"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-content",children:"Content"}),t.jsx("textarea",{id:"doc-content",value:_,onChange:ne=>K(ne.target.value),rows:6,placeholder:"Enter document content…",disabled:U})]}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{R(!1),E(""),K("")},disabled:U,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void He(),disabled:U||!F.trim()||!_.trim(),children:U?"Creating…":"Create"})]})]}),o.length===0&&!N?t.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):t.jsx("div",{className:"task-documents-list",children:o.map(ne=>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(xa,{size:14}),t.jsx("span",{className:"task-document-key",children:ne.key}),t.jsxs("span",{className:"task-document-revision-badge",children:["v",ne.revision]})]}),t.jsxs("div",{className:"task-document-meta",children:[t.jsx("span",{className:"task-document-author",children:ne.author}),t.jsx("span",{className:"task-document-timestamp",children:nf(ne.updatedAt||ne.createdAt)})]})]}),u===ne.key&&p!==ne.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:()=>M(fe=>!fe),"aria-label":O?"Switch to plain text":"Switch to markdown","aria-pressed":O,title:O?"Switch to plain text":"Switch to markdown",children:O?"Markdown":"Plain"})}),t.jsx("div",{className:"task-document-content",children:O?t.jsx("div",{className:"task-document-content-markdown",children:t.jsx("div",{className:"markdown-body",children:t.jsx(xi,{remarkPlugins:[vi],children:h})})}):t.jsx("pre",{className:"task-document-content-text",children:h})}),b===ne.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(fe=>fe.revision<ne.revision).sort((fe,Z)=>Z.revision-fe.revision).map(fe=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>je(fe),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",fe.revision]}),t.jsx("span",{className:"revision-author",children:fe.author}),t.jsx("span",{className:"revision-timestamp",children:nf(fe.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:PP(fe.content,100)})]},fe.id))})]})]}),p===ne.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:w,onChange:fe=>v(fe.target.value),rows:10,disabled:U}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:le,disabled:U,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void ke(),disabled:U||!w.trim(),children:U?"Saving…":"Save"})]})]}),t.jsxs("div",{className:"task-document-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>void $(ne),children:u===ne.key?t.jsxs(t.Fragment,{children:[t.jsx(Li,{size:14})," Collapse"]}):t.jsxs(t.Fragment,{children:[t.jsx(gn,{size:14})," Expand"]})}),u===ne.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void k(ne.key),children:[t.jsx(Oa,{size:14})," History"]}),r&&p!==ne.key&&t.jsx("button",{className:"btn btn-sm",onClick:X,children:"Edit"}),r&&(Q===ne.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 ye(ne.key),disabled:T===ne.key,children:T===ne.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>se(null),disabled:T===ne.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>se(ne.key),children:t.jsx(Tn,{size:14})}))]})]})]},ne.key))}),r&&!N&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>R(!0),children:[t.jsx($n,{size:14})," New Document"]})]})}function vl(e){return e.toLocaleString()}function Cd(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function oo(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 DP(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=Wb(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 LP({tokenUsage:e,loading:n,task:s}){const a=Date.now(),r=qb(s?.log??[]),o=r.filter(g=>typeof g.durationMs=="number"),l=o.reduce((g,w)=>g+(w.durationMs??0),0),c=Vb(s?.log)??0,d=typeof s?.timedExecutionMs=="number"?s.timedExecutionMs:Math.max(l,c),u=o.reduce((g,w)=>!g||(w.durationMs??0)>(g.durationMs??0)?w:g,void 0),m=DP(s?.workflowStepResults??[]),f=Gb(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:oo(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:oo(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:oo(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} (${oo(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} (${oo(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 ${Cd(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:vl(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:vl(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:vl(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:vl(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:Cd(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:Cd(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}const km=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]),sf={p:({children:e,...n})=>t.jsx("p",{...n,children:Ys(e)}),li:({children:e,...n})=>t.jsx("li",{...n,children:Ys(e)}),code:({children:e,...n})=>{const s=typeof e=="string"?e:ga.Children.toArray(e).join(""),a=Cs(s);return a.length===1&&typeof a[0]=="string"?t.jsx("code",{...n,children:e}):t.jsx("code",{...n,children:a})}};function OP(e){let n=null;for(const s of e){if(s.agent!=="executor"||s.type!=="text")continue;const a=s.text.match(/^Executor using model: (.+?)\/(.+)$/);a&&(n={provider:a[1],modelId:a[2]})}return n}function FP(e){let n=null;for(const s of e){if(s.agent!=="reviewer"||s.type!=="text")continue;const a=s.text.match(/^Reviewer using model: (.+?)\/(.+)$/);a&&(n={provider:a[1],modelId:a[2]})}return n}function bv(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 zP(e,n,s,a){const r=OP(n);if(r)return r;if(km.has(e.status??"")||e.column==="in-progress"){const o=bv(s);if(o.provider&&o.modelId)return o}return Tb(e,a)}function BP(e,n,s,a){const r=FP(n);if(r)return r;if(km.has(e.status??"")||e.column==="in-progress"){const o=bv(s);if(o.provider&&o.modelId)return o}return Pb(e,a)}function UP(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 HP(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const a=UP(n);return a||$b(e,s)}function qP(e){switch(e){case"done":return"var(--color-success)";case"in-progress":return"var(--in-progress)";case"skipped":return"var(--text-dim)";case"pending":default:return"var(--border)"}}function Ed(e){const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(r/60),l=Math.floor(o/24);return r<1?"just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function VP(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function _d(e,n){return e.length>n?e.slice(0,n)+"…":e}function af(e=[],n=[]){return e.length===n.length&&e.every((s,a)=>s===n[a])}function Md(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function Ad(e){return e.trim()}function WP(e){const n=e.trim();return n.length>0?n:void 0}function Ki(e){return typeof e=="string"&&wa.includes(e)?e:Ps}function Ji(e){return e==="fast"?"fast":"standard"}function GP(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function KP(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 JP=i.lazy(()=>En(()=>import("./AgentDetailView-V32TpEe1.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(e=>({default:e.AgentDetailView})));function YP(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:GP(e.sourceMetadata)};case"research":return{label:"Research",contextInfo:KP(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 Rd=200,QP=new Set(["triage","todo"]),XP=new Set(["triage","todo","in-progress","in-review"]);function xv({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:w=!1,onRequestClose:v}){const[b,y]=i.useState(p),[S,j]=i.useState(()=>"prompt"in e?e:null),[C,x]=i.useState(()=>!("prompt"in e));i.useEffect(()=>{if("prompt"in e){j(e),x(!1);return}let ee=!1;return x(!0),j(null),Ba(e.id,n).then(De=>{ee||(j(De),x(!1))}).catch(()=>{ee||x(!1)}),()=>{ee=!0}},[e.id,n]);const N=S?{...S,...e,prompt:S.prompt,log:S.log,githubTracking:e.githubTracking??S.githubTracking}:{...e,prompt:""},R=e.status==="failed"||e.status==="stuck-killed"||e.status==="planning"||e.status==="needs-replan"||(e.stuckKillCount??0)>0||(e.recoveryRetryCount??0)>0||!!e.nextRecoveryAt,[F,E]=i.useState(null),[_,K]=i.useState(null),U=YP(N,{sourceAgentName:F?.name});i.useEffect(()=>{y(p)},[p]),i.useEffect(()=>{Q(!1)},[e.id]);const[A,T]=i.useState("activity"),[H,Q]=i.useState(!1),[se,O]=i.useState(e.attachments||[]),[M,D]=i.useState(!1),[$,k]=i.useState(e.dependencies||[]),[X,le]=i.useState(!1),[ke,He]=i.useState(""),[ye,je]=i.useState(null),[ne,fe]=i.useState([]),[Z,re]=i.useState(!1),[q,L]=i.useState(!1),[xe,he]=i.useState(!1),[B,pe]=i.useState(!1),[ze,ae]=i.useState(!1),[Ve,Te]=i.useState(N.prompt||""),[rt,Be]=i.useState(""),[ce,Re]=i.useState(!1),[Le,ct]=i.useState(""),[Ue,ue]=i.useState(!1),[oe,Ee]=i.useState(!1),[ft,ht]=i.useState(e.title||""),[tt,xt]=i.useState(e.description||""),[Me,Ye]=i.useState(e.dependencies||[]),[dt,wt]=i.useState(e.branch??""),[St,Fe]=i.useState(e.baseBranch??""),[J,me]=i.useState(""),[Ze,be]=i.useState(""),[gt,$t]=i.useState(""),[Ie,ge]=i.useState(""),[st,yt]=i.useState("default"),[pt,vt]=i.useState(void 0),[Ut,Dt]=i.useState(Ps),[nn,on]=i.useState(e.nodeId),[sn,ln]=i.useState(Ji(e.executionMode)),[xn,qt]=i.useState(""),[Qt,hn]=i.useState(e.enabledWorkflowSteps||[]),[Zt,ve]=i.useState(e.sourceIssue?.provider??""),[Pe,Ke]=i.useState(e.sourceIssue?.repository??""),[at,We]=i.useState(e.sourceIssue?.externalIssueId??""),[It,Lt]=i.useState(e.sourceIssue?.url??""),[Bt,Gt]=i.useState([]),[bt,Ot]=i.useState(!1),[en,Kt]=i.useState(Ki(e.priority)),[Sn,dn]=i.useState(!1),[Jt,tn]=i.useState(Ji(e.executionMode)),[Ne,W]=i.useState(!1),Y=i.useRef(!1),[_e,ut]=i.useState(!1),[At,zt]=i.useState(!1),[yn,Zn]=i.useState(!1),[vn,Dn]=i.useState(!1),[de,nt]=i.useState(e.githubTracking?.repoOverride??""),[ot,_t]=i.useState(null),[G,Oe]=i.useState(null),[Mt,Xt]=i.useState(!1),_n=i.useRef(null),Pn=i.useRef(null),kn=i.useRef(null),{getSlotsForId:Vn}=Eb(n),vs=Vn("task-detail-tab").map((ee,De)=>({entry:ee,tabId:`plugin-${ee.pluginId}-${De}`})),As=typeof b=="string"&&b.startsWith("plugin-")?vs.find(ee=>ee.tabId===b)??null:null;i.useEffect(()=>(Y.current=!0,()=>{Y.current=!1}),[]);const[bn,Ht]=i.useState(void 0),[On,Fn]=i.useState(null),[as,Wn]=i.useState([]),[Rs,In]=i.useState(!1),[rs,Ns]=i.useState(e.enabledWorkflowSteps||[]),ys=e.column==="in-progress"||km.has(e.status);i.useEffect(()=>{ht(e.title||""),xt(e.description||""),wt(e.branch??""),Fe(e.baseBranch??""),ve(e.sourceIssue?.provider??""),Ke(e.sourceIssue?.repository??""),We(e.sourceIssue?.externalIssueId??""),Lt(e.sourceIssue?.url??""),ln(Ji(e.executionMode)),Zn(!1),Dn(!1),nt(N.githubTracking?.repoOverride??""),_t(null),Oe(null),Ee(!1)},[e.id,e.title,e.description,e.branch,e.baseBranch,e.sourceIssue,e.executionMode,N.githubTracking]),i.useEffect(()=>{Ns(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),i.useEffect(()=>{Kt(Ki(e.priority))},[e.id,e.priority]),i.useEffect(()=>{tn(Ji(e.executionMode))},[e.id,e.executionMode]),i.useEffect(()=>{ot!==null&&N.githubTracking?.enabled===!0===ot&&_t(null)},[ot,N.githubTracking?.enabled]),i.useEffect(()=>{let ee=!1;return kc(n).then(De=>{ee||Ht(De)}).catch(()=>{}),na().then(De=>{ee||Fn(De)}).catch(()=>{ee||Fn(null)}),()=>{ee=!0}},[n]),i.useEffect(()=>{if(b!=="workflow")return;let ee=!1;return In(!0),qS(e.id,n).then(De=>{ee||Wn(De)}).catch(De=>{ee||h(`Failed to load workflow results: ${Se(De)}`,"error")}).finally(()=>{ee||In(!1)}),()=>{ee=!0}},[b,e.id,n,h]),i.useEffect(()=>{if(b!=="workflow")return;const ee=n?`?projectId=${encodeURIComponent(n)}`:"",De=Ct=>{try{const Wt=JSON.parse(Ct.data);Wt.id===e.id&&Array.isArray(Wt.workflowStepResults)&&Wn(Wt.workflowStepResults)}catch{}};return yi(`/api/events${ee}`,{events:{"task:updated":De}})},[b,e.id,n]),i.useEffect(()=>{X||He("")},[X]),i.useEffect(()=>{if(!e.assignedAgentId){je(null);return}const ee=ne.find(Ct=>Ct.id===e.assignedAgentId);if(ee){je(ee);return}let De=!1;return uu(e.assignedAgentId,n).then(Ct=>{De||je(Ct)}).catch(()=>{De||je(null)}),()=>{De=!0}},[e.assignedAgentId,n,ne]),i.useEffect(()=>{if(!e.sourceAgentId){E(null);return}const ee=ne.find(Ct=>Ct.id===e.sourceAgentId);if(ee){E(ee);return}let De=!1;return Promise.resolve(uu(e.sourceAgentId,n)).then(Ct=>{De||E(Ct??null)}).catch(()=>{De||E(null)}),()=>{De=!0}},[e.sourceAgentId,n,ne]),i.useEffect(()=>{re(!1)},[e.id]),i.useEffect(()=>{if(!(_e||At))return;const De=Ct=>{const Wt=Ct.target,ns=_n.current?.contains(Wt),Gi=kn.current?.contains(Wt);!ns&&_e&&ut(!1),!Gi&&At&&zt(!1)};return document.addEventListener("mousedown",De),()=>document.removeEventListener("mousedown",De)},[_e,At]),i.useEffect(()=>{if(!(_e||At))return;const De=Ct=>{Ct.key==="Escape"&&(Ct.stopPropagation(),_e&&ut(!1),At&&zt(!1))};return document.addEventListener("keydown",De),()=>document.removeEventListener("keydown",De)},[_e,At]),i.useEffect(()=>{ae(!1),Te(N.prompt||""),Be("")},[e.id,N.prompt]);const cs=QP.has(e.column)&&!bt,ss=XP.has(e.column)&&!bt,te=ot??N.githubTracking?.enabled===!0,we=N.githubTracking?.issue,P=ss&&!we&&(!te||Mt&&N.githubTracking?.enabled!==!0),Ce=ss||te||!!we,qe=we?"Linked":te?"Enabled":"Disabled",et=fv(bn??null,On),mt=de.trim(),Nt=i.useCallback(async()=>{if(!ss||Mt)return;const ee=!te;_t(ee),Xt(!0);try{const De=await Us(e.id,{githubTracking:{enabled:ee}},n);m?.(De)}catch(De){_t(N.githubTracking?.enabled===!0),h(`Failed to update ${e.id}: ${Se(De)}`,"error")}finally{Y.current&&Xt(!1)}},[h,ss,te,Mt,m,n,N.githubTracking?.enabled,e.id]),Pt=i.useCallback(async()=>{if(!(!ss||Mt)){if(mt.length>0&&!Sc.test(mt)){Oe("Repository override must be in owner/repo format");return}Oe(null),Xt(!0);try{const ee=await Us(e.id,{githubTracking:{repoOverride:mt.length>0?mt:null}},n);m?.(ee)}catch(ee){h(`Failed to update ${e.id}: ${Se(ee)}`,"error")}finally{Y.current&&Xt(!1)}}},[h,ss,mt,Mt,m,n,e.id]),an=i.useCallback(async()=>{if(!(!te||we||Mt)){Xt(!0);try{const ee=await Us(e.id,{githubTracking:{enabled:!0}},n);m?.(ee),h("Requested GitHub tracking issue creation","info")}catch(ee){h(`Failed to update ${e.id}: ${Se(ee)}`,"error")}finally{Y.current&&Xt(!1)}}},[h,we,te,Mt,m,n,e.id]),Cn=i.useCallback(()=>{if(!cs)return;Ee(!0),ht(e.title||""),xt(e.description||""),Ye(e.dependencies||[]),wt(e.branch??""),Fe(e.baseBranch??"");const ee=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",De=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",Ct=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";me(ee),be(De),$t(Ct),ge(e.thinkingLevel??""),on(e.nodeId),yt(ee||De||Ct?"custom":"default"),qt(""),hn(e.enabledWorkflowSteps||[]),ln(Ji(e.executionMode)),ve(e.sourceIssue?.provider??""),Ke(e.sourceIssue?.repository??""),We(e.sourceIssue?.externalIssueId??""),Lt(e.sourceIssue?.url??""),Gt([]),vt(e.reviewLevel),Dt(Ki(e.priority))},[cs,e]),ie=i.useCallback(()=>{Ee(!1),ht(e.title||""),xt(e.description||""),Ye(e.dependencies||[]),wt(e.branch??""),Fe(e.baseBranch??""),on(e.nodeId),ve(e.sourceIssue?.provider??""),Ke(e.sourceIssue?.repository??""),We(e.sourceIssue?.externalIssueId??""),Lt(e.sourceIssue?.url??""),Dt(Ki(e.priority)),ln(Ji(e.executionMode)),Bt.forEach(ee=>URL.revokeObjectURL(ee.previewUrl)),Gt([])},[e.title,e.description,e.dependencies,e.nodeId,e.priority,e.executionMode,Bt]),[$e,Qe]=i.useState("idle"),Ft=i.useRef(null),cn=i.useRef(0),pn=i.useCallback(ee=>{const De={},Ct=ft.trim(),Wt=tt.trim();Ct&&Ct!==(e.title??"")&&(De.title=Ct),ee&&Wt&&Wt!==(e.description??"")&&(De.description=Wt),af(Me,e.dependencies??[])||(De.dependencies=Me),af(Qt,e.enabledWorkflowSteps??[])||(De.enabledWorkflowSteps=Qt);const ns=dt.trim()||null,Gi=e.branch??null;ns!==Gi&&(De.branch=ns);const Em=St.trim()||null,hy=e.baseBranch??null;Em!==hy&&(De.baseBranch=Em);const _m=Md(J),py=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";J!==py&&(De.modelProvider=_m?.provider??null,De.modelId=_m?.modelId??null);const Mm=Md(Ze),fy=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";Ze!==fy&&(De.validatorModelProvider=Mm?.provider??null,De.validatorModelId=Mm?.modelId??null);const Am=Md(gt),gy=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";gt!==gy&&(De.planningModelProvider=Am?.provider??null,De.planningModelId=Am?.modelId??null);const by=e.thinkingLevel??"";Ie!==by&&(De.thinkingLevel=Ie!==""?Ie:null),(e.nodeId??void 0)!==nn&&(De.nodeId=nn??null),pt!==e.reviewLevel&&(De.reviewLevel=pt),Ut!==Ki(e.priority)&&(De.priority=Ut),sn!==Ji(e.executionMode)&&(De.executionMode=sn==="fast"?"fast":null);const $c=Ad(Zt),Dc=Ad(Pe),nl=Ad(at),Lc=WP(It);if($c.length===0&&Dc.length===0&&nl.length===0&&!Lc)e.sourceIssue&&(De.sourceIssue=null);else{if(!$c||!Dc||!nl)return{updates:null,error:"Source issue provider, repository, and issue identifier are required"};const xy=Number.parseInt(nl,10),Oc=e.sourceIssue?.issueNumber??xy;if(!Number.isFinite(Oc)||Oc<=0)return{updates:null,error:"Source issue identifier must be numeric for new metadata"};const or={provider:$c,repository:Dc,externalIssueId:nl,issueNumber:Oc,...Lc?{url:Lc}:{}},lr=e.sourceIssue;(!lr||lr.provider!==or.provider||lr.repository!==or.repository||lr.externalIssueId!==or.externalIssueId||lr.issueNumber!==or.issueNumber||(lr.url??void 0)!==or.url)&&(De.sourceIssue=or)}return{updates:De,error:null}},[St,dt,Me,tt,sn,J,nn,gt,Ut,pt,Qt,at,Zt,Pe,It,Ie,ft,Ze,e]),jn=i.useCallback(async ee=>{const{updates:De,error:Ct}=pn(ee);if(!De)return Qe("error"),Ct&&h(`Failed to update ${e.id}: ${Ct}`,"error"),!1;if(Object.keys(De).length===0)return!0;const Wt=++cn.current;Ot(!0),Qe("saving");try{const ns=await Us(e.id,De,n);return Wt!==cn.current?void 0:(m?.(ns),Qe("saved"),!0)}catch(ns){return Wt===cn.current&&(Qe("error"),h(`Failed to update ${e.id}: ${Se(ns)}`,"error")),!1}finally{Y.current&&Wt===cn.current&&Ot(!1)}},[h,pn,m,n,e.id]),Un=i.useCallback(async ee=>{await jn(!0)},[jn]),gs=i.useCallback(async()=>{await jn(!0)&&(h(`Updated ${e.id}`,"success"),Y.current&&Ee(!1))},[h,jn,e.id]);i.useEffect(()=>{if(oe)return Ft.current&&clearTimeout(Ft.current),Ft.current=setTimeout(()=>{jn(!1)},700),()=>{Ft.current&&(clearTimeout(Ft.current),Ft.current=null)}},[oe,ft,Me,dt,St,J,Ze,gt,Ie,nn,pt,Ut,sn,Qt,Zt,Pe,at,It,jn]);const bs=i.useCallback(async ee=>{const De=Ki(ee),Ct=Ki(e.priority);if(De===Ct){Kt(Ct);return}const Wt=en;Kt(De),dn(!0);try{const ns=await Us(e.id,{priority:De},n);Kt(Ki(ns.priority)),m?.(ns),h(`Priority updated to ${Ki(ns.priority)}`,"success")}catch(ns){Kt(Wt),h(`Failed to update ${e.id}: ${Se(ns)}`,"error")}finally{Y.current&&dn(!1)}},[e.id,e.priority,n,en,m,h]),is=i.useCallback(async()=>{const De=Ji(e.executionMode)==="fast"?"standard":"fast",Ct=Jt;tn(De),W(!0);try{const Wt=await Us(e.id,{executionMode:De==="fast"?"fast":null},n),ns=Ji(Wt.executionMode);tn(ns),m?.(Wt),h(`Execution mode updated to ${ns}`,"success")}catch(Wt){tn(Ct),h(`Failed to update ${e.id}: ${Se(Wt)}`,"error")}finally{Y.current&&W(!1)}},[e.id,e.executionMode,n,Jt,m,h]),ds=i.useCallback(ee=>{oe&&(ee.key==="Escape"?(ee.preventDefault(),ie()):ee.key==="Enter"&&(ee.ctrlKey||ee.metaKey)&&(ee.preventDefault(),gs()))},[oe,ie,gs]);i.useEffect(()=>{if(oe)return document.addEventListener("keydown",ds),()=>document.removeEventListener("keydown",ds)},[oe,ds]);const xs=i.useRef(null),{nodes:ra}=Cc(),{confirm:Jn}=li(),Ui=i.useCallback(async()=>{if(!(!cs||!we||Mt||!await Jn({title:"Unlink GitHub issue?",message:"This stops Fusion from syncing with the linked GitHub issue. The issue itself will not be modified.",confirmLabel:"Unlink",danger:!0}))){Xt(!0);try{const De=await Us(e.id,{githubTracking:{issue:null}},n);m?.(De),h("GitHub issue unlinked","success")}catch(De){h(`Failed to update ${e.id}: ${Se(De)}`,"error")}finally{Y.current&&Xt(!1)}}},[h,cs,Jn,we,Mt,m,n,e.id]),{entries:Hi,loading:Zs,loadMore:ja,hasMore:Na,total:Ya,loadingMore:Qa}=lv(e.id,b==="logs"&&A==="agent-log",n),Mn=i.useCallback(()=>{v?.()},[v]);i.useEffect(()=>{if(w)return;const ee=De=>{De.key==="Escape"&&!oe&&Mn()};return document.addEventListener("keydown",ee),()=>document.removeEventListener("keydown",ee)},[w,Mn,oe]);const ci=i.useCallback(async ee=>{try{const De=e.steps.some(ns=>ns.status!=="pending"),Ct=(ee==="todo"||ee==="triage")&&De;let Wt;if(Ct){if(await Jn({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Wt={preserveProgress:!0};else if(!await Jn({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,ee,Wt),Mn(),h(`Moved to ${hs[ee]}`,"success")}catch(De){h(Se(De),"error")}},[e.id,e.steps,r,Mn,h,Jn]),wi=i.useCallback(async()=>{if(await Jn({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0}))try{await o(e.id),Mn(),h(`Deleted ${e.id}`,"info")}catch(De){const Ct=Zu(De);if(!Ct||Ct.dependentIds.length===0){h(Se(De),"error");return}const Wt=Ct.dependentIds.join(", ");if(!await Jn({title:"Force Delete Task",message:`${e.id} is a dependency of ${Wt}.
|
|
685
|
+
|
|
686
|
+
Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await o(e.id,{removeDependencyReferences:!0}),Mn(),h(`Deleted ${e.id} after removing dependency references`,"info")}catch(Gi){h(Se(Gi),"error")}}},[e.id,o,Mn,h,Jn]),Ai=i.useCallback(async()=>{await Jn({title:"Merge Task",message:`Merge ${e.id} into the current branch?`})&&(Mn(),h(`Merging ${e.id}...`,"info"),l(e.id).then(De=>{const Ct=De.merged?`Merged ${e.id} (branch: ${De.branch})`:`Closed ${e.id} (${De.error||"no branch to merge"})`;h(Ct,"success")}).catch(De=>{h(Se(De),"error")}))},[e.id,l,Mn,h,Jn]),Sa=i.useCallback(()=>{c&&(Mn(),c(e.id).then(()=>{h(`Retried ${e.id}`,"success")}).catch(ee=>{h(Se(ee),"error")}))},[e.id,c,Mn,h]),Xa=i.useCallback(()=>{d&&window.confirm(`This will erase all progress for ${e.id} and start the task from scratch. Continue?`)&&(Mn(),d(e.id).then(()=>{h(`Reset ${e.id} — fresh run will be allocated`,"success")}).catch(ee=>{h(Se(ee),"error")}))},[e.id,d,Mn,h]),Za=i.useCallback(async()=>{if(!(!u||!await Jn({title:"Duplicate Task",message:`Duplicate ${e.id}? This will create a new task in Triage with the same description and prompt.`})))try{const De=await u(e.id);Mn(),h(`Duplicated ${e.id} → ${De.id}`,"success")}catch(De){h(Se(De),"error")}},[e.id,u,Mn,h,Jn]),Ca=i.useCallback(async()=>{try{e.paused?(await Wj(e.id,n),h(`Unpaused ${e.id}`,"success")):(await ub(e.id,n),h(`Paused ${e.id}`,"success")),Mn()}catch(ee){h(Se(ee),"error")}},[e.id,e.paused,Mn,h]),Ea=i.useCallback(async()=>{try{await Yj(e.id,n),h(`Plan approved — ${e.id} moved to Todo`,"success"),Mn()}catch(ee){h(Se(ee),"error")}},[e.id,Mn,h]),_a=i.useCallback(async()=>{if(await Jn({title:"Reject Plan",message:"Reject this plan? The specification will be discarded and regenerated.",danger:!0}))try{await Qj(e.id,n),h(`Plan rejected — ${e.id} returned to Planning for replanning`,"info"),Mn()}catch(De){h(Se(De),"error")}},[e.id,Mn,h,Jn]),er=i.useCallback(async()=>{if(await Jn({title:"Rebuild Plan",message:"Rebuild the plan for this task? The task will move to planning for replanning."}))try{await lN(e.id,n),Mn(),h(`Replanning ${e.id}...`,"info")}catch(De){h(Se(De),"error")}},[e.id,n,Mn,h,Jn]),Ma=i.useCallback(()=>{Re(!0),ct("")},[]),di=i.useCallback(()=>{ut(!1),zt(!1)},[]),ki=i.useCallback(ee=>{di(),ci(ee)},[di]),Ds=i.useCallback(ee=>{di(),ee()},[di]),tr=i.useCallback(()=>{di(),Ai()},[di,Ai]),qi=i.useCallback(()=>{Re(!1),ct(""),ue(!1)},[]),nr=i.useCallback(async()=>{if(!Le.trim()){h("Please enter feedback describing what needs refinement","error");return}if(Le.length>2e3){h("Feedback must be 2000 characters or less","error");return}ue(!0);try{const ee=await cN(e.id,Le.trim(),n);h(`Refinement task created: ${ee.id}`,"success"),Mn()}catch(ee){h(Se(ee),"error")}finally{ue(!1)}},[e.id,Le,h,Mn]),ei=i.useCallback(async ee=>{D(!0);try{const De=await jc(e.id,ee,n);O(Ct=>[...Ct,De]),h("Screenshot attached","success")}catch(De){h(Se(De),"error")}finally{D(!1)}},[e.id,h]),Gr=i.useCallback(async ee=>{const De=ee.target.files?.[0];De&&(await ei(De),xs.current&&(xs.current.value=""))},[ei]);i.useEffect(()=>{const ee=De=>{const Ct=De.clipboardData?.items;if(Ct)for(let Wt=0;Wt<Ct.length;Wt++){const ns=Ct[Wt];if(ns.type.startsWith("image/")){const Gi=ns.getAsFile();if(Gi){De.preventDefault(),ei(Gi);return}}}};return document.addEventListener("paste",ee),()=>document.removeEventListener("paste",ee)},[ei]);const Kr=i.useCallback(ee=>{ee.preventDefault()},[]),Jr=i.useCallback(ee=>{ee.preventDefault();const De=ee.dataTransfer.files;for(let Ct=0;Ct<De.length;Ct++){const Wt=De[Ct];if(Wt.type.startsWith("image/")){ei(Wt);return}}},[ei]),oa=i.useCallback(async ee=>{try{await eN(e.id,ee,n),O(De=>De.filter(Ct=>Ct.filename!==ee)),h("Attachment deleted","info")}catch(De){h(Se(De),"error")}},[e.id,h]),Vi=i.useCallback(async ee=>{const De=rs;Ns(ee);try{const Ct=await Us(e.id,{enabledWorkflowSteps:ee},n);h("Workflow steps updated","success"),m?.(Ct)}catch(Ct){Ns(De),h(`Failed to update workflow steps: ${Se(Ct)}`,"error")}},[e.id,n,rs,m,h]),sr=i.useCallback(async()=>{L(!0);try{const ee=await Ur(void 0,n);fe(ee),re(!0)}catch(ee){h(`Failed to load agents: ${Se(ee)}`,"error"),re(!1)}finally{L(!1)}},[n,h]),ir=i.useCallback(async ee=>{try{const De=await sh(e.id,ee,n),Ct=ne.find(Wt=>Wt.id===ee)??null;je(Ct||(Wt=>Wt?.id===ee?Wt:null)),re(!1),m?.(De),h("Assigned agent updated","success")}catch(De){h(`Failed to assign agent: ${Se(De)}`,"error")}},[e.id,n,ne,m,h]),Yr=i.useCallback(async()=>{try{const ee=await sh(e.id,null,n);je(null),re(!1),m?.(ee),h("Agent unassigned","success")}catch(ee){h(`Failed to unassign agent: ${Se(ee)}`,"error")}},[e.id,n,m,h]),ar=i.useCallback(async ee=>{const De=[...$,ee];k(De);try{await Us(e.id,{dependencies:De},n)}catch(Ct){k($),h(Se(Ct),"error")}},[e.id,$,h]),Aa=i.useCallback(async(ee,De)=>{ee.stopPropagation();const Ct=$.filter(Wt=>Wt!==De);k(Ct);try{await Us(e.id,{dependencies:Ct},n)}catch(Wt){k($),h(Se(Wt),"error")}},[e.id,$,h]),Wi=i.useCallback(async ee=>{try{const De=await Ba(ee,n);a(De)}catch{h(`Failed to load dependency ${ee}`,"error")}},[a,h]),Je=i.useCallback(async ee=>{he(!0);try{await Us(N.id,{prompt:ee},n),h("Spec updated","success"),S&&(S.prompt=ee)}catch(De){throw h(Se(De),"error"),De}finally{he(!1)}},[N,S,h]),Rt=i.useCallback(async ee=>{pe(!0);try{await oN(e.id,ee,n),h("AI revision requested. Task moved to planning.","success"),Mn()}catch(De){const Ct=Se(De);Ct.includes("done")||Ct.includes("archived")?h("Cannot request revision: Task must be in 'triage', 'todo', 'in-progress', or 'in-review' column.","error"):h(Ct,"error")}finally{pe(!1)}},[e.id,h,Mn]),rn=i.useCallback(()=>{ae(!0),Te(N.prompt||""),Be("")},[N.prompt]),es=i.useCallback(()=>{ae(!1),Te(N.prompt||""),Be("")},[N.prompt]),Hn=i.useCallback(async()=>{if(Ve===(N.prompt||"")){es();return}ae(!1);try{await Je(Ve)}catch(ee){throw ae(!0),ee}},[Ve,N.prompt,Je,es]),Bs=i.useCallback(async()=>{rt.trim()&&await Rt(rt.trim())},[rt,Rt]),rr=i.useCallback(ee=>{ee.key==="Escape"?(ee.preventDefault(),es()):ee.key==="Enter"&&(ee.ctrlKey||ee.metaKey)&&(ee.preventDefault(),Hn())},[es,Hn]),Qr=s.filter(ee=>ee.id!==e.id&&!$.includes(ee.id)).sort((ee,De)=>{const Ct=De.createdAt.localeCompare(ee.createdAt);if(Ct!==0)return Ct;const Wt=parseInt(ee.id.slice(ee.id.lastIndexOf("-")+1),10)||0;return(parseInt(De.id.slice(De.id.lastIndexOf("-")+1),10)||0)-Wt}),z=i.useMemo(()=>tm(s),[s]).get(e.id),Ae=i.useMemo(()=>{if(!z)return[];const ee=new Set(z.staleBlockedByDependentIds);return z.dependentIds.map(De=>{const Ct=s.find(Wt=>Wt.id===De);return{id:De,label:Ct?.title||Ct?.description||De,stale:ee.has(De)}})},[z,s]),Ge=ye?.name??e.assignedAgentId??null,kt=i.useMemo(()=>{const ee=[];return N.modelProvider&&ee.push(N.modelProvider),N.validatorModelProvider&&!ee.includes(N.validatorModelProvider)&&ee.push(N.validatorModelProvider),N.planningModelProvider&&!ee.includes(N.planningModelProvider)&&ee.push(N.planningModelProvider),ee},[N.modelProvider,N.validatorModelProvider,N.planningModelProvider]),An=mu[e.column]||[],Vt=["todo","in-progress"],Nn=e.column==="in-review"?Vt:An,Xe=Nn[0],lt=Nn.slice(1),Tt=lt.length>0,Ln=i.useCallback(()=>{ut(!1),Pn.current?.focus()},[]),ti=i.useCallback(ee=>{if(!Tt){Xe&&ki(Xe);return}const De=ee.currentTarget.querySelector(".detail-move-btn__arrow");if(!!(ee.target instanceof Element&&ee.target.closest(".detail-move-btn__arrow")||De&&ee.clientX>0&&ee.clientX>=De.getBoundingClientRect().left)){ut(Wt=>!Wt),zt(!1);return}Xe&&ki(Xe)},[Tt,Xe,ki]),ui=i.useCallback(ee=>{!Tt||!(ee.key==="ArrowDown"||ee.altKey&&ee.key==="ArrowDown")||(ee.preventDefault(),ut(!0),zt(!1))},[Tt]),us=i.useCallback(ee=>{ee.key==="Escape"&&(ee.preventDefault(),ee.stopPropagation(),Ln())},[Ln]);i.useEffect(()=>{if(!_e)return;_n.current?.querySelector(".detail-move-menu-item")?.focus()},[_e]);const ts={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…","merging-fix":"Merging fixes…"},un=e.status?ts[e.status]:void 0,ni=bn?.mergeStrategy??"direct",Gs=bn?.autoMerge??!1,mi=ni==="pull-request"&&!Gs;let la="Merge & Close";return mi&&!un&&(e.prInfo?e.prInfo.status==="open"?la="Check PR Status":e.prInfo.status==="merged"&&(la="Finish & Close"):la="Start PR Review"),t.jsxs("div",{className:w?"task-detail-content task-detail-content--embedded":"task-detail-content",onDragOver:Kr,onDrop:Jr,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:hs[e.column]})]}),t.jsxs("div",{className:"modal-header-actions",children:[!oe&&cs&&t.jsx("button",{className:"modal-edit-btn",onClick:Cn,title:"Edit task","aria-label":"Edit task",children:t.jsx(Hs,{size:14})}),!w&&g==="back"&&t.jsxs("button",{className:"modal-close task-detail-mobile-back",onClick:Mn,"aria-label":"Back to task list",type:"button",children:[t.jsx(Ga,{"aria-hidden":"true"}),t.jsx("span",{children:"Back"})]}),!w&&g!=="back"&&t.jsx("button",{className:"modal-close",onClick:Mn,"aria-label":"Close",type:"button",children:"×"})]})]}),t.jsxs("div",{className:`detail-body${b==="logs"&&A==="agent-log"&&!oe?" detail-body--agent-log":""}`,children:[oe?t.jsx("div",{className:"modal-edit-form",children:t.jsx(gv,{mode:"edit",title:ft,onTitleChange:ht,description:tt,onDescriptionChange:xt,dependencies:Me,onDependenciesChange:Ye,branch:dt,onBranchChange:wt,baseBranch:St,onBaseBranchChange:Fe,executorModel:J,onExecutorModelChange:me,validatorModel:Ze,onValidatorModelChange:be,planningModel:gt,onPlanningModelChange:$t,thinkingLevel:Ie,onThinkingLevelChange:ge,presetMode:st,onPresetModeChange:yt,selectedPresetId:xn,onSelectedPresetIdChange:qt,selectedWorkflowSteps:Qt,onWorkflowStepsChange:hn,pendingImages:Bt,onImagesChange:Gt,tasks:s.filter(ee=>ee.id!==e.id),projectId:n,disabled:bt,addToast:h,isActive:oe,onAutoSaveDescription:Un,reviewLevel:pt,onReviewLevelChange:vt,priority:Ut,onPriorityChange:Dt,nodeId:nn,onNodeIdChange:on,nodeOptions:ra,nodeOverrideDisabled:ys,nodeOverrideDisabledReason:ys?"Execution node override is locked while a task is active/in progress.":void 0,executionMode:sn,onExecutionModeChange:ln,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:Zt,onChange:ee=>ve(ee.target.value),disabled:bt,"data-testid":"task-source-provider-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Repository (e.g. owner/repo)",value:Pe,onChange:ee=>Ke(ee.target.value),disabled:bt,"data-testid":"task-source-repository-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:at,onChange:ee=>We(ee.target.value),disabled:bt,"data-testid":"task-source-external-id-input"}),t.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:It,onChange:ee=>Lt(ee.target.value),disabled:bt,"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 ee=e.title||e.description||e.id,De=!H&&ee.length>Rd;return t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"detail-title",children:De?ee.slice(0,Rd)+"…":ee}),ee.length>Rd&&t.jsx("button",{className:"detail-description-toggle",onClick:()=>Q(!H),children:H?"Show less":"Show more"})]})})(),t.jsxs("div",{className:"detail-meta",children:[t.jsxs("div",{className:"detail-meta-inline-controls","data-testid":"detail-meta-inline-controls",children:[t.jsxs("label",{className:`card-priority-badge card-priority-badge--${en} detail-priority-chip ${Sn?"detail-priority-chip--saving":""}`,children:[t.jsx("span",{children:"Priority:"}),t.jsx("select",{className:"detail-priority-select",value:en,onChange:ee=>{bs(ee.target.value)},disabled:Sn,"aria-label":"Task priority",children:wa.map(ee=>t.jsx("option",{value:ee,children:ee},ee))})]}),t.jsxs("button",{type:"button",className:`btn btn-sm detail-execution-mode-toggle ${Jt==="fast"?"detail-execution-mode-toggle--fast":""} ${Ne?"detail-execution-mode-toggle--saving":""}`,onClick:()=>{is()},disabled:Ne,"aria-label":`Execution mode: ${Jt}`,"aria-pressed":Jt==="fast",children:[t.jsx(ls,{"aria-hidden":"true"}),t.jsx("span",{children:Jt==="fast"?"Fast":"Standard"})]})]}),U&&t.jsxs("div",{className:"detail-provenance",children:[t.jsx(Os,{"aria-hidden":"true"}),t.jsxs("span",{children:[N.sourceType==="agent_heartbeat"?t.jsxs(t.Fragment,{children:["Created by"," ",U.sourceAgentId?t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>K(U.sourceAgentId),children:U.label}):U.label]}):t.jsxs(t.Fragment,{children:["Created via ",U.label]}),U.parentTaskId&&t.jsxs(t.Fragment,{children:[" ","of"," ",t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>Wi(U.parentTaskId),children:U.parentTaskId})]}),U.contextInfo?` (${U.contextInfo})`:""]})]}),(e.prInfo?.number||e.mergeDetails?.prNumber)&&t.jsxs("div",{className:"detail-provenance detail-pr-link-row",children:[t.jsx(Os,{"aria-hidden":"true"}),t.jsxs("span",{children:["PR"," ",e.prInfo?.url?t.jsxs("a",{className:"detail-provenance-link",href:e.prInfo.url,target:"_blank",rel:"noopener noreferrer",children:["#",e.prInfo.number]}):t.jsxs("span",{children:["#",e.prInfo?.number??e.mergeDetails?.prNumber]})]})]}),t.jsxs("div",{className:"detail-timestamps","aria-label":"Task timestamps",children:[t.jsxs("span",{className:"detail-timestamp-item",children:[t.jsx("span",{className:"detail-timestamp-label",children:"Created"})," ",t.jsx("time",{dateTime:e.createdAt,title:new Date(e.createdAt).toLocaleString(),children:Ed(e.createdAt)})]}),t.jsx("span",{className:"detail-timestamp-separator","aria-hidden":"true",children:"·"}),t.jsxs("span",{className:"detail-timestamp-item",children:[t.jsx("span",{className:"detail-timestamp-label",children:"Updated"})," ",t.jsx("time",{dateTime:e.updatedAt,title:new Date(e.updatedAt).toLocaleString(),children:Ed(e.updatedAt)})]})]})]})]}),e.status==="failed"&&e.error&&t.jsxs("div",{className:"detail-error-alert",children:[t.jsx("span",{className:"detail-error-icon",children:"⚠"}),t.jsxs("div",{className:"detail-error-content",children:[t.jsx("div",{className:"detail-error-title",children:"Task Failed"}),t.jsx("div",{className:"detail-error-message",children:e.error})]})]}),!oe&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"detail-tabs",children:[t.jsx("button",{className:`detail-tab${b==="definition"?" detail-tab-active":""}`,onClick:()=>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"}),vs.map(({entry:ee,tabId:De})=>t.jsx("button",{className:`detail-tab${b===De?" detail-tab-active":""}`,onClick:()=>y(De),children:ee.slot.label},`plugin-tab-${ee.pluginId}-${De}`))]}),b==="workflow"?t.jsx("div",{className:"detail-section",children:t.jsx(EP,{taskId:e.id,results:as,loading:Rs,enabledWorkflowSteps:rs,canEdit:cs,projectId:n,isTaskInProgress:e.column==="in-progress"&&e.status!=="paused",onWorkflowStepsChange:Vi})}):b==="model"?t.jsx("div",{className:"detail-section",children:t.jsx(tP,{task:e,addToast:h,onTaskUpdated:m,settings:bn})}):b==="logs"?t.jsxs("div",{className:`detail-section${A==="agent-log"?" detail-section--agent-log":""}`,children:[t.jsxs("div",{className:"log-subview-toggle",children:[t.jsx("button",{className:`log-subview-btn${A==="activity"?" log-subview-btn-active":""}`,onClick:()=>T("activity"),children:"Activity"}),t.jsx("button",{className:`log-subview-btn${A==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>T("agent-log"),children:"Agent Log"})]}),A==="agent-log"?t.jsx(YT,{entries:Hi,loading:Zs,executorModel:zP(e,Hi,ye,bn),validatorModel:BP(e,Hi,ye,bn),planningModel:HP(e,Hi,bn),hasMore:Na,onLoadMore:ja,loadingMore:Qa,totalCount:Ya}):t.jsxs("div",{className:"detail-activity",children:[t.jsx("h4",{children:"Activity"}),N.activityLogTruncatedCount?t.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",N.log.length," activity entries."]}):null,N.log&&N.log.length>0?t.jsx("div",{className:"detail-activity-list",children:[...N.log].reverse().map((ee,De)=>t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-timestamp",children:Ed(ee.timestamp)}),t.jsx("span",{className:"detail-log-action",children:ee.action})]}),ee.outcome&&t.jsx("div",{className:"detail-log-outcome",children:ee.outcome})]},De))}):t.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):b==="changes"?t.jsx(xP,{taskId:e.id,worktree:e.worktree,projectId:n,column:e.column,mergeDetails:e.mergeDetails,modifiedFiles:e.modifiedFiles}):b==="review"?t.jsx(hP,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):b==="comments"?t.jsx(rP,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):b==="documents"?t.jsx($P,{taskId:e.id,addToast:h,projectId:n,onTaskUpdated:m,canEdit:cs}):As?t.jsx("div",{className:"detail-section",children:t.jsx(pa,{slotId:"task-detail-tab",projectId:n,pluginIds:[As.entry.pluginId]})}):b==="stats"?t.jsx("div",{className:"detail-section",children:t.jsx(LP,{tokenUsage:N.tokenUsage,loading:C,task:N})}):b==="routing"?t.jsx("div",{className:"detail-section",children:t.jsx(RP,{task:e,settings:bn,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(xi,{remarkPlugins:[vi],components:sf,children:e.summary})})]}),t.jsx(fP,{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(Os,{"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":yn,"aria-label":yn?"Collapse source issue details":"Expand source issue details",onClick:()=>Zn(ee=>!ee),children:t.jsx(qn,{size:16,className:yn?"detail-source-chevron--expanded":void 0})})]}),yn&&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)"})})]})]})]}),Ce&&t.jsxs("div",{className:"detail-section detail-github-tracking-section",children:[t.jsxs("div",{className:"detail-source-header",children:[t.jsxs("div",{className:"detail-source-summary",children:[t.jsx("span",{className:"detail-source-label",children:"GitHub tracking"}),t.jsxs("span",{className:"detail-source-provider-badge","aria-label":"GitHub tracking status",children:[t.jsx(Os,{"aria-hidden":"true"}),t.jsx("span",{children:qe})]}),!we&&t.jsx("span",{className:"detail-source-empty",children:te?"Issue not yet created":"Tracking is currently disabled"})]}),P&&t.jsx("button",{type:"button",className:"btn btn-sm btn-primary detail-github-tracking-enable","aria-label":"Enable GitHub tracking",onClick:()=>void Nt(),disabled:Mt,children:Mt?"Saving…":"Enable"}),t.jsx("button",{type:"button",className:"detail-source-toggle","aria-expanded":vn,"aria-label":vn?"Collapse GitHub tracking details":"Expand GitHub tracking details",onClick:()=>Dn(ee=>!ee),children:t.jsx(qn,{size:16,className:vn?"detail-source-chevron--expanded":void 0})})]}),vn&&t.jsxs("div",{className:"detail-github-tracking-content",children:[we&&t.jsxs("dl",{className:"detail-source-grid detail-github-tracking-grid",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Issue"}),t.jsx("dd",{children:we.url?t.jsx("a",{className:"detail-source-link",href:we.url,target:"_blank",rel:"noopener noreferrer",children:`${we.owner}/${we.repo}#${we.number}`}):t.jsx("span",{children:`${we.owner}/${we.repo}#${we.number}`})})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"State"}),t.jsx("dd",{children:t.jsx("span",{className:`detail-github-issue-state ${e.issueInfo?.state==="closed"?"detail-github-issue-state--closed":"detail-github-issue-state--open"}`,children:e.issueInfo?.state??"open"})})]})]}),t.jsxs("div",{className:"detail-github-tracking-controls",children:[!we&&te&&t.jsx("button",{className:"btn btn-sm touch-target",onClick:()=>void an(),disabled:Mt,children:"Create tracking issue"}),ss&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"checkbox-label",htmlFor:"detail-github-tracking-toggle",children:[t.jsx("input",{id:"detail-github-tracking-toggle",type:"checkbox",checked:te,disabled:Mt,onChange:()=>void Nt()}),"Enable GitHub tracking"]}),t.jsxs("div",{className:"detail-github-tracking-repo-row",children:[t.jsx("input",{className:"input",value:de,onChange:ee=>{nt(ee.target.value),Oe(null)},placeholder:et||"owner/repo"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void Pt(),disabled:Mt,children:"Save"})]}),G&&t.jsx("small",{className:"detail-github-tracking-error",children:G}),we&&t.jsx("button",{className:"btn btn-sm touch-target",onClick:()=>void Ui(),disabled:Mt,children:"Unlink GitHub issue"})]})]})]})]}),t.jsx("div",{className:"detail-section detail-agent-section",children:t.jsxs("div",{className:"detail-meta-row",children:[t.jsxs("div",{className:"detail-meta-left",children:[kt.length>0&&t.jsx("span",{className:"detail-provider-icons","data-testid":"detail-provider-icons",children:kt.map(ee=>t.jsx(zn,{provider:ee,size:"sm"},ee))}),t.jsxs("span",{className:"detail-meta-label",children:[t.jsx(Qn,{size:14,className:"detail-meta-label-icon"}),"Agent"]})]}),t.jsxs("div",{className:"detail-agent-actions",children:[Ge?t.jsxs("span",{className:"detail-agent-chip",children:[t.jsx(Qn,{size:14}),Ge,t.jsx("button",{className:"detail-agent-clear",onClick:()=>void Yr(),title:"Unassign agent",children:t.jsx(mn,{size:12})})]}):t.jsx("button",{className:"btn btn-sm",onClick:()=>{Z?re(!1):sr()},children:"Assign Agent"}),Z&&t.jsxs("div",{className:"agent-picker-dropdown",children:[q&&t.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!q&&ne.map(ee=>t.jsxs("button",{className:`agent-picker-item${e.assignedAgentId===ee.id?" selected":""}`,onClick:()=>void ir(ee.id),children:[t.jsx(Qn,{size:14}),t.jsx("span",{className:"agent-picker-name",children:ee.name}),t.jsx("span",{className:"agent-picker-role",children:ee.role})]},ee.id)),!q&&ne.length===0&&t.jsx("div",{className:"agent-picker-empty",children:"No agents available"})]})]})]})}),t.jsxs("div",{className:"detail-section detail-step-progress",children:[t.jsx("h4",{children:"Progress"}),N.steps&&N.steps.length>0?t.jsxs("div",{className:"step-progress-wrapper",children:[t.jsx("div",{className:"step-progress-bar",children:N.steps.map((ee,De)=>t.jsx("div",{className:`step-progress-segment step-progress-segment--${ee.status}`,"data-tooltip":`${ee.name} (${ee.status})`,style:{backgroundColor:qP(ee.status)}},De))}),t.jsxs("span",{className:"step-progress-label",children:[N.steps.filter(ee=>ee.status==="done").length,"/",N.steps.length," step",N.steps.length===1?"":"s"]})]}):t.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),t.jsxs("div",{className:"detail-section",children:[!ze&&t.jsx("div",{className:"detail-spec-edit-trigger",children:t.jsx("button",{className:"btn btn-sm",onClick:rn,children:"Edit"})}),ze?t.jsxs("div",{className:"spec-editor-edit-mode",children:[t.jsx("textarea",{className:"spec-editor-textarea",value:Ve,onChange:ee=>Te(ee.target.value),onKeyDown:rr,disabled:xe,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:es,disabled:xe,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Hn(),disabled:Ve===(N.prompt||"")||xe,children:xe?"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:rt,onChange:ee=>Be(ee.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:B,rows:4,maxLength:2e3}),t.jsxs("div",{className:"spec-editor-revision-actions",children:[t.jsxs("span",{className:"spec-editor-char-count",children:[rt.length,"/2000"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Bs(),disabled:!rt.trim()||B,children:B?"Requesting…":"Request AI Revision"})]})]})]}):C?t.jsx("div",{className:"spec-loading",children:"Loading specification…"}):N.prompt?t.jsx("div",{className:"markdown-body",children:t.jsx(xi,{remarkPlugins:[vi],components:sf,children:N.prompt.replace(/^#\s+[^\n]*\n+/,"")})}):t.jsx("div",{className:"detail-prompt",children:"(no prompt)"})]}),t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Attachments"}),se.length>0?t.jsx("div",{className:"detail-attachments-grid",children:se.map(ee=>{const De=Fi(`/api/tasks/${e.id}/attachments/${ee.filename}`);return t.jsxs("div",{className:"detail-attachment-card",children:[t.jsx("a",{className:"detail-attachment-link",href:De,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{src:De,alt:ee.originalName,className:"detail-attachment-image"})}),t.jsxs("div",{className:"detail-attachment-meta",children:[ee.originalName," (",VP(ee.size),")"]}),t.jsx("button",{className:"detail-attachment-delete",onClick:()=>oa(ee.filename),title:"Delete attachment",children:"×"})]},ee.filename)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no attachments)"}),t.jsx("input",{className:"detail-hidden-file-input",ref:xs,type:"file",accept:"image/*",onChange:Gr}),t.jsx("button",{className:"btn btn-sm",onClick:()=>xs.current?.click(),disabled:M,children:M?"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(ee=>{const De=s.find(Wt=>Wt.id===ee),Ct=De?.title||De?.description||ee;return t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>Wi(ee),onKeyDown:Wt=>{(Wt.key==="Enter"||Wt.key===" ")&&(Wt.preventDefault(),Wi(ee))},role:"link",tabIndex:0,title:`Click to view ${ee}`,children:[t.jsx("span",{className:"detail-dep-id",children:ee}),t.jsx("span",{className:"detail-dep-label",children:_d(Ct,40)})]}),t.jsx("button",{className:"dep-remove-btn",onClick:Wt=>Aa(Wt,ee),title:`Remove dependency ${ee}`,children:"×"})]},ee)})}):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:()=>{X&&He(""),le(ee=>!ee)},children:"Add Dependency"}),X&&(()=>{const ee=ke.toLowerCase(),De=ee?Qr.filter(Ct=>Ct.id.toLowerCase().includes(ee)||Ct.title&&Ct.title.toLowerCase().includes(ee)||Ct.description&&Ct.description.toLowerCase().includes(ee)):Qr;return t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:ke,onChange:Ct=>He(Ct.target.value),onClick:Ct=>Ct.stopPropagation()}),De.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):De.map(Ct=>t.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{ar(Ct.id),le(!1)},children:[t.jsx("span",{className:"dep-dropdown-id",children:Ct.id}),t.jsx("span",{className:"dep-dropdown-title",children:_d(Ct.title||Ct.description||Ct.id,30)})]},Ct.id))]})})()]})]}),t.jsxs("div",{className:"detail-deps detail-blocking",children:[t.jsx("h4",{children:"Blocking"}),Ae.length>0?t.jsx("ul",{className:"detail-dep-list",children:Ae.map(ee=>t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>Wi(ee.id),onKeyDown:De=>{(De.key==="Enter"||De.key===" ")&&(De.preventDefault(),Wi(ee.id))},role:"link",tabIndex:0,title:`Click to view ${ee.id}`,children:[t.jsx("span",{className:"detail-dep-id",children:ee.id}),t.jsx("span",{className:"detail-dep-label",children:_d(ee.label,40)})]}),ee.stale&&t.jsx("span",{className:"detail-blocking-item--stale",title:"Stale blockedBy edge: self-healing clearStaleBlockedBy should clear this automatically",children:"(stale)"})]},ee.id))}):t.jsx("div",{className:"detail-empty-inline",children:"(no downstream tasks blocked)"})]}),e.column==="in-review"&&t.jsx("div",{className:"detail-section detail-pr-section",children:t.jsx(sP,{taskId:e.id,projectId:n,prInfo:e.prInfo,automationStatus:e.status??null,autoMerge:bn?.autoMerge??!1,isManualPrFlow:mi,prAuthAvailable:f??!1,onPrCreated:ee=>{e.prInfo=ee},onPrUpdated:ee=>{e.prInfo=ee},addToast:h})})]})]})]}),t.jsx("div",{className:"modal-actions",children:oe?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"modal-edit-hint",children:$e==="saving"?"Autosaving…":$e==="saved"?"Saved":$e==="error"?"Save failed":"Changes autosave as you edit"}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("button",{className:"btn btn-sm",onClick:ie,disabled:bt,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void gs(),disabled:bt,children:bt?"Saving…":"Save"})]}):t.jsxs(t.Fragment,{children:[e.column==="triage"&&e.status==="awaiting-approval"&&N.prompt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Ea,children:"Approve Plan"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:_a,children:"Reject Plan"})]}),e.column==="triage"&&e.status!=="awaiting-approval"&&!R&&t.jsx("button",{className:"btn btn-sm btn-danger",onClick:wi,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(e.column!=="triage"||e.status==="awaiting-approval"||R||e.paused)&&t.jsxs("div",{className:"detail-actions-dropdown",ref:kn,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{zt(ee=>!ee),ut(!1)},"aria-haspopup":"menu","aria-expanded":At,children:["Actions",t.jsx(gn,{size:12})]}),At&&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(wi),children:"Delete"}),u&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Ds(Za),children:"Duplicate"}),(e.column==="done"||e.column==="in-review")&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Ds(Ma),children:"Refine"}),t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Ds(er),children:"Respecify"}),R&&c&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Ds(Sa),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(Xa),children:"Reset"}),e.column!=="done"&&!e.assignedAgentId&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Ds(Ca),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:_n,children:e.column==="in-review"?t.jsxs("div",{className:"detail-move-actions-in-review",children:[t.jsxs("div",{children:[t.jsxs("button",{ref:Pn,className:"btn btn-primary btn-sm detail-move-btn",onClick:ti,onKeyDown:ui,disabled:!Xe,"aria-label":Xe?`Move to ${hs[Xe]}`:void 0,"aria-haspopup":Tt?"menu":void 0,"aria-expanded":Tt?_e:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",Xe?hs[Xe]:""]}),Tt&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(gn,{size:12})})]}),_e&&Tt&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:us,children:lt.map(ee=>t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>ki(ee),onKeyDown:us,children:ee==="in-progress"?"Back to In Progress":`Move to ${hs[ee]}`},ee))})]}),un?t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:un}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:tr,children:la})]}):t.jsxs("div",{children:[t.jsxs("button",{ref:Pn,className:"btn btn-primary btn-sm detail-move-btn",onClick:ti,onKeyDown:ui,disabled:!Xe,"aria-label":Xe?`Move to ${hs[Xe]}`:void 0,"aria-haspopup":Tt?"menu":void 0,"aria-expanded":Tt?_e:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",Xe?hs[Xe]:""]}),Tt&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(gn,{size:12})})]}),_e&&Tt&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:us,children:lt.map(ee=>t.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>ki(ee),onKeyDown:us,children:["Move to ",hs[ee]]},ee))})]})})]})}),ce&&t.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:qi,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal detail-refine-modal",onClick:ee=>ee.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:qi,"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:Le,onChange:ee=>ct(ee.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:[Le.length,"/2000 characters"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:nr,disabled:!Le.trim()||Ue,children:Ue?"Creating...":"Create Refinement Task"})]})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:qi,disabled:Ue,children:"Cancel"})})]})}),_&&t.jsx(i.Suspense,{fallback:null,children:t.jsx(JP,{agentId:_,projectId:n,onClose:()=>K(null),addToast:h})})]})}function ZP({onClose:e,...n}){const s=i.useRef(null);zi(s,!0,"task-detail-modal-size"),Mi(!0);const a=sa(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(xv,{...n,onRequestClose:e})})})}const yl={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},rf=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function of(e){return e==="merging-fix"?"Merging fixes…":e}const vv=["title","status","column","dependencies","progress"],e$=["title","status","column"];function t$(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function n$(e){return e==="online"?"●":e==="connecting"?"◐":e==="error"?"✕":"○"}function lf(e){try{const n=Gn("kb-dashboard-list-columns",e);if(n){const a=JSON.parse(n).filter(r=>vv.includes(r));if(a.length>0)return new Set(a)}}catch{}return new Set(e$)}function cf(e){try{const n=Gn("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function df(e){try{const n=Gn("kb-dashboard-list-collapsed",e);if(n){const a=JSON.parse(n).filter(r=>ha.includes(r));if(a.length>0)return new Set(a)}}catch{}return new Set}function uf(e){try{const n=Gn("kb-dashboard-selected-tasks",e);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function mf(e){try{const n=Gn("kb-dashboard-list-selected-task",e);if(typeof n=="string"&&n.trim().length>0)return n}catch{}return null}function hf(e){try{const s=Gn("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 ac=280,_u=.65,wl=16;function Mu(e){return Math.max(ac,e*_u)}function kl(e,n){const s=Mu(n);return Math.min(Math.max(e,ac),s)}function s$(e){return e.status==="executing"||e.column==="in-progress"}function pf(e){const n=Hb(e);return n.total===0||!s$(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:w,onToggleModelFavorite:v,onPlanningMode:b,onSubtaskBreakdown:y,onTasksUpdated:S,projectId:j,projectName:C,taskStuckTimeoutMs:x,searchQuery:N="",lastFetchTimeMs:R,prAuthAvailable:F}){const[E,_]=i.useState(null),[K,U]=i.useState("asc"),[A,T]=i.useState(null),[H,Q]=i.useState(null),[se,O]=i.useState(null),D=oi()==="mobile",{confirm:$}=li(),[k,X]=i.useState(()=>lf(j)),[le,ke]=i.useState(()=>cf(j)),[He,ye]=i.useState(()=>df(j));i.useEffect(()=>{typeof window<"u"&&fs("kb-dashboard-list-columns",JSON.stringify([...k]),j)},[j,k]),i.useEffect(()=>{typeof window<"u"&&fs("kb-dashboard-hide-done",le.toString(),j)},[le,j]),i.useEffect(()=>{typeof window<"u"&&fs("kb-dashboard-list-collapsed",JSON.stringify([...He]),j)},[He,j]);const[je,ne]=i.useState(!1),[fe,Z]=i.useState(!1),[re,q]=i.useState(()=>uf(j)),[L,xe]=i.useState(()=>mf(j)),[he,B]=i.useState(null),[pe,ze]=i.useState(()=>hf(j)),ae=i.useRef(null),Ve=i.useRef(null);i.useEffect(()=>{X(lf(j)),ke(cf(j)),ye(df(j)),q(uf(j));const ve=mf(j);xe(ve),B(ve?e.find(Pe=>Pe.id===ve)??null:null),ze(hf(j))},[j,e]),i.useEffect(()=>{typeof window<"u"&&fs("kb-dashboard-selected-tasks",JSON.stringify([...re]),j)},[j,re]),i.useEffect(()=>{if(!(typeof window>"u")){if(L){fs("kb-dashboard-list-selected-task",L,j);return}Ar("kb-dashboard-list-selected-task",j)}},[j,L]),i.useEffect(()=>{if(!L){B(null);return}const ve=e.find(Pe=>Pe.id===L);ve&&B(Pe=>!Pe||Pe.id!==L?ve:{...Pe,...ve})},[L,e]),i.useEffect(()=>{if(D||typeof ResizeObserver>"u")return;const ve=ae.current;if(!ve)return;const Pe=()=>{const at=kl(pe,ve.clientWidth);at!==pe&&ze(at)};Pe();const Ke=new ResizeObserver(Pe);return Ke.observe(ve),()=>Ke.disconnect()},[D,pe]),i.useEffect(()=>{if(D||typeof ResizeObserver>"u")return;const ve=Ve.current,Pe=ae.current;if(!ve||!Pe)return;let Ke=null,at=ve.offsetWidth;const We=new ResizeObserver(()=>{const It=kl(ve.offsetWidth,Pe.clientWidth);It!==at&&(at=It,Ke&&clearTimeout(Ke),Ke=setTimeout(()=>{try{fs("kb-dashboard-list-sidebar-width",String(It),j)}catch{}},200))});return We.observe(ve),()=>{We.disconnect(),Ke&&clearTimeout(Ke)}},[D,j]);const Te=i.useCallback(()=>{Z(ve=>(ve&&q(new Set),!ve))},[]),rt=i.useCallback(ve=>{q(Pe=>{const Ke=new Set(Pe);return Ke.has(ve)?Ke.delete(ve):Ke.add(ve),Ke})},[]),Be=i.useCallback(()=>{q(new Set)},[]),ce=i.useCallback(ve=>{X(Pe=>{const Ke=new Set(Pe);return Ke.has(ve)?Ke.size>1&&Ke.delete(ve):Ke.add(ve),Ke})},[]),Re={title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},Le=i.useCallback(ve=>{if(E===ve){U(Pe=>Pe==="asc"?"desc":"asc");return}_(ve),U("asc")},[E]),ct=i.useCallback(ve=>{O(Pe=>Pe===ve?null:ve)},[]),Ue=i.useCallback(ve=>{ye(Pe=>{const Ke=new Set(Pe);return Ke.has(ve)?Ke.delete(ve):Ke.add(ve),Ke})},[]),ue=i.useCallback(()=>{O(null)},[]),oe=i.useMemo(()=>{let ve=N?e.filter(at=>at.id.toLowerCase().includes(N.toLowerCase())||at.title&&at.title.toLowerCase().includes(N.toLowerCase())||at.description.toLowerCase().includes(N.toLowerCase())):[...e];le&&!se&&(ve=ve.filter(at=>at.column!=="done"&&at.column!=="archived"));const Pe=se?ve.filter(at=>at.column===se):ve,Ke={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};Pe.forEach(at=>{const We=Qu(at.column)?at.column:Xl;Ke[We].push(at)});for(const at of ha){if(!E){Ke[at]=Ob(Ke[at],at);continue}Ke[at]=[...Ke[at]].sort((We,It)=>{let Lt=0;switch(E){case"title":Lt=(We.title||We.description).localeCompare(It.title||It.description);break;case"status":Lt=(We.status||"").localeCompare(It.status||"");break;case"column":Lt=We.column.localeCompare(It.column);break}return K==="asc"?Lt:-Lt})}return Ke},[e,N,E,K,le,se]),Ee=i.useMemo(()=>Object.values(oe).reduce((ve,Pe)=>ve+Pe.length,0),[oe]),ft=i.useMemo(()=>e.filter(ve=>ve.column==="done"||ve.column==="archived").length,[e]),ht=i.useMemo(()=>le?ft:0,[le,ft]),tt=i.useCallback(()=>{const ve=Object.values(oe).flat().filter(Pe=>Pe.column!=="archived").map(Pe=>Pe.id);q(Pe=>{if(ve.every(at=>Pe.has(at))){const at=new Set(Pe);return ve.forEach(We=>at.delete(We)),at}else return new Set([...Pe,...ve])})},[oe]),xt=i.useMemo(()=>{const ve=Object.values(oe).flat().filter(Pe=>Pe.column!=="archived");return ve.length===0?!1:ve.every(Pe=>re.has(Pe.id))},[oe,re]),Me=i.useMemo(()=>{const ve=Object.values(oe).flat().filter(Ke=>Ke.column!=="archived");if(ve.length===0)return!1;const Pe=ve.filter(Ke=>re.has(Ke.id)).length;return Pe>0&&Pe<ve.length},[oe,re]),[Ye,dt]=i.useState("__no_change__"),[wt,St]=i.useState("__no_change__"),[Fe,J]=i.useState("__no_change__"),[me,Ze]=i.useState([]),[be,gt]=i.useState(!1),$t=i.useMemo(()=>Fe&&Fe!=="__no_change__"?me.find(ve=>ve.id===Fe):void 0,[me,Fe]),[Ie,ge]=i.useState(!1);i.useEffect(()=>{if(re.size===0)return;let ve=!1;return(async()=>{gt(!0);try{const Ke=await Yl();ve||Ze(Ke)}catch(Ke){console.error("Failed to fetch nodes for bulk edit",Ke),ve||Ze([])}finally{ve||gt(!1)}})(),()=>{ve=!0}},[re.size]);const st=i.useCallback(async()=>{if(re.size===0)return;const ve=Array.from(re).map(Bt=>e.find(Gt=>Gt.id===Bt)).filter(Bt=>!!Bt),Pe=ve.filter(Bt=>Bt.column==="archived"),Ke=ve.filter(Bt=>Bt.column!=="archived");if(Ke.length===0){d("No selected tasks can be deleted (archived tasks are excluded)","error");return}if(!await $({title:"Delete Selected Tasks",message:`Delete ${Ke.length} selected task${Ke.length===1?"":"s"}?`,confirmLabel:"Delete",cancelLabel:"Cancel",danger:!0}))return;ge(!0);const We=[],It=[],Lt=Pe.map(Bt=>Bt.id);try{for(const Bt of Ke)try{await a(Bt.id),We.push(Bt.id)}catch(Gt){const bt=Zu(Gt);if(!bt){It.push(Bt.id);continue}if(!await $({title:"Force Delete Task",message:`Task ${Bt.id} has dependents: ${bt.dependentIds.join(", ")}. Remove dependency references and force delete?`,confirmLabel:"Force Delete",cancelLabel:"Skip",danger:!0})){It.push(Bt.id);continue}try{await a(Bt.id,{removeDependencyReferences:!0}),We.push(Bt.id)}catch{It.push(Bt.id)}}}finally{ge(!1)}We.length>0&&q(Bt=>{const Gt=new Set(Bt);for(const bt of We)Gt.delete(bt);return Gt}),d(`Deleted ${We.length} task${We.length===1?"":"s"} · ${Lt.length} archived skipped · ${It.length} failed`,It.length>0?"error":"success")},[d,$,a,re,e]),yt=i.useCallback(async()=>{if(re.size===0)return;const ve=Array.from(re).filter(Ke=>{const at=e.find(We=>We.id===Ke);return at&&at.column!=="archived"});if(ve.length===0){d("No valid tasks to update (archived tasks cannot be modified)","error");return}const Pe={taskIds:ve};if(Ye!=="__no_change__")if(Ye==="")Pe.modelProvider=null,Pe.modelId=null;else{const Ke=Ye.indexOf("/");Ke!==-1&&(Pe.modelProvider=Ye.slice(0,Ke),Pe.modelId=Ye.slice(Ke+1))}if(wt!=="__no_change__")if(wt==="")Pe.validatorModelProvider=null,Pe.validatorModelId=null;else{const Ke=wt.indexOf("/");Ke!==-1&&(Pe.validatorModelProvider=wt.slice(0,Ke),Pe.validatorModelId=wt.slice(Ke+1))}if(Fe!=="__no_change__"&&(Fe===""?Pe.nodeId=null:Pe.nodeId=Fe),Object.keys(Pe).length===1){d("No changes to apply","info");return}ge(!0);try{const Ke=await Fj(Pe.taskIds,Pe.modelProvider,Pe.modelId,Pe.validatorModelProvider,Pe.validatorModelId,void 0,void 0,Pe.nodeId,j);S&&S(Ke.updated),d(`Updated ${ve.length} task${ve.length===1?"":"s"}`,"success"),Be(),dt("__no_change__"),St("__no_change__"),J("__no_change__")}catch(Ke){d(Se(Ke)||"Failed to update models","error")}finally{ge(!1)}},[re,e,Ye,wt,Fe,j,d,Be,S]),pt=i.useCallback(ve=>{if(D){c(ve,{origin:"list-mobile"});return}xe(ve.id),B(ve)},[D,c]),vt=i.useRef(null),Ut=i.useRef(null);i.useEffect(()=>()=>{vt.current&&clearTimeout(vt.current)},[]);const Dt=i.useCallback(ve=>{if(xe(ve.id),B(ve),"prompt"in ve){Ut.current=null,vt.current&&(clearTimeout(vt.current),vt.current=null);return}Ut.current=ve.id,vt.current&&clearTimeout(vt.current),vt.current=setTimeout(()=>{vt.current=null,Ut.current===ve.id&&Ba(ve.id,j).then(Ke=>{Ut.current===Ke.id&&B(at=>!at||at.id!==Ke.id?at:{...at,...Ke})}).catch(()=>{})},200)},[j]),nn=i.useCallback((ve,Pe)=>{if(Pe.paused){ve.preventDefault();return}ve.dataTransfer.setData("text/plain",Pe.id),ve.dataTransfer.effectAllowed="move",T(Pe.id)},[]),on=i.useCallback(()=>{T(null),Q(null)},[]),sn=i.useCallback(ve=>{if(D)return;ve.preventDefault();const Pe=ae.current;if(!Pe)return;const Ke=Pe.getBoundingClientRect(),at=It=>{const Lt=It.clientX-Ke.left;ze(kl(Lt,Ke.width))},We=()=>{window.removeEventListener("mousemove",at),window.removeEventListener("mouseup",We)};window.addEventListener("mousemove",at),window.addEventListener("mouseup",We)},[D]),ln=i.useCallback(ve=>{if(D)return;const Pe=ae.current?.clientWidth??0,Ke=pe/_u+wl,at=Math.max(Pe,Ke),We=Mu(at);if(ve.key==="ArrowLeft"||ve.key==="ArrowRight"){ve.preventDefault();const It=ve.key==="ArrowLeft"?-wl:wl;ze(Lt=>kl(Lt+It,at));return}if(ve.key==="Home"){ve.preventDefault(),ze(ac);return}ve.key==="End"&&(ve.preventDefault(),ze(We))},[D,pe]),xn=i.useCallback((ve,Pe)=>{ve.preventDefault(),ve.dataTransfer.dropEffect="move",Q(Pe)},[]),qt=i.useCallback(()=>{Q(null)},[]),Qt=i.useCallback(async(ve,Pe)=>{ve.preventDefault(),Q(null);const Ke=ve.dataTransfer.getData("text/plain");if(Ke){if(Pe==="archived"){d("Tasks can only be archived via the archive button","error");return}try{const We=e.find(Bt=>Bt.id===Ke)?.steps.some(Bt=>Bt.status!=="pending")??!1,It=(Pe==="todo"||Pe==="triage")&&We;let Lt;if(It){if(await $({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Lt={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,Pe,Lt)}catch(at){d(Se(at),"error")}}},[n,d,e,$]),hn=ve=>!E||E!==ve?t.jsx(Yg,{size:14,className:"sort-icon"}):K==="asc"?t.jsx(La,{size:14,className:"sort-icon active"}):t.jsx(Bo,{size:14,className:"sort-icon active"}),Zt=ve=>t.jsxs("div",{id:ve,className:"list-view-options-panel",children:[t.jsx("div",{className:"list-view-options-columns",children:vv.map(Pe=>{const Ke=k.has(Pe),at=Ke&&k.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${at?" disabled":""}`,title:at?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:Ke,onChange:()=>ce(Pe),disabled:at}),t.jsx("span",{children:Re[Pe]})]},Pe)})}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>ke(Pe=>!Pe),"aria-pressed":le,title:le?"Show done tasks":"Hide done tasks",children:[le?t.jsx(Fr,{size:14}):t.jsx(zu,{size:14}),le?"Show Done":"Hide Done"]}),t.jsx("div",{className:"list-drop-zones list-drop-zones--sidebar",children:ha.map(Pe=>{const Ke=e.filter(Lt=>Lt.column===Pe).length,at=Pe==="done"||Pe==="archived",We=le&&at?0:Ke,It=le&&at&&Ke>0;return t.jsxs("div",{className:`list-drop-zone${H===Pe?" drag-over":""}${se===Pe?" active":""}`,onClick:()=>ct(Pe),onDragOver:Lt=>xn(Lt,Pe),onDragLeave:qt,onDrop:Lt=>Qt(Lt,Pe),"data-column":Pe,children:[t.jsx("span",{className:`list-section-dot dot-${Pe}`}),t.jsx("span",{className:"drop-zone-label",children:hs[Pe]}),t.jsx("span",{className:"drop-zone-count",children:It?`${We} of ${Ke}`:Ke})]},Pe)})})]});return t.jsxs("div",{className:"list-view",children:[D&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"list-toolbar",children:[t.jsx("button",{className:"btn btn-sm",onClick:Te,"aria-pressed":fe,children:fe?"Done Editing":"Bulk Edit"}),t.jsxs("button",{className:"btn btn-sm list-view-options-toggle",onClick:()=>ne(ve=>!ve),"aria-expanded":je,"aria-controls":"list-view-options-panel-mobile",children:[t.jsx(Tm,{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:se?`${Ee} of ${e.length} tasks in ${hs[se]}`:`${Ee} of ${e.length} tasks`})]}),je?t.jsx("div",{className:"list-toolbar-mobile-options",children:Zt("list-view-options-panel-mobile")}):null]}),t.jsx("div",{className:"list-table-container",children:t.jsxs("div",{className:D?"":"list-split-layout","data-testid":D?void 0:"list-split-layout",ref:ae,children:[t.jsxs("div",{className:D?"":"list-split-sidebar","data-testid":D?void 0:"list-split-sidebar",ref:Ve,style:D?void 0:{width:`${pe}px`},children:[!D&&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:[se?`${Ee} of ${e.length} tasks in ${hs[se]}`:`${Ee} of ${e.length} tasks`,ht>0&&!se&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",ht," hidden)"]})]}),t.jsxs("div",{className:"list-sidebar-controls__actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Te,"aria-pressed":fe,children:fe?"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:[se?t.jsx("button",{className:"btn btn-sm",onClick:ue,"aria-label":"Clear column filter",children:`Filter: ${hs[se]}`}):null,le?t.jsx("span",{className:"list-sidebar-chip",children:"Done hidden"}):null,fe?t.jsx("span",{className:"list-sidebar-chip",children:"Bulk edit"}):null,fe&&re.size>0?t.jsx("button",{className:"btn btn-sm",onClick:Be,children:`${re.size} selected`}):null]})]}),t.jsxs("button",{className:"btn btn-sm list-view-options-toggle",onClick:()=>ne(ve=>!ve),"aria-expanded":je,"aria-controls":"list-view-options-panel",children:[t.jsx(Tm,{size:14}),"View options"]}),je&&Zt("list-view-options-panel"),fe&&re.size>0?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"bulk-edit-toolbar",children:t.jsxs("button",{className:"btn btn-danger btn-sm",onClick:st,disabled:Ie,children:[t.jsx(Tn,{size:14}),"Delete selected"]})}),f&&f.length>0?t.jsxs("div",{className:"bulk-edit-toolbar",children:[t.jsx("span",{className:"bulk-edit-label",children:"Bulk Edit Models & Node:"}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(_s,{models:f,value:Ye,onChange:dt,label:"Executor Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:p,onToggleFavorite:w,favoriteModels:g,onToggleModelFavorite:v})}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(_s,{models:f,value:wt,onChange:St,label:"Reviewer Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:p,onToggleFavorite:w,favoriteModels:g,onToggleModelFavorite:v})}),t.jsxs("div",{className:"bulk-edit-dropdown bulk-edit-node-wrap",children:[t.jsxs("select",{className:"select bulk-node-select",value:Fe,onChange:ve=>J(ve.target.value),"aria-label":"Node Override",disabled:be,children:[t.jsx("option",{value:"__no_change__",children:"No change"}),t.jsx("option",{value:"",children:"Use project default"}),me.map(ve=>t.jsx("option",{value:ve.id,children:`${n$(ve.status)} ${ve.name||ve.id} (${t$(ve.status)})`},ve.id))]}),$t?t.jsx(Ua,{status:$t.status,showLabel:!0}):null]}),t.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:yt,disabled:Ie||Ye==="__no_change__"&&wt==="__no_change__"&&Fe==="__no_change__",children:Ie?"Applying...":"Apply"})]}):null]}):null]}),t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx(Qb,{onCreate:h??(async()=>d("Task creation not available","error")),addToast:d,tasks:e,availableModels:f,onPlanningMode:b,onSubtaskBreakdown:y,projectId:j,autoExpand:!1,favoriteProviders:p,favoriteModels:g,onToggleFavorite:w,onToggleModelFavorite:v})}),Ee===0?t.jsx("div",{className:"list-empty",children:N?"No tasks match your filter":"No tasks yet"}):D?t.jsx("div",{className:"list-cards",children:ha.map(ve=>{if(se&&ve!==se||le&&(ve==="done"||ve==="archived")&&!se)return null;const Pe=oe[ve],Ke=Pe.length===0;if(N&&Ke)return null;const at=He.has(ve);return t.jsxs(i.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${at?" list-section-header--collapsed":""}`,onClick:()=>Ue(ve),"aria-expanded":!at,role:"button",tabIndex:0,onKeyDown:We=>{(We.key==="Enter"||We.key===" ")&&(We.preventDefault(),Ue(ve))},children:[t.jsx(qn,{size:14,className:`list-section-chevron${at?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${ve}`}),t.jsx("span",{className:"list-section-title",children:hs[ve]}),t.jsx("span",{className:"list-section-count",children:Pe.length})]}),!at&&t.jsx(t.Fragment,{children:Ke?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):Pe.map(We=>{const It=We.status==="failed",Lt=We.paused===!0,Bt=ec(We,x,R),Gt=!u&&!It&&!Lt&&!Bt&&(We.column==="in-progress"||rf.has(We.status)),bt=typeof We.status=="string"&&We.status.trim().length>0,Ot=!!(We.dependencies&&We.dependencies.length>0),en=pf(We),Kt=en.hasProgress,Sn=fe;return t.jsxs("div",{className:`list-card${Gt?" agent-active":""}${Sn?" list-card--selectable":""}`,onClick:()=>pt(We),"data-id":We.id,children:[Sn&&t.jsx("label",{className:"list-card-checkbox",onClick:dn=>dn.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:re.has(We.id),onChange:dn=>{dn.stopPropagation(),rt(We.id)},onClick:dn=>dn.stopPropagation(),disabled:We.column==="archived","aria-label":`Select ${We.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:We.id}),We.executionMode==="fast"&&t.jsxs("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",title:"Fast mode","aria-label":"Fast mode",children:[t.jsx(ls,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),t.jsx("span",{className:"list-card-spacer"}),Lt&&We.pausedByAgentId?t.jsx("span",{className:"list-status-badge paused",children:"paused by agent"}):Bt?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):bt?t.jsx("span",{className:`list-status-badge list-status-badge--${We.column}${It?" failed":""}${Gt?" pulsing":""}`,children:of(We.status??"")}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:We.title||We.description})}),(Ot||Kt)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[Ot&&t.jsxs("span",{className:"list-dep-badge",title:We.dependencies.join(", "),children:[t.jsx(Sr,{size:12})," ",We.dependencies.length]}),Kt&&t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${en.percent}%`,backgroundColor:yl[We.column]}})}),t.jsx("span",{className:"list-progress-label",children:en.label})]})]})]},We.id)})})]},ve)})}):t.jsxs("table",{className:"list-table",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[fe&&t.jsx("th",{className:"list-header-cell list-header-checkbox",children:t.jsx("input",{type:"checkbox",checked:xt,ref:ve=>{ve&&(ve.indeterminate=Me)},onChange:tt,"aria-label":"Select all visible tasks"})}),k.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Le("title"),children:["Title ",hn("title")]}),k.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Le("status"),children:["Status ",hn("status")]}),k.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Le("column"),children:["Column ",hn("column")]}),k.has("dependencies")&&t.jsx("th",{className:"list-header-cell",children:"Dependencies"}),k.has("progress")&&t.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),t.jsx("tbody",{children:ha.map(ve=>{if(se&&ve!==se||le&&(ve==="done"||ve==="archived")&&!se)return null;const Pe=oe[ve],Ke=Pe.length===0;if(N&&Ke)return null;const at=He.has(ve);return t.jsxs(i.Fragment,{children:[t.jsx("tr",{className:`list-section-header${at?" list-section-header--collapsed":""}`,onClick:()=>Ue(ve),"aria-expanded":!at,children:t.jsxs("th",{colSpan:k.size+(fe?1:0),className:"list-section-cell",children:[t.jsx(qn,{size:14,className:`list-section-chevron${at?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${ve}`}),t.jsx("span",{className:"list-section-title",children:hs[ve]}),t.jsx("span",{className:"list-section-count",children:Pe.length})]})}),!at&&t.jsx(t.Fragment,{children:Ke?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:k.size+(fe?1:0),className:"list-empty-cell",children:"No tasks"})}):Pe.map(We=>{const It=We.status==="failed",Lt=We.paused===!0,Bt=ec(We,x,R),Gt=!u&&!It&&!Lt&&!Bt&&(We.column==="in-progress"||rf.has(We.status)),bt=A===We.id;return t.jsxs("tr",{className:`list-row${It?" failed":""}${Lt?" paused":""}${Bt?" stuck":""}${Gt?" agent-active":""}${bt?" dragging":""}${L===We.id?" list-row--selected":""}`,onClick:()=>pt(We),draggable:!Lt,onDragStart:Ot=>nn(Ot,We),onDragEnd:on,"data-id":We.id,children:[fe&&t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:re.has(We.id),onChange:Ot=>{Ot.stopPropagation(),rt(We.id)},onClick:Ot=>Ot.stopPropagation(),disabled:We.column==="archived","aria-label":`Select ${We.id}`})}),k.has("title")&&t.jsx("td",{className:"list-cell list-cell-title",children:t.jsxs("div",{className:"list-title-content",children:[t.jsx("span",{className:"list-title-id",children:We.id}),t.jsxs("div",{className:"list-title-row",children:[We.executionMode==="fast"&&t.jsxs("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",title:"Fast mode","aria-label":"Fast mode",children:[t.jsx(ls,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),t.jsx("span",{className:"list-title-text",children:We.title||We.description})]})]})}),k.has("status")&&t.jsx("td",{className:"list-cell",children:Lt&&We.pausedByAgentId?t.jsx("span",{className:"list-status-badge paused",children:"paused by agent"}):Bt?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):We.status?t.jsx("span",{className:`list-status-badge list-status-badge--${We.column}${It?" failed":""}${Gt?" pulsing":""}`,children:of(We.status??"")}):t.jsx("span",{className:"list-status-badge",children:"-"})}),k.has("column")&&t.jsx("td",{className:"list-cell",children:t.jsx("span",{className:"list-column-badge",style:{background:`${yl[We.column]}20`,color:yl[We.column]},children:hs[We.column]})}),k.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:We.dependencies&&We.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:We.dependencies.join(", "),children:[t.jsx(Sr,{size:12})," ",We.dependencies.length]}):"-"}),k.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const Ot=pf(We);return Ot.hasProgress?t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${Ot.percent}%`,backgroundColor:yl[We.column]}})}),t.jsx("span",{className:"list-progress-label",children:Ot.label})]}):"-"})()})]},We.id)})})]},ve)})})]})]}),!D&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"list-split-resize-handle","data-testid":"list-split-resize-handle",onMouseDown:sn,onKeyDown:ln,role:"separator",tabIndex:0,"aria-orientation":"vertical","aria-label":"Resize task list sidebar","aria-valuemin":ac,"aria-valuemax":Math.round(Mu(ae.current?.clientWidth??pe/_u+wl)),"aria-valuenow":Math.round(pe)}),t.jsx("div",{className:"list-split-detail","data-testid":"list-split-detail",children:he?t.jsx("div",{className:"list-split-detail-content","data-testid":"list-split-detail-content",children:t.jsx(xv,{task:he,projectId:j,tasks:e,embedded:!0,onOpenDetail:Dt,onMoveTask:n,onDeleteTask:a,onMergeTask:r,onRetryTask:s,onResetTask:o,onDuplicateTask:l,onTaskUpdated:ve=>{B(Pe=>!Pe||Pe.id!==ve.id?Pe:{...Pe,...ve})},addToast:d,prAuthAvailable:F})}):t.jsx("div",{className:"list-split-detail-empty",children:t.jsx("p",{children:"Select a task to view details"})})})]})]})})]})}const a$={active:{label:"Active",color:"var(--color-success)",icon:os},paused:{label:"Paused",color:"var(--color-warning)",icon:Ci},errored:{label:"Error",color:"var(--color-error)",icon:Vs},initializing:{label:"Initializing",color:"var(--color-warning)",icon:jt}};function r$(e){if(!e)return"Never";const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(a/36e5),l=Math.floor(a/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString()}function ff(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 o$(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 l$({project:e,health:n,onSelect:s,onPause:a,onResume:r,onRemove:o,availabilityMappings:l=[],isLoading:c=!1}){const[d,u]=i.useState(!1),m=a$[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]),w=i.useCallback(S=>{if(S.stopPropagation(),!d){u(!0);return}o(e),u(!1)},[d,o,e]),v=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(js,{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:ff(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:ff(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:r$(e.lastActivityAt||n?.lastActivityAt)})]}),t.jsxs("div",{className:"project-card-actions",children:[v?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(os,{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(Ci,{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(Uo,{size:14}),t.jsx("span",{children:"Open"})]}),t.jsxs("button",{className:`project-card-action project-card-action-remove ${d?"is-armed":""}`,onClick:w,disabled:c,title:d?"Confirm remove":"Remove project","aria-label":d?"Confirm remove project":"Remove project",children:[t.jsx(Tn,{size:14}),t.jsx("span",{children:d?"Confirm":""})]})]})]})]})}const c$=i.memo(l$,o$);function gf(e){return typeof e=="string"&&e.trim().length>0}function ko(e){return(e.nodeMappings??[]).filter(s=>gf(s.nodeId)&&gf(s.path)).map(s=>({nodeId:s.nodeId,nodeName:s.nodeName,path:s.path,available:s.available!==!1}))}function d$(e,n){return ko(e).filter(s=>s.nodeId===n.id&&s.available)}function u$(e,n){return d$(e,n).length>0}function m$(e,n){return e.filter(s=>u$(s,n))}function P8(e,n){return m$(e,n).length}function bf(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 h$(){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(js,{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(Js,{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(Xn,{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(Vs,{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 p$=1e4,xf=5;function f$(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+=xf){const w=e.slice(g,g+xf),v=await Promise.allSettled(w.map(async b=>{try{return await rh(b)}catch{return null}}));if(w.forEach((b,y)=>{const S=v[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 rh(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()},p$),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[m,e.length]),{healthMap:n,loading:a,error:o,refresh:m,refreshProject:h}}function g$({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,w]=i.useState("desc");i.useEffect(()=>{if(typeof window>"u")return;const U=localStorage.getItem("kb-dashboard-recent-projects");if(U)try{const A=JSON.parse(U);b(A)}catch{}},[]);const[v,b]=i.useState([]),y=i.useMemo(()=>e.map(U=>U.id),[e]),{healthMap:S,loading:j}=f$(y),C=i.useMemo(()=>e.map(U=>({project:U,health:S[U.id]||null})),[e,S]),x=i.useMemo(()=>{let U=[...C];return d!=="all"&&(U=U.filter(({project:A})=>A.status===d)),m!==null&&(U=U.filter(({project:A})=>ko(A).some(T=>T.available&&T.nodeId===m))),U},[C,d,m]),N=i.useMemo(()=>{const U=[...x];return U.sort((A,T)=>{let H=0;switch(f){case"name":H=A.project.name.localeCompare(T.project.name);break;case"activity":{const Q=A.project.lastActivityAt||A.health?.lastActivityAt||A.project.updatedAt,se=T.project.lastActivityAt||T.health?.lastActivityAt||T.project.updatedAt;H=new Date(se).getTime()-new Date(Q).getTime();break}case"status":{const Q={errored:0,initializing:1,paused:2,active:3};H=Q[A.project.status]-Q[T.project.status];break}}return g==="asc"?H:-H}),U},[x,f,g]),R=i.useMemo(()=>{const U=e.length,A=e.filter(D=>D.status==="active").length,T=e.filter(D=>D.status==="errored").length,H=new Set;e.forEach(D=>{ko(D).forEach($=>{$.available&&H.add($.nodeId)})});const Q=H.size;let se=0,O=0,M=0;return Object.values(S).forEach(D=>{D&&(se+=D.activeTaskCount,O+=D.totalTasksCompleted,M+=D.inFlightAgentCount)}),{totalProjects:U,activeProjects:A,erroredProjects:T,totalNodes:Q,totalActiveTasks:se,totalCompletedTasks:O,totalInFlightAgents:M}},[e,S]),F=i.useMemo(()=>({all:e.length,active:e.filter(U=>U.status==="active").length,paused:e.filter(U=>U.status==="paused").length,errored:e.filter(U=>U.status==="errored").length}),[e]),E=i.useMemo(()=>{const U=new Map;return e.forEach(A=>{ko(A).filter(T=>T.available).forEach(T=>{const H=T.nodeId,Q=U.get(H),se=bf(H,T,c,A);Q?Q.count+=1:U.set(H,{name:se,count:1})})}),Array.from(U.entries()).map(([A,{name:T,count:H}])=>({nodeId:A,name:T,count:H}))},[e,c]),_=i.useCallback(U=>{const A=[U.id,...v.filter(T=>T!==U.id)].slice(0,3);b(A),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify(A)),s(U)},[s,v]);return n||j&&e.length>0&&Object.keys(S).length===0?t.jsx(h$,{}):e.length===0?t.jsx("div",{className:"project-overview project-overview--empty",children:t.jsxs("div",{className:"project-empty-state",children:[t.jsx("div",{className:"project-empty-state__icon",children:t.jsx(ma,{size:48})}),t.jsx("h2",{className:"project-empty-state__title",children:"No Projects Found"}),t.jsx("p",{className:"project-empty-state__description",children:"Get started by adding your first project. Projects allow you to organize and track tasks across multiple repositories."}),t.jsxs("button",{className:"btn btn-primary project-empty-state__cta",onClick:a,children:[t.jsx($n,{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(va,{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(js,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:R.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(Js,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:R.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(Xn,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:R.totalCompletedTasks}),t.jsx("span",{className:"project-stat__label",children:"Completed"})]})]}),R.erroredProjects>0&&t.jsxs("div",{className:"project-stat project-stat--error",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Vs,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:R.erroredProjects}),t.jsx("span",{className:"project-stat__label",children:"Errored"})]})]}),R.totalNodes>1&&t.jsxs("div",{className:"project-stat project-stat--nodes",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(To,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:R.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($n,{size:16}),"Add Project"]})]}),t.jsxs("div",{className:"project-overview__filters",children:[t.jsxs("div",{className:"project-filter-tabs",children:[t.jsxs("button",{className:`project-filter-tab ${d==="all"?"active":""}`,onClick:()=>u("all"),children:["All",t.jsx("span",{className:"project-filter-count",children:F.all})]}),t.jsxs("button",{className:`project-filter-tab ${d==="active"?"active":""}`,onClick:()=>u("active"),children:["Active",t.jsx("span",{className:"project-filter-count",children:F.active})]}),t.jsxs("button",{className:`project-filter-tab ${d==="paused"?"active":""}`,onClick:()=>u("paused"),children:["Paused",t.jsx("span",{className:"project-filter-count",children:F.paused})]}),t.jsxs("button",{className:`project-filter-tab ${d==="errored"?"active":""} ${F.errored>0?"has-errors":""}`,onClick:()=>u("errored"),children:["Errored",t.jsx("span",{className:"project-filter-count",children:F.errored})]})]}),E.length>1&&t.jsxs("div",{className:"project-node-filter",children:[t.jsx(To,{size:14}),t.jsxs("select",{value:m??"",onChange:U=>{h(U.target.value||null)},className:"project-node-filter-select","aria-label":"Filter by node",children:[t.jsx("option",{value:"",children:"All Nodes"}),E.map(({nodeId:U,name:A,count:T})=>t.jsxs("option",{value:U??"",children:[A," (",T,")"]},U??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(ql,{size:14}),t.jsxs("select",{value:`${f}-${g}`,onChange:U=>{const[A,T]=U.target.value.split("-");p(A),w(T)},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(Yg,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:N.map(({project:U,health:A})=>{const T=ko(U).filter(H=>H.available).map(H=>({...H,displayName:bf(H.nodeId,H,c,U)}));return t.jsx(c$,{project:U,health:A,availabilityMappings:T,onSelect:_,onPause:r,onResume:o,onRemove:l},U.id)})}),N.length===0&&t.jsxs("div",{className:"project-overview__no-results",children:[t.jsx(ql,{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 yv=i.createContext(null);function b$({value:e,children:n}){return i.createElement(yv.Provider,{value:e},n)}function wv(){const e=i.useContext(yv);if(!e)throw new Error("useNavigationHistoryContext must be used within a NavigationHistoryProvider");return e}function x$(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 jm="kb-planning-last-description",Nm="kb-subtask-last-description",Sm="kb-mission-last-goal";function v$(e,n){fs(jm,e,n)}function y$(e){return Gn(jm,e)||""}function hr(e){Ar(jm,e)}function w$(e,n){fs(Nm,e,n)}function k$(e){return Gn(Nm,e)||""}function Id(e){Ar(Nm,e)}function j$(e,n){fs(Sm,e,n)}function N$(e){return Gn(Sm,e)||""}function da(e){Ar(Sm,e)}function S$(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 C$(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 E$(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 bi({entries:e,defaultShowThinking:n=!1}){const[s,a]=i.useState({}),r=E$(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?S$(o):void 0,h=o.question&&m!==void 0?C$(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 vf="fusion-tab-id";function _$(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Ja(){if(typeof window>"u")return"server-tab";const e=window.sessionStorage.getItem(vf);if(e)return e;const n=_$();return window.sessionStorage.setItem(vf,n),n}function Tc(e){const n=i.useMemo(()=>Ja(),[]),[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(S0(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=C0(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=Fi(`/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:yi("/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(E0(e,n)),a(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:d,isLoading:l}}const M$="fusion:ai-session-sync",yf="fusion:ai-session-sync",A$=3e4,R$=6e4;function Ii(){return Date.now()}function I$(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function wf(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 T${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=I$(),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:Ii()})}broadcastUpdate(n){const s=n.timestamp??Ii();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??Ii();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=Ii();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=Ii();this.releaseTabOwnership(n,s,a),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:a})}broadcastHeartbeat(n){const s=Ii();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(M$),this.channel.onmessage=s=>{const a=wf(s.data);a&&this.handleIncomingMessage(a)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==yf||!s.newValue))try{const a=JSON.parse(s.newValue),r=wf(a.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=Ii();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},A$)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,a]of this.ownedSessions.entries()){const r=Ii();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(yf,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:Ii()});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=Ii(),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>R$;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 Ti=new T$;function Wr(){const e=i.useSyncExternalStore(c=>Ti.subscribe(c),()=>Ti.getSnapshot(),()=>Ti.getSnapshot());i.useEffect(()=>{Ti.requestSync()},[]);const n=i.useCallback(c=>{Ti.broadcastUpdate(c)},[]),s=i.useCallback(c=>{Ti.broadcastCompleted(c)},[]),a=i.useCallback((c,d)=>{Ti.broadcastLock(c,d)},[]),r=i.useCallback((c,d)=>{Ti.broadcastUnlock(c,d)},[]),o=i.useCallback(c=>{Ti.broadcastHeartbeat(c)},[]),l=i.useCallback(()=>{Ti.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:a,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function P$(e,n){return e&&n?`${e}/${n}`:""}function $$(e){if(!e)return{provider:void 0,modelId:void 0};const n=e.indexOf("/");return n===-1?{provider:void 0,modelId:void 0}:{provider:e.slice(0,n),modelId:e.slice(n+1)}}const D$=["Build a real-time collaborative document editor","Create a customer onboarding flow with email verification","Add a reporting dashboard with charts and CSV export","Implement a plugin system with marketplace"];function L$({isOpen:e,onClose:n,onMissionCreated:s,projectId:a,initialGoal:r,resumeSessionId:o}){Mi(e);const[l,c]=i.useState(""),[d,u]=i.useState({type:"initial"}),[m,h]=i.useState(null),[f,p]=i.useState([]),[g,w]=i.useState([]),[v,b]=i.useState(null),[y,S]=i.useState(!1),j=i.useRef(!1),[C,x]=i.useState(""),[N,R]=i.useState(!0),[F,E]=i.useState(!1),[_,K]=i.useState(!1),[U,A]=i.useState(!1),T=i.useRef(null),H=i.useRef(null),Q=i.useRef(null),se=i.useRef(null),[O,M]=i.useState(o??null),D=i.useMemo(()=>Ja(),[]),{isLockedByOther:$,takeControl:k,isLoading:X}=Tc(e?O:null),{activeTabMap:le,broadcastUpdate:ke,broadcastCompleted:He,broadcastLock:ye,broadcastUnlock:je,broadcastHeartbeat:ne}=Wr(),{confirm:fe}=li(),[Z,re]=i.useState(void 0),[q,L]=i.useState(void 0),[xe,he]=i.useState([]),[B,pe]=i.useState(!0),[ze,ae]=i.useState(null),[Ve,Te]=i.useState([]),[rt,Be]=i.useState([]),ce=P$(Z,q);i.useEffect(()=>{(async()=>{try{pe(!0);const J=await Ws();he(J.models),Te(J.favoriteProviders),Be(J.favoriteModels)}catch(J){ae(Se(J)||"Failed to load models")}finally{pe(!1)}})()},[]);const Re=i.useCallback(Fe=>{Te(J=>{const me=J,be=me.includes(Fe)?me.filter(gt=>gt!==Fe):[Fe,...me];return Bn({favoriteProviders:be,favoriteModels:rt}).catch(()=>{Te(me)}),be})},[rt]),Le=i.useCallback(Fe=>{Be(J=>{const me=J,be=me.includes(Fe)?me.filter(gt=>gt!==Fe):[Fe,...me];return Bn({favoriteProviders:Ve,favoriteModels:be}).catch(()=>{Be(me)}),be})},[Ve]),ct=i.useCallback((Fe,J)=>{if(!Fe||!J)return"Using default";const me=xe.find(Ze=>Ze.provider===Fe&&Ze.id===J);return me?`${me.provider}/${me.id}`:`${Fe}/${J}`},[xe]),Ue=i.useCallback(Fe=>{H.current?.close();const J=u0(Fe,a,{onThinking:me=>{x(Ze=>Ze+me),ke({sessionId:Fe,status:"generating",needsInput:!1,owningTabId:D,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onQuestion:me=>{E(!1),K(!1),da(a),u({type:"question",sessionId:Fe,question:me}),x(""),S(!0),ke({sessionId:Fe,status:"awaiting_input",needsInput:!0,owningTabId:D,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onSummary:me=>{E(!1),K(!1),da(a),u({type:"summary",sessionId:Fe,summary:me}),b(me),x(""),S(!0),ke({sessionId:Fe,status:"complete",needsInput:!1,owningTabId:D,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onError:me=>{const Ze=me||"Session failed while contacting the AI.";E(!1),K(!1),h(null),u({type:"error",sessionId:Fe,errorMessage:Ze}),x(""),S(!0),Q.current=Fe,ke({sessionId:Fe,status:"error",needsInput:!1,owningTabId:D,type:"mission_interview",title:l.trim()||void 0,projectId:a??null}),He({sessionId:Fe,status:"error"})},onComplete:()=>{E(!1),K(!1),Q.current=null,He({sessionId:Fe,status:"complete"})},onConnectionStateChange:me=>{E(me==="reconnecting")}});H.current=J},[He,ke,l,a,D]),ue=i.useCallback(async Fe=>{const J=Fe??l;if(J.trim()){h(null),x(""),p([]),w([]),E(!1),u({type:"loading"});try{const{sessionId:me}=await a0(J.trim(),a,Z&&q?{modelProvider:Z,modelId:q}:void 0);Q.current=me,M(me),da(a),Ue(me),p([])}catch(me){E(!1),h(Se(me)||"Failed to start interview session"),u({type:"initial"}),Q.current=null,M(null)}}},[Ue,l,Z,q,a]);i.useEffect(()=>{e&&d.type==="initial"&&T.current?.focus()},[e,d.type]),i.useEffect(()=>{if(e&&!r&&!o&&!j.current&&d.type==="initial"){const Fe=N$(a);Fe&&c(Fe)}},[e]),i.useEffect(()=>{if(e&&r&&!j.current&&d.type==="initial"){c(r);const Fe=setTimeout(()=>{j.current=!0,ue(r)},0);return()=>clearTimeout(Fe)}},[e,r,d.type,ue]),i.useEffect(()=>{e||(j.current=!1,E(!1),K(!1),M(null))},[e]),i.useEffect(()=>{if(!e||!o||d.type!=="initial")return;let Fe=!1;return Di(o).then(J=>{if(Fe||!J)return;const me=Mr(J.conversationHistory);if(w(me),M(J.id),p(me.map(Ze=>Ze.response).filter(Ze=>!!(Ze&&typeof Ze=="object"&&!Array.isArray(Ze)))),J.status==="awaiting_input"&&J.currentQuestion)try{da(a);const Ze=JSON.parse(J.currentQuestion);Q.current=J.id,S(!0),u({type:"question",sessionId:J.id,question:Ze})}catch{h("Failed to restore session question.")}else if(J.status==="complete"&&J.result)try{da(a);const Ze=JSON.parse(J.result);Q.current=J.id,S(!0),b(Ze),u({type:"summary",sessionId:J.id,summary:Ze})}catch{h("Failed to restore session result.")}else J.status==="generating"?(Q.current=J.id,S(!0),J.thinkingOutput&&x(J.thinkingOutput),u({type:"loading"}),Ue(J.id)):J.status==="error"&&(Q.current=J.id,S(!0),h(null),u({type:"error",sessionId:J.id,errorMessage:J.error??"The session encountered an error."}))}).catch(()=>{Fe||h("Failed to resume session.")}),()=>{Fe=!0}},[Ue,e,o,d.type,a]),i.useEffect(()=>{if(!e){se.current&&(je(se.current,D),se.current=null);return}if(O&&se.current!==O){se.current&&je(se.current,D),ye(O,D),se.current=O;return}!O&&se.current&&(je(se.current,D),se.current=null)},[ye,je,e,O,D]),i.useEffect(()=>{if(!e||!O||se.current!==O)return;ne(D);const Fe=setInterval(()=>{ne(D)},3e4);return()=>{clearInterval(Fe)}},[ne,e,O,D]),i.useEffect(()=>()=>{H.current?.close(),H.current=null,se.current&&(je(se.current,D),se.current=null)},[je,D]),i.useEffect(()=>{if(!e)return;const Fe=J=>{(d.type==="question"||d.type==="summary")&&(J.preventDefault(),J.returnValue=""),H.current?.close()};return window.addEventListener("beforeunload",Fe),()=>window.removeEventListener("beforeunload",Fe)},[e,d]);const oe=i.useCallback(()=>{H.current?.close(),H.current=null,n()},[n]),Ee=i.useCallback(async()=>{if(l&&j$(l,a),!(y&&!await fe({title:"Close Interview",message:"Are you sure you want to close? Your interview progress will be lost.",danger:!0}))){if(H.current?.close(),H.current=null,d.type==="question"||d.type==="summary"||d.type==="error")try{await kb(d.sessionId,a,D)}catch{}c(""),u({type:"initial"}),h(null),p([]),w([]),b(null),x(""),E(!1),K(!1),S(!1),A(!1),re(void 0),L(void 0),Q.current=null,M(null),n()}},[l,y,d,n,a,D,fe]);i.useEffect(()=>{if(!e)return;const Fe=J=>{J.key==="Escape"&&Ee()};return document.addEventListener("keydown",Fe),()=>document.removeEventListener("keydown",Fe)},[e,Ee]);const ft=i.useCallback(async Fe=>{if(d.type!=="question")return;const{sessionId:J}=d;h(null),p(me=>[...me,Fe]),w(me=>[...me,{question:d.question,response:Fe}]),u({type:"loading"}),x("");try{Ue(J),await r0(J,Fe,a,D),S(!0)}catch(me){H.current?.close(),H.current=null,h(Se(me)||"Failed to submit response"),u({type:"question",sessionId:J,question:d.question})}},[d,a,D,Ue]),ht=i.useCallback(async()=>{if(d.type!=="error")return;const Fe=d.sessionId;h(null),K(!0),x(""),u({type:"loading"}),Ue(Fe);try{Q.current=Fe,M(Fe),await o0(Fe,a,D)}catch(J){let me=J;if((Se(J)||"").includes("not in an error state"))try{const be=await Di(Fe);if(!be)throw new Error("Failed to refresh interview session.");const gt=Mr(be.conversationHistory);if(w(gt),p(gt.map($t=>$t.response).filter($t=>!!($t&&typeof $t=="object"&&!Array.isArray($t)))),Q.current=be.id,M(be.id),S(!0),be.status==="generating")x(be.thinkingOutput??""),u({type:"loading"}),H.current?.isConnected()||Ue(be.id);else if(be.status==="awaiting_input"){if(!be.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");da(a);const $t=JSON.parse(be.currentQuestion);u({type:"question",sessionId:be.id,question:$t}),H.current?.isConnected()||Ue(be.id)}else if(be.status==="complete"){if(!be.result)throw new Error("Interview session is complete but has no result.");da(a);const $t=JSON.parse(be.result);b($t),u({type:"summary",sessionId:be.id,summary:$t})}else be.status==="error"&&u({type:"error",sessionId:be.id,errorMessage:be.error??"Retry failed. Please try again."});E(!1);return}catch(be){me=be}H.current?.close(),H.current=null,u({type:"error",sessionId:Fe,errorMessage:Se(me)||"Retry failed. Please try again."}),E(!1)}finally{K(!1)}},[Ue,a,D,d]),tt=i.useCallback(async()=>{if(d.type==="summary"){h(null),A(!0);try{const Fe=await d0(d.sessionId,v||void 0,a);s(Fe),da(a),H.current?.close(),H.current=null,c(""),u({type:"initial"}),h(null),p([]),w([]),b(null),x(""),E(!1),K(!1),S(!1),A(!1),Q.current=null,M(null),n()}catch(Fe){h(Se(Fe)||"Failed to create mission"),A(!1)}}},[d,v,s,n,a]),xt=()=>d.type==="question"?Math.min(f.length+1,6):6,Me=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",Ye=O?le.get(O):null,dt=Ye&&Ye.tabId!==D,wt=!!(dt&&!Ye.stale),St=$&&(!dt||Ye.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Fe=>Fe.target===Fe.currentTarget&&Ee(),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(Es,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Plan Mission with AI"})]}),t.jsxs("div",{className:"modal-header-actions",children:[Me&&t.jsx("button",{className:"modal-send-to-background",onClick:oe,title:"Send to background","aria-label":"Send to background",children:t.jsx(qo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:Ee,"aria-label":"Close",children:t.jsx(mn,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[m&&t.jsx("div",{className:"form-error planning-error",children:m}),F&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),wt&&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(ms,{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:T,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:Fe=>c(Fe.target.value),onKeyDown:Fe=>{Fe.key==="Enter"&&!Fe.shiftKey&&l.trim()&&(Fe.preventDefault(),ue())}})]}),t.jsxs("div",{className:"planning-examples",children:[t.jsx("span",{className:"planning-examples-label",children:"Try an example:"}),t.jsx("div",{className:"planning-example-chips",children:D$.map((Fe,J)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c(Fe),children:Fe.length>45?Fe.slice(0,45)+"...":Fe},J))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",B&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(_s,{id:"mission-interview-modal-model",label:"Planning Model",value:ce,onChange:Fe=>{const{provider:J,modelId:me}=$$(Fe);re(J),L(me)},models:xe,disabled:B,favoriteProviders:Ve,onToggleFavorite:Re,favoriteModels:rt,onToggleModelFavorite:Le}),ze&&t.jsxs("div",{className:"form-hint form-hint-error",children:[ze," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{pe(!0);const Fe=await Ws();he(Fe.models),Te(Fe.favoriteProviders),Be(Fe.favoriteModels),ae(null)}catch(Fe){ae(Se(Fe)||"Failed to load models")}finally{pe(!1)}})()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${Z&&q?"model-badge-custom":"model-badge-default"}`,children:ct(Z,q)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>ue(),disabled:!l.trim(),children:[t.jsx(Es,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),d.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(jt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:C?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>R(!N),type:"button",children:N?"Hide thinking":"Show thinking"}),N&&C&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:C})})]})]}),d.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[g.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(bi,{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 ht(),disabled:_,children:[_?t.jsx(jt,{size:14,className:"spin"}):t.jsx(ps,{size:14}),t.jsx("span",{className:"icon-ml-6",children:_?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Ee,disabled:_,children:"Cancel"})]})]})]})}),d.type==="question"&&t.jsx(O$,{question:d.question,progress:xt(),historyEntries:g,onSubmit:ft}),d.type==="summary"&&v&&t.jsx(F$,{summary:v,historyEntries:g,onSummaryChange:b,onApprove:tt,onStartOver:()=>{u({type:"initial"}),S(!1),b(null),p([]),w([]),M(null),H.current?.close(),H.current=null},isCreating:U}),$&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(yc,{size:16}),t.jsx("span",{children:St?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),St&&t.jsx("button",{type:"button",onClick:()=>{k()},disabled:X,className:"btn btn-primary session-lock-take-control",children:X?"Taking control...":"Take Control"})]})})]})]})}):null}function O$({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(bi,{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 w=g.target.checked?[...p,f.id]:p.filter(v=>v!==f.id);o({[e.id]:w})}}),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(Xn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(mn,{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(Uo,{size:16,className:"icon-ml-4"})]})})]})}function F$({summary:e,historyEntries:n,onSummaryChange:s,onApprove:a,onStartOver:r,isCreating:o}){const[l,c]=i.useState(()=>new Set(e.milestones.map((j,C)=>C))),[d,u]=i.useState(()=>{const j=new Set;return e.milestones.forEach((C,x)=>{C.slices.forEach((N,R)=>j.add(`${x}-${R}`))}),j}),m=j=>{c(C=>{const x=new Set(C);return x.has(j)?x.delete(j):x.add(j),x})},h=j=>{u(C=>{const x=new Set(C);return x.has(j)?x.delete(j):x.add(j),x})},f=(j,C)=>{const x=[...e.milestones];x[j]={...x[j],...C},s({...e,milestones:x})},p=(j,C,x)=>{const N=[...e.milestones],R=[...N[j].slices];R[C]={...R[C],...x},N[j]={...N[j],slices:R},s({...e,milestones:N})},g=(j,C,x,N)=>{const R=[...e.milestones],F=[...R[j].slices],E=[...F[C].features];E[x]={...E[x],...N},F[C]={...F[C],features:E},R[j]={...R[j],slices:F},s({...e,milestones:R})},w=j=>{const C=e.milestones.filter((x,N)=>N!==j);s({...e,milestones:C})},v=(j,C)=>{const x=[...e.milestones];x[j]={...x[j],slices:x[j].slices.filter((N,R)=>R!==C)},s({...e,milestones:x})},b=(j,C,x)=>{const N=[...e.milestones],R=[...N[j].slices];R[C]={...R[C],features:R[C].features.filter((F,E)=>E!==x)},N[j]={...N[j],slices:R},s({...e,milestones:N})},y=(j,C)=>{const x=[...e.milestones],N=[...x[j].slices];N[C]={...N[C],features:[...N[C].features,{title:"New feature",description:""}]},x[j]={...x[j],slices:N},s({...e,milestones:x})},S=e.milestones.reduce((j,C)=>j+C.slices.reduce((x,N)=>x+N.features.length,0),0);return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(bi,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Xn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Mission Plan Ready"}),t.jsxs("p",{className:"text-muted",children:[e.milestones.length," milestones, ",S," features. Review and edit before approving."]})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Title"}),t.jsx("input",{type:"text",className:"form-input",value:e.missionTitle||"",onChange:j=>s({...e,missionTitle:j.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Description"}),t.jsx("textarea",{className:"planning-textarea",rows:3,value:e.missionDescription||"",onChange:j=>s({...e,missionDescription:j.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Roadmap"}),t.jsx("div",{className:"roadmap-list",children:e.milestones.map((j,C)=>t.jsxs("div",{className:"roadmap-card",children:[t.jsxs("div",{className:"roadmap-card-header",onClick:()=>m(C),children:[l.has(C)?t.jsx(gn,{size:16,className:"icon-text-secondary"}):t.jsx(qn,{size:16,className:"icon-text-secondary"}),t.jsx(Fa,{size:16,className:"icon-milestone"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:j.title,onChange:x=>f(C,{title:x.target.value}),onClick:x=>x.stopPropagation()}),e.milestones.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:x=>{x.stopPropagation(),w(C)},title:"Remove milestone",children:t.jsx(Tn,{size:14,className:"icon-text-secondary"})})]}),l.has(C)&&t.jsxs("div",{className:"roadmap-card-body",children:[t.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:j.description||"",onChange:x=>f(C,{description:x.target.value})}),t.jsxs("div",{className:"roadmap-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Verification Criteria"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-sm",rows:2,placeholder:"How to confirm this milestone is complete...",value:j.verification||"",onChange:x=>f(C,{verification:x.target.value})})]}),j.slices.map((x,N)=>{const R=`${C}-${N}`;return t.jsxs("div",{className:"roadmap-slice-card",children:[t.jsxs("div",{className:"roadmap-slice-header",onClick:()=>h(R),children:[d.has(R)?t.jsx(gn,{size:14,className:"icon-text-secondary"}):t.jsx(qn,{size:14,className:"icon-text-secondary"}),t.jsx(ru,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:x.title,onChange:F=>p(C,N,{title:F.target.value}),onClick:F=>F.stopPropagation()}),j.slices.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:F=>{F.stopPropagation(),v(C,N)},title:"Remove slice",children:t.jsx(Tn,{size:12,className:"icon-text-secondary"})})]}),d.has(R)&&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:x.verification||"",onChange:F=>p(C,N,{verification:F.target.value})})]}),x.features.map((F,E)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(eu,{size:12,className:"icon-feature"}),t.jsxs("div",{className:"roadmap-feature-content",children:[t.jsx("input",{type:"text",className:"form-input roadmap-input-feature",value:F.title,onChange:_=>g(C,N,E,{title:_.target.value})}),F.description&&t.jsx("p",{className:"roadmap-feature-text",children:F.description}),F.acceptanceCriteria&&t.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",F.acceptanceCriteria]})]}),t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>b(C,N,E),title:"Remove feature",children:t.jsx(Tn,{size:12,className:"icon-text-secondary"})})]},E)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>y(C,N),children:[t.jsx($n,{size:12}),"Add Feature"]})]})]},N)})]})]},C))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:o,children:[t.jsx(Ga,{size:16,className:"icon-mr-4"}),"Start Over"]}),t.jsx("button",{className:"btn btn-primary",onClick:a,disabled:o||e.milestones.length===0,children:o?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Xn,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}const z$=30,B$=16,U$=16;function H$(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let Ul=null;function kv(){return Ul===null&&(Ul=window.visualViewport?.height??window.innerHeight),Ul}function q$(e){const n=kv();e>n&&(Ul=e)}function V$(e){return e?e instanceof HTMLTextAreaElement?!0:e instanceof HTMLInputElement?!new Set(["checkbox","radio","button","submit","reset","file","range","color","hidden"]).has(e.type):e instanceof HTMLElement&&e.isContentEditable:!1}function kf(){if(typeof window>"u"||!window.visualViewport)return{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0};const e=window.visualViewport,n=V$(document.activeElement),s=e.offsetTop;n||q$(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=kv(),o=Math.max(0,r-e.offsetTop-e.height);if(o>=z$&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};if(o>=B$&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};const l=Math.max(0,r-e.height);return n&&l>=U$?{overlap:0,open:!0,vvHeight:e.height,vvOffsetTop:s}:{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0}}function aa({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||!H$()){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 x=kf();s(x.overlap),r(x.vvHeight),l(x.vvOffsetTop),d(x.open)},h=()=>{const x=kf();s(x.overlap),r(x.vvHeight),d(x.open)},f=[],p=x=>{if(typeof window>"u")return;const N=window.setTimeout(()=>{typeof window>"u"||m()},x);f.push(N)};let g=null,w=0,v=-1,b=0;const y=()=>{g!==null&&typeof window<"u"&&(window.cancelAnimationFrame(g),g=null)},S=()=>{if(typeof window>"u")return;m();const x=window.visualViewport?.offsetTop??0;if(x===v?b+=1:(b=0,v=x),b>=2||performance.now()>w){g=null;return}g=window.requestAnimationFrame(S)},j=()=>{typeof window>"u"||(y(),w=performance.now()+1500,v=-1,b=0,g=window.requestAnimationFrame(S))},C=()=>{m(),p(50),p(200),p(500),p(1e3),p(1500),j()};return C(),u.addEventListener("resize",m),u.addEventListener("scroll",h),document.addEventListener("focusin",C),document.addEventListener("focusout",m),document.addEventListener("visibilitychange",C),window.addEventListener("pageshow",C),()=>{u.removeEventListener("resize",m),u.removeEventListener("scroll",h),document.removeEventListener("focusin",C),document.removeEventListener("focusout",m),document.removeEventListener("visibilitychange",C),window.removeEventListener("pageshow",C);for(const x of f)clearTimeout(x);y(),s(0),r(null),l(0),d(!1)}},[e]),{keyboardOverlap:n,viewportHeight:a,viewportOffsetTop:o,keyboardOpen:c}}function W$({isOpen:e,onClose:n,onApplied:s,targetType:a,targetId:r,targetTitle:o,missionContext:l,projectId:c,resumeSessionId:d}){const u=oi();Mi(e);const{keyboardOverlap:m,viewportHeight:h,viewportOffsetTop:f,keyboardOpen:p}=aa({enabled:u==="mobile"}),g=p?{"--keyboard-overlap":`${m}px`,"--vv-offset-top":`${f}px`,...h!==null?{"--vv-height":`${h}px`}:{}}:{},[w,v]=i.useState({type:"initial"}),[b,y]=i.useState(null),[S,j]=i.useState([]),[C,x]=i.useState([]),[N,R]=i.useState(null),[F,E]=i.useState(""),[_,K]=i.useState(!0),[U,A]=i.useState(!1),[T,H]=i.useState(!1),Q=i.useRef(null),se=i.useRef(null),O=i.useRef(null),M=i.useRef(null),[D,$]=i.useState(null),k=i.useMemo(()=>Ja(),[]);Tc(e?D:null);const{activeTabMap:X,broadcastUpdate:le,broadcastCompleted:ke,broadcastLock:He,broadcastUnlock:ye,broadcastHeartbeat:je}=Wr(),ne=a==="milestone"?m0:b0,fe=a==="milestone"?h0:x0,Z=a==="milestone"?p0:v0,re=a==="milestone"?f0:y0,q=a==="milestone"?g0:w0,L=a==="milestone"?"Milestone":"Slice",xe=a==="milestone"?"milestone_interview":"slice_interview",he=i.useCallback(Ue=>{se.current?.close();const ue=Z(Ue,c,{onThinking:oe=>{E(Ee=>Ee+oe),le({sessionId:Ue,status:"generating",needsInput:!1,owningTabId:k,type:xe,title:o,projectId:c??null})},onQuestion:oe=>{A(!1),B(),v({type:"question",sessionId:Ue,question:oe}),E(""),le({sessionId:Ue,status:"awaiting_input",needsInput:!0,owningTabId:k,type:xe,title:o,projectId:c??null})},onSummary:oe=>{A(!1),B(),v({type:"summary",sessionId:Ue,summary:oe}),R(oe),E(""),le({sessionId:Ue,status:"complete",needsInput:!1,owningTabId:k,type:xe,title:o,projectId:c??null})},onError:oe=>{const Ee=oe||"Session failed while contacting the AI.";A(!1),y(null),v({type:"error",sessionId:Ue,errorMessage:Ee}),E(""),O.current=Ue,le({sessionId:Ue,status:"error",needsInput:!1,owningTabId:k,type:xe,title:o,projectId:c??null}),ke({sessionId:Ue,status:"error"})},onComplete:()=>{A(!1),O.current=null,ke({sessionId:Ue,status:"complete"})},onConnectionStateChange:oe=>{A(oe==="reconnecting")}});se.current=ue},[ke,le,Z,xe,c,k,o]),B=()=>{R(null),j([]),x([]),E("")},pe=i.useCallback(async()=>{y(null),B(),A(!1),v({type:"loading"});try{const{sessionId:Ue}=await ne(r,c);O.current=Ue,$(Ue),he(Ue)}catch(Ue){A(!1),y(Se(Ue)||`Failed to start ${L.toLowerCase()} interview`),v({type:"initial"}),O.current=null,$(null)}},[he,c,ne,r,L]),ze=i.useCallback(async()=>{y(null),H(!0);try{await q(r,c),s(),v({type:"applied"})}catch(Ue){y(Se(Ue)||`Failed to skip ${L.toLowerCase()} interview`),H(!1)}},[s,c,q,r,L]);i.useEffect(()=>{e&&w.type==="initial"&&Q.current?.focus()},[e,w.type]),i.useEffect(()=>{if(!e||!d||w.type!=="initial")return;let Ue=!1;return Di(d).then(ue=>{if(Ue||!ue)return;const oe=Mr(ue.conversationHistory);if(x(oe),$(ue.id),j(oe.map(Ee=>Ee.response).filter(Ee=>!!(Ee&&typeof Ee=="object"&&!Array.isArray(Ee)))),ue.status==="awaiting_input"&&ue.currentQuestion)try{const Ee=JSON.parse(ue.currentQuestion);O.current=ue.id,v({type:"question",sessionId:ue.id,question:Ee})}catch{y("Failed to restore session question.")}else if(ue.status==="complete"&&ue.result)try{const Ee=JSON.parse(ue.result);O.current=ue.id,R(Ee),v({type:"summary",sessionId:ue.id,summary:Ee})}catch{y("Failed to restore session result.")}else ue.status==="generating"?(O.current=ue.id,ue.thinkingOutput&&E(ue.thinkingOutput),v({type:"loading"}),he(ue.id)):ue.status==="error"&&(O.current=ue.id,y(null),v({type:"error",sessionId:ue.id,errorMessage:ue.error??"The session encountered an error."}))}).catch(()=>{Ue||y("Failed to resume session.")}),()=>{Ue=!0}},[he,e,d,w.type]),i.useEffect(()=>{e||(A(!1),$(null))},[e]),i.useEffect(()=>{if(!(!e||!D)){if(M.current!==D){M.current&&ye(M.current,k),He(D,k),M.current=D;return}!D&&M.current&&(ye(M.current,k),M.current=null)}},[He,ye,e,D,k]),i.useEffect(()=>{if(!e||!D||M.current!==D)return;je(k);const Ue=setInterval(()=>{je(k)},3e4);return()=>{clearInterval(Ue)}},[je,e,D,k]),i.useEffect(()=>()=>{se.current?.close(),se.current=null,M.current&&(ye(M.current,k),M.current=null)},[ye,k]);const ae=i.useCallback(()=>{se.current?.close(),se.current=null,n()},[n]),Ve=i.useCallback(async()=>{se.current?.close(),se.current=null,B(),v({type:"initial"}),y(null),O.current=null,$(null),n()},[n]),Te=i.useCallback(async Ue=>{if(w.type!=="question")return;const{sessionId:ue}=w;y(null),j(oe=>[...oe,Ue]),x(oe=>[...oe,{question:w.question,response:Ue}]),v({type:"loading"}),E("");try{he(ue),await fe(ue,Ue,c,k)}catch(oe){se.current?.close(),se.current=null,y(Se(oe)||"Failed to submit response"),v({type:"question",sessionId:ue,question:w.question})}},[he,c,fe,k,w]),rt=i.useCallback(async()=>{if(w.type==="summary"){y(null),H(!0);try{await re(w.sessionId,N||void 0,c),s(),v({type:"applied"})}catch(Ue){y(Se(Ue)||"Failed to apply interview results"),H(!1)}}},[re,N,s,c,w]),Be=()=>w.type==="question"?Math.min(S.length+1,6):6,ce=w.type==="loading"||w.type==="question"||w.type==="summary"||w.type==="error",Re=D?X.get(D):null,ct=!!(Re&&Re.tabId!==k&&!Re.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Ue=>Ue.target===Ue.currentTarget&&Ve(),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(ms,{size:20,className:"icon-triage"}),t.jsxs("h3",{children:["Plan ",L,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[ce&&t.jsx("button",{className:"modal-send-to-background",onClick:ae,title:"Send to background","aria-label":"Send to background",children:t.jsx(qo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:Ve,"aria-label":"Close",children:t.jsx(mn,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[b&&t.jsx("div",{className:"form-error planning-error",children:b}),U&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),ct&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),w.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(ms,{size:32,className:"icon-triage-lg"}),t.jsxs("h4",{children:["Refine ",L," scope with AI"]}),t.jsxs("p",{className:"text-muted",children:["The AI will interview you to refine the ",a,"'s scope, acceptance criteria, and verification methods. Each ",a," can have its own refined plan or inherit context from the mission level."]}),l&&t.jsxs("div",{className:"planning-context-info",children:[t.jsx("span",{className:"planning-context-label",children:"Mission context:"}),t.jsx("span",{className:"planning-context-text",children:l})]})]})}),t.jsxs("div",{className:"planning-view-footer",children:[t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>void pe(),children:[t.jsx(ms,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void ze(),disabled:T,children:[T?t.jsx(jt,{size:16,className:"spin"}):null,"Use Mission Context"]}),t.jsx("button",{className:"btn",onClick:Ve,children:"Cancel"})]})]}),w.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(jt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:F?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>K(!_),type:"button",children:_?"Hide thinking":"Show thinking"}),_&&F&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:F})})]})]}),w.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(bi,{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:w.errorMessage}),t.jsx("div",{className:"ai-error-actions",children:t.jsx("button",{className:"btn",onClick:Ve,children:"Cancel"})})]})]})}),w.type==="question"&&t.jsx(G$,{question:w.question,progress:Be(),historyEntries:C,onSubmit:Te}),w.type==="summary"&&N&&t.jsx(K$,{summary:N,historyEntries:C,onSummaryChange:R,onApply:rt,onCancel:Ve,isApplying:T}),w.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(Xn,{size:48,className:"icon-success"}),t.jsxs("h4",{children:[L," Updated"]}),t.jsxs("p",{className:"text-muted",children:["The ",a,"'s scope and verification have been ",w.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 G$({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(bi,{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 w=g.target.checked?[...p,f.id]:p.filter(v=>v!==f.id);o({[e.id]:w})}}),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(Xn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(mn,{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(Uo,{size:16,className:"icon-ml-4"})]})})]})}function K$({summary:e,historyEntries:n,onSummaryChange:s,onApply:a,onCancel:r,isApplying:o}){const[l,c]=i.useState(e),[d,u]=i.useState(!0),m=(h,f)=>{const p={...l,[h]:f};c(p),s(p)};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(bi,{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(gn,{size:16}):t.jsx(qn,{size:16}),t.jsx("span",{children:"Refined Scope"})]})}),d&&t.jsxs("div",{className:"planning-summary-content",children:[l.description&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:l.description,onChange:h=>m("description",h.target.value)})]}),l.planningNotes&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Planning Notes"}),t.jsx("textarea",{rows:3,value:l.planningNotes,onChange:h=>m("planningNotes",h.target.value)})]}),l.verification&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Verification Criteria"}),t.jsx("textarea",{rows:2,value:l.verification,onChange:h=>m("verification",h.target.value)})]}),!l.description&&!l.planningNotes&&!l.verification&&t.jsx("p",{className:"text-muted planning-summary-empty",children:"No additional details were generated for this item."})]})]})]}),t.jsxs("div",{className:"planning-view-footer",children:[t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:a,disabled:o,children:[o?t.jsx(jt,{size:16,className:"spin"}):null,"Apply"]}),t.jsx("button",{className:"btn",onClick:r,disabled:o,children:"Cancel"})]})]})}const jf=300,jl=220,Nl=560,Nf="fusion:mission-sidebar-width",lo={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)"}},Sf={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)"}},Cf={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)"}},Cl={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)"}},El={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)"}},Ef={not_started:{bg:"var(--assertion-pending-bg)",text:"var(--assertion-pending-text)"},needs_coverage:{bg:"var(--loop-needs-fix-bg)",text:"var(--loop-needs-fix-text)"},ready:{bg:"var(--loop-validating-bg)",text:"var(--loop-validating-text)"},passed:{bg:"var(--loop-passed-bg)",text:"var(--loop-passed-text)"},failed:{bg:"var(--loop-blocked-bg)",text:"var(--loop-blocked-text)"},blocked:{bg:"var(--loop-blocked-bg)",text:"var(--loop-blocked-text)"}},J$=3,Y$=new Set(["generating","awaiting_input","error"]);function Q$(e){switch(e){case"generating":return"Generating plan";case"awaiting_input":return"Awaiting input";case"error":return"Needs retry";default:return e}}function X$(e){return e==="error"?"Retry interview":"Resume interview"}function Z$(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function _f({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 Mf(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const Af={title:"",description:"",status:"planning",autopilotEnabled:!1},Td={title:"",description:"",status:"planning",dependencies:[]},Pd={title:"",description:"",status:"pending"},$d={title:"",description:"",acceptanceCriteria:"",status:"defined"},e4=3600*1e3;function rc(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 t4(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=e4,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 n4(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 s4(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 Dd(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 jv=["feature_triaged","feature_completed"],Nv=["slice_activated","slice_completed","milestone_completed"],Sv=["mission_started","mission_paused","mission_resumed","mission_completed"],Cv=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function Rf(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return Sv.includes(e);case"tasks":return jv.includes(e);case"slices":return Nv.includes(e);case"autopilot":return Cv.includes(e);default:return!0}}function i4(e){return e==="error"||e==="warning"?"mission-event__type--error":Sv.includes(e)?"mission-event__type--state":jv.includes(e)?"mission-event__type--task":Nv.includes(e)?"mission-event__type--slice":Cv.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function a4(e){return e.replace(/_/g," ")}function r4(e,n){return n?e==="watching"?`Watching since ${rc(n)}`:`Last activation ${rc(n)}`:null}function o4({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,w]=i.useState(null),[v,b]=i.useState(!0),[y,S]=i.useState(!1),j=oi()==="mobile",{pushNav:C}=wv(),[x,N]=i.useState(()=>{if(typeof window>"u")return jf;const z=window.localStorage.getItem(Nf),Ae=z?Number(z):NaN;return Number.isFinite(Ae)?Math.max(jl,Math.min(Nl,Ae)):jf}),R=i.useCallback(z=>{try{window.localStorage.setItem(Nf,String(z))}catch{}},[]),F=i.useCallback(z=>{if(j)return;z.preventDefault(),z.stopPropagation();const Ae=z.currentTarget;typeof Ae.setPointerCapture=="function"&&Ae.setPointerCapture(z.pointerId);const Ge=z.clientX,kt=x;let An=kt;document.body.style.userSelect="none";const Vt=Xe=>{const lt=Xe.clientX-Ge,Tt=Math.max(jl,Math.min(Nl,kt+lt));An=Tt,N(Tt)},Nn=Xe=>{typeof Ae.releasePointerCapture=="function"&&Ae.releasePointerCapture(Xe.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",Vt),document.removeEventListener("pointerup",Nn),R(An)};document.addEventListener("pointermove",Vt),document.addEventListener("pointerup",Nn)},[j,R,x]),E=i.useCallback(z=>{if(j||z.key!=="ArrowLeft"&&z.key!=="ArrowRight")return;z.preventDefault();const Ae=z.shiftKey?50:10,Ge=z.key==="ArrowLeft"?-Ae:Ae,kt=Math.max(jl,Math.min(Nl,x+Ge));N(kt),R(kt)},[j,R,x]),[_,K]=i.useState(!1),[U,A]=i.useState(null),[T,H]=i.useState(Af),[Q,se]=i.useState(!1),[O,M]=i.useState(new Set),[D,$]=i.useState(new Set),[k,X]=i.useState(null),[le,ke]=i.useState(Td),[He,ye]=i.useState(!1),[je,ne]=i.useState(null),[fe,Z]=i.useState(Pd),[re,q]=i.useState(!1),[L,xe]=i.useState(null),[he,B]=i.useState(null),[pe,ze]=i.useState($d),[ae,Ve]=i.useState(!1),[Te,rt]=i.useState(null),[Be,ce]=i.useState(null),[Re,Le]=i.useState(""),[ct,Ue]=i.useState(!1),[ue,oe]=i.useState([]),[Ee,ft]=i.useState([]),[ht,tt]=i.useState(void 0),xt=i.useRef(null),Me=ht??(c&&xt.current===c?void 0:c),[Ye,dt]=i.useState(null),[wt,St]=i.useState(null),[Fe,J]=i.useState(null);i.useEffect(()=>{h&&Me&&Ue(!0)},[h,Me]),i.useEffect(()=>{c&&xt.current!==c&&(xt.current=null)},[c]),i.useEffect(()=>{if(!h)return;let z=!1;return Wu(r).then(Ae=>{if(z)return;const Ge=Ae.filter(kt=>kt.type!=="mission_interview"||!Y$.has(kt.status)?!1:r?kt.projectId===r:kt.projectId==null);oe(Ge)}).catch(Ae=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",Ae)}),()=>{z=!0}},[h,r,Me]),i.useEffect(()=>{if(!h)return;let z=!1;return l0(r).then(Ae=>{z||ft(Ae)}).catch(Ae=>{console.warn("[MissionManager] Failed to fetch mission interview drafts:",Ae)}),()=>{z=!0}},[h,r,Me]),i.useEffect(()=>{if(!h||!u)return;let z=!1;return Di(u).then(Ae=>{if(!(z||!Ae))try{const Ge=JSON.parse(Ae.inputPayload||"{}");Ge.targetId&&Ge.targetType&&dt({type:Ge.targetType,id:Ge.targetId,title:Ge.targetTitle||Ae.title,resumeSessionId:u})}catch{dt({type:"milestone",id:"",title:Ae.title,resumeSessionId:u})}}).catch(Ae=>{z||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",Ae),m?.())}),()=>{z=!0}},[h,u,m]);const[me,Ze]=i.useState(null),[be,gt]=i.useState(new Map),[$t,Ie]=i.useState(null),[ge,st]=i.useState({title:"",assertion:"",status:"pending"}),[yt,pt]=i.useState(!1),[vt,Ut]=i.useState(null),[Dt,nn]=i.useState(new Map),[on,sn]=i.useState(new Set),[ln,xn]=i.useState(new Set),[qt,Qt]=i.useState(null),[hn,Zt]=i.useState(new Map),[ve,Pe]=i.useState(null),[Ke,at]=i.useState(null),[We,It]=i.useState(!0),[Lt,Bt]=i.useState(new Set),[Gt,bt]=i.useState(new Map),[Ot,en]=i.useState(null),[Kt,Sn]=i.useState(new Map),[dn,Jt]=i.useState(null),[tn,Ne]=i.useState(new Map),[W,Y]=i.useState(new Map),[_e,ut]=i.useState("structure"),[At,zt]=i.useState([]),yn=i.useRef([]),Zn=i.useRef([]),vn=i.useRef(null),Dn=i.useRef(null),de=i.useRef("structure"),nt=i.useRef("all"),[ot,_t]=i.useState(!1),[G,Oe]=i.useState(0),[Mt,Xt]=i.useState("all"),[_n,Pn]=i.useState(new Set),kn=i.useRef(null),Vn=i.useRef(null);Zn.current=f,vn.current=g,Dn.current=ve,de.current=_e,nt.current=Mt;const $s=i.useCallback((z="auto")=>{const Ae=Vn.current;if(Ae&&typeof Ae.scrollIntoView=="function"){Ae.scrollIntoView({block:"end",behavior:z});return}const Ge=kn.current;Ge&&(Ge.scrollTop=Ge.scrollHeight)},[]),vs=i.useCallback(()=>{const z=kn.current;return z?z.scrollHeight-z.scrollTop-z.clientHeight<=100:!0},[]),As=i.useCallback(async z=>{if(z.length===0){Y(new Map);return}const Ae=await I1(r);Y(Ge=>{const kt=new Map(Ge);for(const[An,Vt]of Object.entries(Ae))n4(Vt)&&kt.set(An,Vt);return kt})},[r]),bn=i.useCallback(async()=>{try{b(!0);const z=await E1(r);p(z),As(z)}catch(z){a(Se(z)||"Failed to load missions","error")}finally{b(!1)}},[a,r,As]),Ht=i.useCallback(async z=>{try{S(!0);const Ae=await wb(z,r);if(!Ae||!Array.isArray(Ae.milestones)){S(!1);return}if(w(Ae),Ae.milestones.length>0){const Ge=Ae.milestones[0].id;Pe(Ge),It(!0),M(new Set([Ge])),Hc(Ge,r).then(kt=>{gt(An=>{const Vt=new Map(An);return Vt.set(Ge,kt),Vt})}).catch(()=>{}),qc(Ge,r).then(kt=>{Zt(An=>{const Vt=new Map(An);return Vt.set(Ge,kt),Vt})}).catch(()=>{}),Ae.milestones[0].slices.length>0&&$(new Set([Ae.milestones[0].slices[0].id]))}else Pe(null),at(null)}catch(Ae){a(Se(Ae)||"Failed to load mission details","error")}finally{S(!1)}},[a,r]);i.useEffect(()=>{if(!h||!ve){at(null);return}let z=!1;return at(null),lh(ve,r).then(Ae=>{if(!z){if(!Dd(Ae)){at(null);return}at(Ae),Zt(Ge=>{const kt=new Map(Ge);return kt.set(ve,Ae.rollup),kt})}}).catch(()=>{z||at(null)}),()=>{z=!0}},[h,ve,r]),i.useEffect(()=>{It(!0)},[ve]);const On=i.useCallback(z=>{!z||z!==Dn.current||lh(z,r).then(Ae=>{Dn.current!==z||!Dd(Ae)||(at(Ae),Zt(Ge=>{const kt=new Map(Ge);return kt.set(z,Ae.rollup),kt}))}).catch(()=>{})},[r]),Fn=i.useCallback(async(z,Ae)=>{const Ge=Ae?.append??!1,kt=Ge?yn.current.length:0;Ge||(_t(!0),Pn(new Set));try{const An=await R1(z,{limit:50,offset:kt,eventType:void 0},r),Vt=An.events.filter(Nn=>Rf(Nn.eventType,Mt));zt(Nn=>{if(!Ge)return yn.current=Vt,Vt;const Xe=new Set(Nn.map(Tt=>Tt.id)),lt=[...Nn];for(const Tt of Vt)Xe.has(Tt.id)||lt.push(Tt);return yn.current=lt,lt}),Oe(An.total),Ge||requestAnimationFrame(()=>{$s("auto")})}catch(An){a(Se(An)||"Failed to load mission activity","error")}finally{Ge||_t(!1)}},[a,Mt,r,$s]);i.useEffect(()=>{yn.current=At},[At]),i.useEffect(()=>{h&&(bn(),w(null),Pe(null),at(null),zt([]),Oe(0),ut("structure"),Xt("all"),Pn(new Set))},[h,bn]);const as=i.useRef(null);i.useEffect(()=>{h&&d&&as.current!==d&&f.length>0&&(as.current=d,Ht(d))},[h,d,f,Ht]),i.useEffect(()=>{h||(as.current=null)},[h]);const Wn=i.useRef(!1);i.useEffect(()=>{!h||!n||j||v||Wn.current||g||d||f.length!==0&&(Wn.current=!0,Ht(f[0].id))},[h,n,j,v,f,g,d,Ht]),i.useEffect(()=>{h||(Wn.current=!1)},[h]),i.useEffect(()=>{!h||!g||_e!=="activity"||Fn(g.id)},[_e,h,Fn,g,Mt]),i.useEffect(()=>{if(!h||typeof EventSource>"u")return;const z=new URLSearchParams;r&&z.set("projectId",r);const Ae=`/api/events${z.size>0?`?${z.toString()}`:""}`,Ge=()=>{As(Zn.current)},kt=us=>{Ge();const ts=us;if(ts.data)try{const un=JSON.parse(ts.data);un?.id&&p(ni=>ni.map(Gs=>Gs.id===un.id?{...Gs,...un}:Gs))}catch{}vn.current&&Ht(vn.current.id)},An=us=>{Ge(),vn.current&&Ht(vn.current.id)},Vt=()=>{Ge(),vn.current&&Ht(vn.current.id)},Nn=us=>{Ge(),vn.current&&Ht(vn.current.id)},Xe=us=>{const ts=us;if(ts.data)try{const un=JSON.parse(ts.data);un&&un.featureId&&(ci(un.featureId),wi(un.featureId),un.milestoneId&&On(un.milestoneId))}catch{}},lt=us=>{const ts=us;if(ts.data)try{const un=JSON.parse(ts.data);un&&un.featureId&&(ci(un.featureId),wi(un.featureId),un.milestoneId&&On(un.milestoneId),vn.current&&Ht(vn.current.id))}catch{}},Tt=us=>{const ts=us;if(ts.data)try{const un=JSON.parse(ts.data);un&&un.milestoneId&&(xs(un.milestoneId),On(un.milestoneId))}catch{}},Ln=us=>{const ts=us;if(ts.data)try{const un=JSON.parse(ts.data);un&&un.milestoneId&&(ds(un.milestoneId),xs(un.milestoneId),On(un.milestoneId))}catch{}};return yi(Ae,{events:{"mission:updated":kt,"slice:updated":An,"feature:updated":Vt,"milestone:updated":Nn,"mission:event":us=>{Ge();const ts=vn.current;if(!ts||de.current!=="activity")return;const un=vs(),ni=us;if(ni.data)try{const Gs=JSON.parse(ni.data);if(!s4(Gs)||Gs.missionId!==ts.id||!Rf(Gs.eventType,nt.current))return;zt(mi=>{const la=mi.filter(ee=>ee.id!==Gs.id);return[Gs,...la].slice(0,100)}),Oe(mi=>mi+1),un&&requestAnimationFrame(()=>{const mi=kn.current;mi&&(mi.scrollTop=0)})}catch{}},"validator-run:started":Xe,"validator-run:completed":lt,"milestone:validation:updated":Tt,"assertion:created":Ln,"assertion:updated":Ln,"assertion:deleted":Ln,"assertion:linked":Ln,"assertion:unlinked":Ln,"fix-feature:created":us=>{const ts=us;if(ts.data)try{const un=JSON.parse(ts.data);if(un&&un.sourceFeatureId){ci(un.sourceFeatureId);const ni=un?.feature?.sliceId,Gs=vn.current;if(ni&&Gs){const mi=Gs.milestones.find(la=>la.slices.some(ee=>ee.id===ni));mi&&On(mi.id)}vn.current&&Ht(vn.current.id)}}catch{}}}})},[h,vs,Ht,As,r,On]);const Rs=i.useCallback(z=>{A(z.id),K(!1),H({title:z.title,description:z.description||"",status:z.status,autopilotEnabled:z.autopilotEnabled??!1})},[]),In=i.useCallback(()=>{A(null),K(!1),H(Af)},[]),rs=i.useCallback(async()=>{if(!T.title.trim()){a("Mission title is required","error");return}try{if(se(!0),_)await _1({title:T.title.trim(),description:T.description.trim()||void 0,autopilotEnabled:T.autopilotEnabled},r),a("Mission created","success");else if(U){const z={title:T.title.trim(),description:T.description.trim()||void 0,status:T.status,autopilotEnabled:T.autopilotEnabled};T.autopilotEnabled&&(z.autoAdvance=!0),await M1(U,z,r),a("Mission updated","success"),g?.id===U&&await Ht(U)}await bn(),In()}catch(z){a(Se(z)||"Failed to save mission","error")}finally{se(!1)}},[T,_,U,a,bn,Ht,g,In,r]),Ns=i.useCallback(async z=>{try{await A1(z,r),a("Mission deleted","success"),g?.id===z&&w(null),await bn(),Ze(null)}catch(Ae){a(Se(Ae)||"Failed to delete mission","error")}},[a,bn,g,r]),ys=i.useCallback(()=>{ye(!0),X(null),ke(Td)},[]),cs=i.useCallback(z=>{X(z.id),ye(!1),ke({title:z.title,description:z.description||"",status:z.status,dependencies:z.dependencies})},[]),ss=i.useCallback(()=>{X(null),ye(!1),ke(Td)},[]),te=i.useCallback(async()=>{if(!le.title.trim()){a("Milestone title is required","error");return}try{se(!0),He&&g?(await T1(g.id,{title:le.title.trim(),description:le.description.trim()||void 0,dependencies:le.dependencies},r),a("Milestone created","success")):k&&(await P1(k,{title:le.title.trim(),description:le.description.trim()||void 0,status:le.status,dependencies:le.dependencies},r),a("Milestone updated","success")),await Ht(g.id),ss()}catch(z){a(Se(z)||"Failed to save milestone","error")}finally{se(!1)}},[le,He,k,g,a,Ht,ss,T.title,r]),we=i.useCallback(async z=>{try{await $1(z,r),a("Milestone deleted","success"),await Ht(g.id),Ze(null)}catch(Ae){a(Se(Ae)||"Failed to delete milestone","error")}},[a,Ht,g,r]),P=i.useCallback(z=>{Pe(z),It(!0),M(Ae=>{const Ge=new Set(Ae);return!Ge.has(z)?(Ge.add(z),Hc(z,r).then(An=>{gt(Vt=>{const Nn=new Map(Vt);return Nn.set(z,An),Nn})}).catch(()=>{}),qc(z,r).then(An=>{Zt(Vt=>{const Nn=new Map(Vt);return Nn.set(z,An),Nn})}).catch(()=>{})):Ge.delete(z),Ge})},[r]),Ce=i.useCallback(z=>{xe(z),q(!0),ne(null),Z(Pd)},[]),qe=i.useCallback(z=>{ne(z.id),q(!1),Z({title:z.title,description:z.description||"",status:z.status})},[]),et=i.useCallback(()=>{ne(null),q(!1),xe(null),Z(Pd)},[]),mt=i.useCallback(async()=>{if(!fe.title.trim()){a("Slice title is required","error");return}try{se(!0),re&&L?(await D1(L,{title:fe.title.trim(),description:fe.description.trim()||void 0},r),a("Slice created","success")):je&&(await L1(je,{title:fe.title.trim(),description:fe.description.trim()||void 0,status:fe.status},r),a("Slice updated","success")),await Ht(g.id),et()}catch(z){a(Se(z)||"Failed to save slice","error")}finally{se(!1)}},[fe,re,je,L,g,a,Ht,et,r]),Nt=i.useCallback(async z=>{try{await O1(z,r),a("Slice deleted","success"),await Ht(g.id),Ze(null)}catch(Ae){a(Se(Ae)||"Failed to delete slice","error")}},[a,Ht,g,r]),Pt=i.useCallback(async z=>{try{await F1(z,r),a("Slice activated","success"),await Ht(g.id)}catch(Ae){a(Se(Ae)||"Failed to activate slice","error")}},[a,Ht,g,r]),an=i.useCallback(z=>{$(Ae=>{const Ge=new Set(Ae);return Ge.has(z)?Ge.delete(z):Ge.add(z),Ge})},[]),Cn=i.useCallback(z=>{rt(z),Ve(!0),B(null),ze($d)},[]),ie=i.useCallback(z=>{B(z.id),Ve(!1),ze({title:z.title,description:z.description||"",acceptanceCriteria:z.acceptanceCriteria||"",status:z.status})},[]),$e=i.useCallback(()=>{B(null),Ve(!1),rt(null),ze($d)},[]),Qe=i.useCallback(async()=>{if(!pe.title.trim()){a("Feature title is required","error");return}try{se(!0),ae&&Te?(await z1(Te,{title:pe.title.trim(),description:pe.description.trim()||void 0,acceptanceCriteria:pe.acceptanceCriteria.trim()||void 0},r),a("Feature created","success")):he&&(await B1(he,{title:pe.title.trim(),description:pe.description.trim()||void 0,acceptanceCriteria:pe.acceptanceCriteria.trim()||void 0,status:pe.status},r),a("Feature updated","success")),await Ht(g.id),$e()}catch(z){a(Se(z)||"Failed to save feature","error")}finally{se(!1)}},[pe,ae,he,Te,g,a,Ht,$e,r]),Ft=i.useCallback(async z=>{try{await U1(z,r),a("Feature deleted","success"),await Ht(g.id),Ze(null)}catch(Ae){a(Se(Ae)||"Failed to delete feature","error")}},[a,Ht,g,r]),cn=i.useCallback(async()=>{if(!Be||!Re.trim()){a("Task ID is required","error");return}try{await H1(Be,Re.trim(),r),a("Feature linked to task","success"),await Ht(g.id),ce(null),Le("")}catch(z){a(Se(z)||"Failed to link feature to task","error")}},[Be,Re,a,Ht,g,r]),pn=i.useCallback(async z=>{try{await q1(z,r),a("Feature unlinked from task","success"),await Ht(g.id)}catch(Ae){a(Se(Ae)||"Failed to unlink feature","error")}},[a,Ht,g,r]),jn=i.useCallback(async z=>{try{se(!0),await V1(z,void 0,void 0,r),a("Feature triaged — task created","success"),await Ht(g.id)}catch(Ae){a(Se(Ae)||"Failed to triage feature","error")}finally{se(!1)}},[a,Ht,g,r]),Un=i.useCallback(async z=>{J(z);try{const Ae=await k0(z,r);St({featureId:z,enrichedDescription:Ae.description})}catch{await jn(z)}finally{J(null)}},[jn,r]),gs=i.useCallback(async()=>{wt&&(St(null),await jn(wt.featureId))},[jn,wt]),bs=i.useCallback(()=>{St(null)},[]),is=i.useCallback(async z=>{try{se(!0);const Ae=await W1(z,r);a(`Triaged ${Ae.count} feature${Ae.count!==1?"s":""}`,"success"),await Ht(g.id)}catch(Ae){a(Se(Ae)||"Failed to triage slice features","error")}finally{se(!1)}},[a,Ht,g,r]),ds=i.useCallback(async z=>{try{const Ae=await Hc(z,r);gt(Ge=>{const kt=new Map(Ge);return kt.set(z,Ae),kt})}catch{}},[r]),xs=i.useCallback(async z=>{try{const Ae=await qc(z,r);Zt(Ge=>{const kt=new Map(Ge);return kt.set(z,Ae),kt})}catch{}},[r]),ra=i.useCallback(async z=>{if(!ge.title.trim()||!ge.assertion.trim()){a("Title and assertion text are required","error");return}try{se(!0),await G1(z,{title:ge.title.trim(),assertion:ge.assertion.trim(),status:ge.status},r),a("Assertion created","success"),await ds(z),await xs(z),pt(!1),st({title:"",assertion:"",status:"pending"})}catch(Ae){a(Se(Ae)||"Failed to create assertion","error")}finally{se(!1)}},[ge,a,ds,xs,r]),Jn=i.useCallback(z=>{Ie(z.id),st({title:z.title,assertion:z.assertion,status:z.status})},[]),Ui=i.useCallback(()=>{Ie(null),pt(!1),st({title:"",assertion:"",status:"pending"})},[]),Hi=i.useCallback(async(z,Ae)=>{if(!ge.title.trim()||!ge.assertion.trim()){a("Title and assertion text are required","error");return}try{se(!0),await K1(z,{title:ge.title.trim(),assertion:ge.assertion.trim(),status:ge.status},r),a("Assertion updated","success"),await ds(Ae),await xs(Ae),Ui()}catch(Ge){a(Se(Ge)||"Failed to update assertion","error")}finally{se(!1)}},[ge,a,ds,xs,Ui,r]),Zs=i.useCallback(async z=>{try{const Ae=await Q1(z,r);nn(Ge=>{const kt=new Map(Ge);return kt.set(z,Ae),kt})}catch{}},[r]),ja=i.useCallback(async z=>{const Ae=vt!==z;Ut(Ge=>Ge===z?null:z),Ae&&await Zs(z)},[vt,Zs]),Na=i.useCallback(z=>{Ut(z),Zs(z),requestAnimationFrame(()=>{const Ae=document.querySelector(`[data-mission-assertion-id="${z}"]`);Ae instanceof HTMLElement&&typeof Ae.scrollIntoView=="function"&&Ae.scrollIntoView({behavior:"smooth",block:"center"})})},[Zs]),Ya=i.useCallback(async(z,Ae)=>{try{sn(Ge=>new Set(Ge).add(Ae)),await J1(z,Ae,r),a("Feature linked to assertion","success"),await Zs(Ae),Qt(null)}catch(Ge){a(Se(Ge)||"Failed to link feature","error")}finally{sn(Ge=>{const kt=new Set(Ge);return kt.delete(Ae),kt})}},[a,Zs,r]),Qa=i.useCallback(async(z,Ae)=>{const Ge=`${z}-${Ae}`;try{xn(kt=>new Set(kt).add(Ge)),await Y1(z,Ae,r),a("Feature unlinked from assertion","success"),await Zs(Ae)}catch(kt){a(Se(kt)||"Failed to unlink feature","error")}finally{xn(kt=>{const An=new Set(kt);return An.delete(Ge),An})}},[a,Zs,r]),Mn=i.useCallback(async z=>{try{Bt(Ge=>new Set(Ge).add(z)),await X1(z,r),a("Validation triggered","success");const Ae=await ch(z,r);bt(Ge=>{const kt=new Map(Ge);return kt.set(z,Ae),kt})}catch(Ae){a(Se(Ae)||"Failed to trigger validation","error")}finally{Bt(Ae=>{const Ge=new Set(Ae);return Ge.delete(z),Ge})}},[a,r]),ci=i.useCallback(async z=>{try{const Ae=await ch(z,r);bt(Ge=>{const kt=new Map(Ge);return kt.set(z,Ae),kt})}catch{}},[r]),wi=i.useCallback(async z=>{try{const Ae=await Z1(z,{limit:10},r);Sn(Ge=>{const kt=new Map(Ge);return kt.set(z,Ae),kt})}catch{}},[r]),Ai=i.useCallback(z=>{const Ae=vn.current;if(Ae){for(const Ge of Ae.milestones)for(const kt of Ge.slices)if(kt.features.find(Vt=>Vt.id===z)){M(Vt=>{const Nn=new Set(Vt);return Nn.add(Ge.id),Nn}),$(Vt=>{const Nn=new Set(Vt);return Nn.add(kt.id),Nn}),en(z),Pe(Ge.id),ci(z),wi(z),requestAnimationFrame(()=>{const Vt=document.querySelector(`[data-mission-feature-id="${z}"]`);Vt instanceof HTMLElement&&typeof Vt.scrollIntoView=="function"&&Vt.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[ci,wi]),Sa=i.useCallback(async z=>{try{const Ae=await e0(z,r);Ne(Ge=>{const kt=new Map(Ge);return kt.set(z,Ae),kt})}catch{}},[r]),Xa=i.useCallback(async z=>{Ot===z?en(null):(en(z),await ci(z),await wi(z))},[Ot,ci,wi]),Za=i.useCallback(async z=>{dn===z?Jt(null):(Jt(z),await Sa(z))},[dn,Sa]),Ca=i.useCallback(async z=>{try{await t0(z,r),a("Mission resumed","success"),await Ht(z),bn()}catch(Ae){a(Se(Ae)||"Failed to resume mission","error")}},[a,Ht,bn,r]),Ea=i.useCallback(async z=>{try{const Ge=(await n0(z,r)).pausedTaskIds?.length??0;a(`Mission stopped (${Ge} task${Ge!==1?"s":""} paused)`,"success"),await Ht(z),bn()}catch(Ae){a(Se(Ae)||"Failed to stop mission","error")}},[a,Ht,bn,r]),_a=i.useCallback(async z=>{try{await s0(z,r),a("Mission started — first slice activated","success"),await Ht(z),bn()}catch(Ae){a(Se(Ae)||"Failed to start mission","error")}},[a,Ht,bn,r]),er=i.useCallback(async(z,Ae)=>{try{await i0(z,{enabled:Ae},r),a(Ae?"Autopilot enabled":"Autopilot disabled","success"),await Ht(z),bn()}catch(Ge){a(Se(Ge)||"Failed to update autopilot","error")}},[a,Ht,bn,r]),Ma=i.useCallback(z=>{ut("structure"),Pe(null),at(null),zt([]),Oe(0),Xt("all"),Pn(new Set),Ht(z.id)},[Ht]),di=i.useCallback(()=>{w(null),Pe(null),at(null),ut("structure"),zt([]),Oe(0),Xt("all"),Pn(new Set),bn()},[bn]),ki=At.length<G,Ds=g?.autopilotState??"inactive",tr=Ds==="watching"||Ds==="activating",qi=r4(Ds,g?.lastAutopilotActivityAt),nr=i.useRef(g?.id??null);i.useEffect(()=>{const z=nr.current,Ae=g?.id??null;nr.current=Ae,!(!h||!j||!Ae||z===Ae)&&C({type:"view",revert:di})},[di,h,j,C,g?.id]);const ei=i.useMemo(()=>!Ke||!ve||!Dd(Ke)?null:Ke.rollup.milestoneId===ve?Ke:null,[ve,Ke]),Gr=i.useMemo(()=>{const z=new Map;for(const Ae of ei?.validationTelemetry.validationRounds??[]){const Ge=z.get(Ae.featureId);(!Ge||Ae.startedAt>Ge.startedAt)&&z.set(Ae.featureId,Ae)}return z},[ei]),Kr=i.useCallback(()=>{!g||ot||!ki||Fn(g.id,{append:!0})},[ot,ki,Fn,g]),Jr=i.useCallback(z=>{Pn(Ae=>{const Ge=new Set(Ae);return Ge.has(z)?Ge.delete(z):Ge.add(z),Ge})},[]),oa=i.useCallback(z=>{z.key==="Enter"&&!z.shiftKey&&(z.preventDefault(),rs())},[rs]),Vi=i.useCallback(z=>{z.key==="Enter"&&!z.shiftKey&&(z.preventDefault(),te())},[te]),sr=i.useCallback(z=>{z.key==="Enter"&&!z.shiftKey&&(z.preventDefault(),mt())},[mt]),ir=i.useCallback(z=>{z.key==="Enter"&&!z.shiftKey&&(z.preventDefault(),Qe())},[Qe]),Yr=i.useRef(null);if(i.useEffect(()=>{if(!h)return;const z=Ae=>{Ae.key==="Escape"&&s()};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[h,s]),!h)return null;const ar=()=>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:[tr&&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:(lo[g.status]||lo.planning).bg,color:(lo[g.status]||lo.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:z=>er(g.id,z.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(ls,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),t.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(Cl[Ds]||Cl.inactive).bg,color:(Cl[Ds]||Cl.inactive).text},"data-testid":"autopilot-state-badge",children:[tr&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),Ds]})]}),qi&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:qi})]}),t.jsxs("div",{className:"mission-detail__actions",children:[g.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ea(g.id),title:"Stop mission","aria-label":"Stop mission",children:t.jsx($i,{size:14})}),g.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Ca(g.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(os,{size:14})}),g.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>_a(g.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(os,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Rs(g),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(Hs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ze({type:"mission",id:g.id}),title:"Delete mission","aria-label":"Delete mission",children:t.jsx(Tn,{size:14})})]})]}),U===g.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:T.title,onChange:z=>H({...T,title:z.target.value}),onKeyDown:oa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:T.description,onChange:z=>H({...T,description:z.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:T.status,onChange:z=>H({...T,status:z.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:T.autopilotEnabled,onChange:z=>H({...T,autopilotEnabled:z.target.checked})}),t.jsx(ls,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:rs,disabled:Q,children:[Q?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ks,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:In,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[t.jsx("button",{className:`mission-btn ${_e==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>ut("structure"),role:"tab","aria-selected":_e==="structure","data-testid":"mission-tab-structure",children:"Structure"}),t.jsxs("button",{className:`mission-btn ${_e==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>ut("activity"),role:"tab","aria-selected":_e==="activity","data-testid":"mission-tab-activity",children:["Activity (",G,")"]})]}),_e==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[g.milestones.map(z=>{const Ae=ei?.rollup.milestoneId===z.id?ei:null,Ge=Ae?.rollup??hn.get(z.id),kt=Ae?.validationTelemetry.validationRounds??[],An=Ae?.fixFeatures??[],Vt=Ef[Ge?.state??"not_started"]??Ef.not_started,Nn=Ge&&(Ge.state==="blocked"||Ge.state==="failed")?Ae?.validationTelemetry.validationRounds.find(Xe=>Xe.blockedReason)?.blockedReason:void 0;return t.jsxs("div",{className:"mission-milestone",children:[t.jsxs("div",{className:"mission-milestone__header",onClick:()=>P(z.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:O.has(z.id)?t.jsx(gn,{size:16}):t.jsx(qn,{size:16})}),t.jsx(Fa,{size:16,className:"mission-milestone__icon"}),t.jsx("span",{className:"mission-milestone__title",children:z.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Sf[z.status].bg,color:Sf[z.status].text},children:z.status}),t.jsxs("span",{className:"mission-milestone__count",children:[z.slices.length," slices"]}),t.jsx(_f,{state:Z$(z.interviewState)}),Ge&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Vt.bg,color:Vt.text},title:"Validation state",children:Mf(Ge.state)}),Ge.totalAssertions>0&&t.jsx("div",{className:"mission-milestone__coverage-bar",title:`${Ge.passedAssertions??0} of ${Ge.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${(Ge.passedAssertions??0)/Ge.totalAssertions*100}%`,backgroundColor:(Ge.passedAssertions??0)===Ge.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),z.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>dt({type:"milestone",id:z.id,title:z.title}),title:"Plan milestone","aria-label":"Plan milestone",children:t.jsx(xa,{size:14})}),t.jsxs("div",{className:"mission-milestone__actions",onClick:Xe=>Xe.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ce(z.id),title:"Add slice",children:t.jsx($n,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>cs(z),title:"Edit milestone",children:t.jsx(Hs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ze({type:"milestone",id:z.id}),title:"Delete milestone",children:t.jsx(Tn,{size:14})})]})]}),O.has(z.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(He||k===z.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:le.title,onChange:Xe=>ke({...le,title:Xe.target.value}),onKeyDown:Vi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:le.description,onChange:Xe=>ke({...le,description:Xe.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:te,disabled:Q,children:[Q?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ks,{size:14}),k?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ss,children:"Cancel"})]})]}),Ae&&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:[Ae.validationTelemetry.totalRuns," rounds",Ae.validationTelemetry.lastValidatorStatus?` · Last ${Ae.validationTelemetry.lastValidatorStatus}`:""]})]}),Nn&&t.jsxs("div",{className:"mission-blocked-reason",children:[t.jsx("strong",{children:"Blocked reason:"})," ",Nn]}),kt.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:()=>It(Xe=>!Xe),title:We?"Hide validation rounds":"Show validation rounds",children:[We?t.jsx(gn,{size:12}):t.jsx(qn,{size:12}),"Validation rounds (",kt.length,")"]}),We&&t.jsx("div",{className:"mission-validation-rounds__list",children:kt.map(Xe=>t.jsxs("div",{className:"mission-validation-round",children:[t.jsxs("div",{className:"mission-validation-round__header",children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-validation-round__status mission-validation-round__status--${Xe.validatorStatus}`,children:Xe.validatorStatus}),t.jsx("span",{className:"mission-validation-round__feature",children:Xe.featureTitle}),t.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",Xe.implementationAttempt," · reviewer #",Xe.validatorAttempt]})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),Xe.failedAssertionIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Xe.failedAssertionIds.map(lt=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Na(lt),title:`Jump to assertion ${lt}`,children:lt},`${Xe.roundId}-${lt}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Generated fix features:"}),Xe.generatedFixFeatureIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Xe.generatedFixFeatureIds.map(lt=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Ai(lt),title:`Jump to fix feature ${lt}`,children:lt},`${Xe.roundId}-${lt}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),Xe.blockedReason&&t.jsx("div",{className:"mission-validation-round__blocked-reason",children:Xe.blockedReason})]},Xe.roundId))})]}),An.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:An.map(Xe=>t.jsxs("div",{className:"mission-fix-feature",children:[t.jsxs("div",{className:"mission-fix-feature__header",children:[t.jsx("button",{className:"mission-fix-feature__title",onClick:()=>Ai(Xe.id),title:`Jump to feature ${Xe.id}`,children:Xe.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Sl[Xe.status].bg,color:Sl[Xe.status].text},children:Xe.status}),Xe.loopState&&t.jsx("span",{className:`mission-loop-state mission-loop-state--${Xe.loopState}`,children:Xe.loopState})]}),t.jsxs("div",{className:"mission-fix-feature__meta",children:[t.jsx("span",{children:"Source:"}),t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Ai(Xe.sourceFeatureId),title:`Jump to source feature ${Xe.sourceFeatureId}`,children:Xe.sourceFeatureId}),t.jsx("span",{children:"Run:"}),t.jsx("span",{className:"mission-fix-feature__run",children:Xe.runId})]}),Xe.failedAssertionIds.length>0&&t.jsxs("div",{className:"mission-fix-feature__assertions",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),t.jsx("div",{className:"mission-validation-round__chip-list",children:Xe.failedAssertionIds.map(lt=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Na(lt),title:`Jump to assertion ${lt}`,children:lt},`${Xe.id}-${lt}`))})]})]},Xe.id))})]})]}),t.jsxs("div",{className:"mission-slices",children:[z.slices.map(Xe=>t.jsxs("div",{className:"mission-slice",children:[t.jsxs("div",{className:"mission-slice__header",onClick:()=>an(Xe.id),children:[t.jsx("button",{className:"mission-slice__expand",children:D.has(Xe.id)?t.jsx(gn,{size:16}):t.jsx(qn,{size:16})}),t.jsx(ru,{size:16,className:"mission-slice__icon"}),t.jsx("span",{className:"mission-slice__title",children:Xe.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Cf[Xe.status].bg,color:Cf[Xe.status].text},children:Xe.status}),t.jsxs("span",{className:"mission-slice__count",children:[Xe.features?.length||0," features"]}),t.jsx(_f,{state:Xe.planState??"not_started"}),Xe.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>dt({type:"slice",id:Xe.id,title:Xe.title}),title:"Plan slice","aria-label":"Plan slice",children:t.jsx(xa,{size:14})}),t.jsxs("div",{className:"mission-slice__actions",onClick:lt=>lt.stopPropagation(),children:[Xe.status==="pending"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Pt(Xe.id),title:"Activate slice",children:t.jsx(os,{size:14})}),Xe.status==="active"&&Xe.features?.some(lt=>lt.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>is(Xe.id),title:"Triage all features",disabled:Q,children:Q?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ls,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Cn(Xe.id),title:"Add feature",children:t.jsx($n,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>qe(Xe),title:"Edit slice",children:t.jsx(Hs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ze({type:"slice",id:Xe.id}),title:"Delete slice",children:t.jsx(Tn,{size:14})})]})]}),D.has(Xe.id)&&t.jsxs("div",{className:"mission-slice__body",children:[re&&L===z.id&&!je&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:fe.title,onChange:lt=>Z({...fe,title:lt.target.value}),onKeyDown:sr,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:fe.description,onChange:lt=>Z({...fe,description:lt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:mt,disabled:Q,children:[Q?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ks,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:et,children:"Cancel"})]})]}),je===Xe.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:fe.title,onChange:lt=>Z({...fe,title:lt.target.value}),onKeyDown:sr,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:fe.description,onChange:lt=>Z({...fe,description:lt.target.value}),rows:2}),t.jsxs("select",{value:fe.status,onChange:lt=>Z({...fe,status:lt.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:mt,disabled:Q,children:[Q?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ks,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:et,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-features",children:[Xe.features?.map(lt=>t.jsxs("div",{className:"mission-feature","data-mission-feature-id":lt.id,children:[t.jsxs("div",{className:"mission-feature__header",children:[t.jsx("button",{className:"mission-feature__expand",onClick:()=>Xa(lt.id),title:Ot===lt.id?"Collapse details":"Expand to show run history",children:Ot===lt.id?t.jsx(gn,{size:14}):t.jsx(qn,{size:14})}),t.jsx(eu,{size:14,className:"mission-feature__icon"}),t.jsx("span",{className:"mission-feature__title",children:lt.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Sl[lt.status].bg,color:Sl[lt.status].text},children:lt.status}),lt.loopState&<.loopState!=="idle"&&t.jsxs("span",{className:`mission-loop-state mission-loop-state--${lt.loopState}`,title:`Loop state: ${lt.loopState}`,children:[lt.loopState==="implementing"&&"⏳",lt.loopState==="validating"&&"🔄",lt.loopState==="needs_fix"&&"🔧",lt.loopState==="passed"&&"✅",lt.loopState==="blocked"&&"🚫"]}),lt.generatedFromFeatureId&&t.jsx("button",{className:"mission-feature__lineage",onClick:()=>Ai(lt.generatedFromFeatureId),title:`Generated from feature: ${lt.generatedFromFeatureId}`,children:"🔗 Fix"}),(lt.loopState==="validating"||lt.loopState==="needs_fix")&&(()=>{const Tt=Gt.get(lt.id),Ln=Gr.get(lt.id),ti=Tt?.implementationAttemptCount??Ln?.implementationAttempt??lt.implementationAttemptCount??0,ui=Tt?.retryBudgetRemaining??Math.max(0,J$-ti);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",ti," · ",ui," ",ui===1?"retry":"retries"," left"]})})(),lt.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>Mn(lt.id),title:"Validate feature",disabled:Lt.has(lt.id),children:Lt.has(lt.id)?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ms,{size:14})}),lt.taskId&&t.jsx("span",{className:"mission-feature__task-link",onClick:()=>o?.(lt.taskId),title:"Click to view task",children:lt.taskId}),t.jsxs("div",{className:"mission-feature__actions",children:[lt.status==="defined"&&!lt.taskId&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Un(lt.id),title:"Triage — create task",disabled:Q||Fe===lt.id,children:Fe===lt.id?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ls,{size:14})}),lt.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>pn(lt.id),title:"Unlink task",children:t.jsx(Lm,{size:14})}):lt.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>ce(lt.id),title:"Link to task",children:t.jsx(Sr,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>ie(lt),title:"Edit feature",children:t.jsx(Hs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ze({type:"feature",id:lt.id}),title:"Delete feature",children:t.jsx(Tn,{size:14})})]})]}),lt.description&&t.jsx("p",{className:"mission-feature__description",children:lt.description}),lt.acceptanceCriteria&&t.jsxs("p",{className:"mission-feature__criteria",children:[t.jsx("strong",{children:"Acceptance:"})," ",lt.acceptanceCriteria]}),wt?.featureId===lt.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:wt.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(jt,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:bs,disabled:Q,children:"Cancel"})]})]}),he===lt.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:pe.title,onChange:Tt=>ze({...pe,title:Tt.target.value}),onKeyDown:ir,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:pe.description,onChange:Tt=>ze({...pe,description:Tt.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:pe.acceptanceCriteria,onChange:Tt=>ze({...pe,acceptanceCriteria:Tt.target.value}),rows:2}),t.jsxs("select",{value:pe.status,onChange:Tt=>ze({...pe,status:Tt.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:Qe,disabled:Q,children:[Q?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ks,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:$e,children:"Cancel"})]})]}),Ot===lt.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"})}),(Kt.get(lt.id)??[]).map(Tt=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>Za(Tt.id),children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${Tt.status}`,title:Tt.status,children:Tt.status}),t.jsx("span",{className:"mission-run__time",children:new Date(Tt.startedAt).toLocaleString()}),Tt.completedAt&&t.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(Tt.completedAt).getTime()-new Date(Tt.startedAt).getTime())/1e3),"s"]}),Tt.triggerType&&t.jsx("span",{className:"mission-run__trigger",children:Tt.triggerType}),t.jsx("button",{className:"mission-icon-btn",title:dn===Tt.id?"Hide details":"Show details",children:dn===Tt.id?t.jsx(gn,{size:12}):t.jsx(qn,{size:12})})]}),dn===Tt.id&&tn.get(Tt.id)&&t.jsxs("div",{className:"mission-run__details",children:[Tt.summary&&t.jsx("p",{className:"mission-run__summary",children:Tt.summary}),Tt.blockedReason&&t.jsxs("p",{className:"mission-run__blocked-reason",children:[t.jsx("strong",{children:"Blocked:"})," ",Tt.blockedReason]}),tn.get(Tt.id)?.failures&&tn.get(Tt.id).failures.length>0&&t.jsxs("div",{className:"mission-run__failures",children:[t.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),tn.get(Tt.id).failures.map(Ln=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:Ln.message}),Ln.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",Ln.expected]}),Ln.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",Ln.actual]})]},Ln.id))]}),(!tn.get(Tt.id)?.failures||tn.get(Tt.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},Tt.id)),(!Kt.get(lt.id)||Kt.get(lt.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},lt.id)),ae&&Te===Xe.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:pe.title,onChange:lt=>ze({...pe,title:lt.target.value}),onKeyDown:ir,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:pe.description,onChange:lt=>ze({...pe,description:lt.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:pe.acceptanceCriteria,onChange:lt=>ze({...pe,acceptanceCriteria:lt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Qe,disabled:Q,children:[Q?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ks,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:$e,children:"Cancel"})]})]}),!ae&&(!Xe.features||Xe.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(eu,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},Xe.id)),z.slices.length===0&&!re&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(ru,{size:16}),t.jsx("span",{children:"No slices yet"})]}),t.jsxs("div",{className:"mission-assertions",children:[t.jsxs("div",{className:"mission-assertions__header",children:[t.jsx("span",{className:"mission-assertions__title",children:"Assertions"}),Ge&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Vt.bg,color:Vt.text},children:Mf(Ge.state)}),Ge&&Ge.totalAssertions>0&&t.jsx("div",{className:"mission-assertions__coverage-bar",title:`${Ge.passedAssertions??0} of ${Ge.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${(Ge.passedAssertions??0)/Ge.totalAssertions*100}%`,backgroundColor:(Ge.passedAssertions??0)===Ge.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>{pt(!0),Ie(null),st({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx($n,{size:14})})]}),yt&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:ge.title,onChange:Xe=>st({...ge,title:Xe.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:ge.assertion,onChange:Xe=>st({...ge,assertion:Xe.target.value}),rows:2}),t.jsxs("select",{value:ge.status,onChange:Xe=>st({...ge,status:Xe.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"passed",children:"Passed"}),t.jsx("option",{value:"failed",children:"Failed"}),t.jsx("option",{value:"blocked",children:"Blocked"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:()=>ra(z.id),disabled:Q,children:[Q?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ks,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ui,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(be.get(z.id))?be.get(z.id):[]).map(Xe=>t.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":Xe.id,children:[t.jsx("div",{className:"mission-assertion__header",children:$t===Xe.id?t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:ge.title,onChange:lt=>st({...ge,title:lt.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:ge.assertion,onChange:lt=>st({...ge,assertion:lt.target.value}),rows:2}),t.jsxs("select",{value:ge.status,onChange:lt=>st({...ge,status:lt.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:()=>Hi(Xe.id,z.id),disabled:Q,children:[Q?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ks,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ui,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(El[Xe.status]??El.pending).bg,color:(El[Xe.status]??El.pending).text},children:Xe.status}),t.jsx("span",{className:"mission-assertion__title",children:Xe.title}),(()=>{const Tt=Dt.get(Xe.id)?.length??0;return Tt>0?t.jsxs("span",{className:"mission-assertion__linked-count",title:`${Tt} linked feature${Tt!==1?"s":""}`,children:["(",Tt," linked)"]}):null})(),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ja(Xe.id),title:"Toggle details",children:vt===Xe.id?t.jsx(gn,{size:14}):t.jsx(qn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Jn(Xe),title:"Edit assertion",children:t.jsx(Hs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ze({type:"assertion",id:Xe.id}),title:"Delete assertion",children:t.jsx(Tn,{size:14})})]})}),vt===Xe.id&&t.jsxs("div",{className:"mission-assertion__body",children:[t.jsx("p",{className:"mission-assertion__text",children:Xe.assertion}),t.jsxs("div",{className:"mission-assertion__linked-features",children:[t.jsxs("div",{className:"mission-assertion__linked-features-header",children:[t.jsx("span",{className:"mission-assertion__linked-features-label",children:"Linked Features"}),t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:async()=>{vt!==Xe.id&&await ja(Xe.id),Qt(qt===Xe.id?null:Xe.id)},title:"Link a feature",children:[t.jsx(Sr,{size:12}),"Link Feature"]})]}),qt===Xe.id&&t.jsx("div",{className:"mission-assertion__feature-picker",children:t.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const lt=new Set((Dt.get(Xe.id)??[]).map(Ln=>Ln.id)),Tt=[];return g?.milestones.forEach(Ln=>Ln.slices.forEach(ti=>Tt.push(...ti.features.filter(ui=>!lt.has(ui.id))))),Tt.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):Tt.map(Ln=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>Ya(Ln.id,Xe.id),disabled:on.has(Xe.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:Ln.title}),on.has(Xe.id)&&t.jsx(jt,{size:12,className:"spinner"})]},Ln.id))})()})}),(()=>{const lt=Dt.get(Xe.id)??[];return lt.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):lt.map(Tt=>{const Ln=`${Tt.id}-${Xe.id}`,ti=ln.has(Ln);return t.jsxs("div",{className:"mission-assertion__linked-feature",children:[t.jsx("span",{className:"mission-assertion__linked-feature-title",children:Tt.title}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Qa(Tt.id,Xe.id),disabled:ti,title:"Unlink feature",children:ti?t.jsx(jt,{size:12,className:"spinner"}):t.jsx(Lm,{size:12})})]},Tt.id)})})()]})]})]},Xe.id)),(!be.get(z.id)||be.get(z.id)?.length===0)&&!yt&&t.jsx("div",{className:"mission-manager__empty mission-assertions__empty",children:t.jsx("span",{children:"No assertions defined. Add one to define completion criteria."})})]})]})]})]})]},z.id)}),g&&!He&&k===null&&t.jsxs("button",{className:"mission-add-btn",onClick:ys,children:[t.jsx($n,{size:16}),"Add Milestone"]}),He&&k===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:le.title,onChange:z=>ke({...le,title:z.target.value}),onKeyDown:Vi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:le.description,onChange:z=>ke({...le,description:z.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:te,disabled:Q,children:[Q?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ks,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ss,children:"Cancel"})]})]}),g.milestones.length===0&&!He&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Fa,{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:Mt,onChange:z=>Xt(z.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:[At.length," of ",G]})]}),!ot&&ki&&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:Kr,"data-testid":"mission-activity-load-more",children:"Load more"})}),ot?t.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[t.jsx(jt,{size:18,className:"spinner"}),t.jsx("span",{children:"Loading mission activity..."})]}):At.length===0?t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Js,{size:18}),t.jsx("span",{children:"No events yet."})]}):t.jsxs("div",{ref:kn,className:"mission-events","data-testid":"mission-activity-events",children:[At.map(z=>{const Ae=!!(z.metadata&&Object.keys(z.metadata).length>0),Ge=_n.has(z.id);return t.jsxs("div",{className:"mission-event",children:[t.jsxs("div",{className:"mission-event__header",children:[t.jsx("span",{className:`mission-event__type ${i4(z.eventType)}`,children:a4(z.eventType)}),t.jsx("span",{className:"mission-event__time",children:rc(z.timestamp)})]}),t.jsx("p",{className:"mission-event__description",children:z.description}),t.jsx("span",{className:"mission-event__timestamp",children:new Date(z.timestamp).toLocaleString()}),Ae&&t.jsxs("div",{className:"mission-event__metadata",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>Jr(z.id),"data-testid":`mission-event-metadata-${z.id}`,children:[Ge?"Hide":"Show"," metadata"]}),Ge&&t.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(z.metadata,null,2)})]})]},z.id)}),t.jsx("div",{ref:Vn})]})]})]}):null,Aa=z=>{tt(z),Ue(!0)},Wi=()=>{xt.current=Me??null,tt(void 0),Ue(!1)},Je=async z=>{try{await c0(z,r),ft(Ae=>Ae.filter(Ge=>Ge.id!==z))}catch(Ae){if(Ae instanceof Kl&&Ae.status===409){a("Draft is open in another tab","error");return}if(Ae instanceof Kl&&Ae.status===404){ft(Ge=>Ge.filter(kt=>kt.id!==z));return}a(Se(Ae)||"Failed to discard draft","error");return}finally{Ze(null)}},Rt=()=>Ee.map(z=>{const Ae=z.status==="error",Ge=z.status==="generating",kt=X$(z.status);return t.jsxs("div",{className:"mission-list__item mission-list__item--interview",onClick:()=>Aa(z.id),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(ms,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:z.title||"Mission interview"})]}),t.jsx("div",{className:"mission-list__item-tags",children:t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-interview-status mission-interview-status--${z.status}`,children:Q$(z.status)})}),t.jsx("p",{className:"mission-list__item-description",children:Ge?"Generating mission hierarchy from interview context.":Ae?"Interview hit an error. Retry from this list item.":"Interview is waiting for your next response."})]}),t.jsxs("div",{className:"mission-list__item-actions mission-list__resume-actions",onClick:An=>An.stopPropagation(),children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>Aa(z.id),title:kt,"aria-label":kt,children:[Ge?t.jsx(jt,{size:14,className:"spinner"}):Ae?t.jsx(ps,{size:14}):t.jsx(ms,{size:14}),t.jsx("span",{children:Ae?"Retry":"Resume"})]}),t.jsxs("button",{className:"mission-btn mission-btn--danger mission-btn--sm",onClick:()=>Ze({type:"interview_draft",id:z.id}),title:"Discard draft","aria-label":"Discard draft",children:[t.jsx(Tn,{size:14}),t.jsx("span",{children:"Discard"})]})]})]},z.id)}),rn=(z,Ae)=>z.map(Ge=>{const kt=Ge,An=g?.id===kt.id,Vt=lo[kt.status]||{bg:"",text:""},Nn=kt.summary,Xe=W.get(kt.id),lt=t4(Xe),Tt=!!(Nn&&(Nn.totalMilestones>0||Nn.totalFeatures>0)),Ln=Xe?.totalTasks??0,ti=Xe?.tasksCompleted??0,ui=Xe?.tasksFailed??0,us=Xe?.estimatedCompletionPercent??Nn?.progressPercent??0,ts=Tt||Ln>0||ui>0||!!Xe?.lastActivityAt,un=Ae?.interviewStyle===!0;return t.jsxs("div",{className:`mission-list__item ${An?"mission-list__item--selected":""} ${un?"mission-list__item--interview":""}`,onClick:()=>Ma(Ge),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(Es,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:kt.title})]}),t.jsxs("div",{className:"mission-list__item-tags",children:[Ge.autopilotEnabled&&t.jsx("span",{title:"Autopilot enabled",children:t.jsx(ls,{size:12,className:"mission-list__item-autopilot-icon"})}),t.jsx("span",{className:`mission-health-badge mission-health-badge--${lt}`,"data-testid":`mission-health-badge-${kt.id}`,"aria-label":`Mission health: ${lt}`}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Vt.bg,color:Vt.text},children:kt.status}),un&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm mission-interview-status mission-interview-status--awaiting_input",children:"Interview in progress"})]}),un?t.jsx("p",{className:"mission-list__item-description",children:"Mission interview is still in progress. Open this mission to continue planning."}):kt.description?t.jsx("p",{className:"mission-list__item-description",children:kt.description}):null,ts&&t.jsxs("div",{className:"mission-list__item-summary",children:[Tt&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[Nn.completedMilestones,"/",Nn.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[Nn.completedFeatures,"/",Nn.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${kt.id}`,children:[ti,"/",Ln," tasks"]}),ui>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:ni=>{ni.stopPropagation(),Ma(Ge)},"data-testid":`mission-failed-${kt.id}`,title:"View mission failures",children:[ui," failed"]}),t.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${lt}`,children:t.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${us}%`}})})]}),ts&&t.jsx("div",{className:"mission-list__item-activity",children:t.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${kt.id}`,children:["Activity ",rc(Xe?.lastActivityAt)]})})]}),t.jsxs("div",{className:"mission-list__item-actions",onClick:ni=>ni.stopPropagation(),children:[kt.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ea(kt.id),title:"Stop mission",children:t.jsx($i,{size:14})}),kt.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Ca(kt.id),title:"Resume mission",children:t.jsx(os,{size:14})}),kt.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>_a(kt.id),title:"Start mission",children:t.jsx(os,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Rs(Ge),title:"Edit mission",children:t.jsx(Hs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ze({type:"mission",id:kt.id}),title:"Delete mission",children:t.jsx(Tn,{size:14})})]})]},kt.id)}),es=({hideBottomButtons:z=!1}={})=>{const Ae=f.filter(Vt=>Vt.interviewState==="in_progress"),Ge=f.filter(Vt=>Vt.interviewState!=="in_progress"),kt=j&&f.length>0&&!_,An=!z&&!kt;return t.jsxs("div",{className:"mission-list",children:[_&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:T.title,onChange:Vt=>H({...T,title:Vt.target.value}),onKeyDown:oa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:T.description,onChange:Vt=>H({...T,description:Vt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:rs,disabled:Q,children:[Q?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ks,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:In,children:"Cancel"})]})]}),kt&&t.jsx("div",{className:"mission-list__top-action",children:t.jsxs("button",{className:"btn btn-sm btn-task-create mission-list__primary-cta",onClick:()=>Ue(!0),children:[t.jsx(ms,{size:14}),"Plan New Mission"]})}),rn(Ae,{interviewStyle:!0}),rn(Ge),Ee.length>0&&t.jsxs("div",{className:"mission-list__drafts-group",children:[t.jsxs("div",{className:"mission-list__drafts-header",children:[t.jsx(ms,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{children:"Drafts"}),t.jsxs("span",{children:["(",Ee.length,")"]})]}),Rt()]}),U&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:T.title,onChange:Vt=>H({...T,title:Vt.target.value}),onKeyDown:oa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:T.description,onChange:Vt=>H({...T,description:Vt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:T.status,onChange:Vt=>H({...T,status:Vt.target.value}),children:[t.jsx("option",{value:"planning",children:"Planning"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"blocked",children:"Blocked"}),t.jsx("option",{value:"complete",children:"Complete"}),t.jsx("option",{value:"archived",children:"Archived"})]}),t.jsxs("label",{className:"mission-checkbox",children:[t.jsx("input",{type:"checkbox",checked:T.autopilotEnabled,onChange:Vt=>H({...T,autopilotEnabled:Vt.target.checked})}),t.jsx(ls,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:rs,disabled:Q,children:[Q?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ks,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:In,children:"Cancel"})]})]}),f.length===0&&Ee.length===0&&!_&&t.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large mission-manager__empty--mission",children:[t.jsx(Es,{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:()=>Ue(!0),children:[t.jsx(ms,{size:14}),"Plan New Mission"]})]}),!_&&t.jsx("div",{className:"mission-list__footer",children:An&&t.jsx("div",{className:"mission-list__footer-actions",children:t.jsxs("button",{className:"mission-add-btn",onClick:()=>Ue(!0),children:[t.jsx(ms,{size:16}),"Plan New Mission"]})})})]})},Hn=()=>{const z=me?.type==="interview_draft";return t.jsx("div",{className:"mission-confirm-panel mission-confirm-panel--danger",children:t.jsxs("div",{className:"mission-confirm-panel__content",children:[t.jsx("p",{children:z?"Discard this interview draft? This removes the saved draft and cannot be undone.":`Delete this ${me?.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()=>{me&&(me.type==="mission"?await Ns(me.id):me.type==="milestone"?await we(me.id):me.type==="slice"?await Nt(me.id):me.type==="feature"?await Ft(me.id):me.type==="interview_draft"&&await Je(me.id))},children:z?"Discard":"Delete"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>Ze(null),children:"Cancel"})]})]})})},Bs=()=>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:Re,onChange:z=>Le(z.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(z=>t.jsxs("button",{className:"mission-task-suggestions__item",onClick:()=>Le(z.id),children:[z.id,": ",z.title||"Untitled"]},z.id))})]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--primary",onClick:cn,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{ce(null),Le("")},children:"Cancel"})]})]})}),rr=t.jsxs("div",{ref:Yr,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:di,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(pc,{size:18})}),t.jsx(Es,{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(mn,{size:18})})]}),j?t.jsxs("div",{className:"mission-manager__body mission-manager__body--stacked",children:[v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(jt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(jt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?ar():es(),me&&Hn(),Be&&Bs()]}):t.jsxs("div",{className:"mission-manager__split",children:[t.jsxs("aside",{className:"mission-manager__sidebar","data-testid":"mission-sidebar","aria-label":"Mission list",style:j?void 0:{width:`${x}px`},children:[t.jsx("div",{className:"mission-manager__sidebar-list",children:v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(jt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):es({hideBottomButtons:!0})}),t.jsx("div",{className:"mission-manager__sidebar-footer","data-testid":"mission-sidebar-footer",children:t.jsxs("button",{className:"btn btn-primary mission-manager__sidebar-cta",onClick:()=>Ue(!0),title:"Plan New Mission","aria-label":"Plan New Mission",children:[t.jsx(ms,{size:14}),"Plan New Mission"]})})]}),!j&&t.jsx("div",{className:"mission-manager__sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":jl,"aria-valuemax":Nl,"aria-valuenow":x,"aria-label":"Resize mission sidebar",tabIndex:0,onPointerDown:F,onKeyDown:E}),t.jsxs("div",{className:"mission-manager__detail-pane",children:[y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(jt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?ar():t.jsxs("div",{className:"mission-manager__detail-pane-empty","data-testid":"mission-empty-detail",children:[t.jsx(Es,{size:32}),t.jsx("span",{children:"Select a mission to view details"})]}),me&&Hn(),Be&&Bs()]})]})]}),Qr=t.jsx(L$,{isOpen:ct,onClose:Wi,onMissionCreated:()=>{bn(),a("Mission created from AI interview","success")},projectId:r,resumeSessionId:Me}),Pc=Ye?t.jsx(W$,{isOpen:!0,onClose:()=>dt(null),onApplied:()=>{dt(null),g&&Ht(g.id)},targetType:Ye.type,targetId:Ye.id,targetTitle:Ye.title,missionContext:g?.title,projectId:r,resumeSessionId:Ye.resumeSessionId}):null;return n?t.jsxs(t.Fragment,{children:[rr,Qr,Pc]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mission-manager-overlay open",onClick:z=>z.target===z.currentTarget&&s(),"data-testid":"mission-manager-overlay",role:"dialog","aria-modal":"true",children:rr}),Qr,Pc]})}const l4={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})},If=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(xi,{remarkPlugins:[vi],components:l4,children:n})})}),_l=2e3;function Tf({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,w]=i.useState(!1),[v,b]=i.useState(!1),[y,S]=i.useState(null),j=i.useRef(null),C=i.useMemo(()=>s.find(U=>U.id===d),[s,d]),x=i.useMemo(()=>e?s.find(U=>U.id===e.id):void 0,[s,e]),N=m==="agent",R=N&&C?.runtimeConfig?.messageResponseMode==="immediate",F=N&&(g||R),E=d.trim()!==""&&f.trim().length>0&&f.length<=_l,_=i.useCallback(async()=>{if(!(!E||v)){b(!0),S(null);try{const U=m==="agent"?"user-to-agent":"system",A=n?{replyTo:{messageId:n.messageId}}:void 0,T=F;await T0({toId:d.trim(),toType:m,content:f.trim(),type:U,...A?{metadata:A}:{},...T?{wakeImmediately:!0}:{}},a),r()}catch(U){const A=Se(U)||"Failed to send message";S(A),l?.(A,"error")}finally{b(!1)}}},[E,v,d,m,f,F,n,a,r,l]),K=i.useCallback(U=>{u(U),h("agent")},[]);return i.useEffect(()=>{n&&j.current?.focus()},[n]),i.useEffect(()=>{if(!n||typeof window>"u"||window.visualViewport==null)return;const U=()=>{j.current?.scrollIntoView({block:"center",behavior:"auto"})};return window.visualViewport.addEventListener("resize",U),()=>{window.visualViewport?.removeEventListener("resize",U)}},[n]),t.jsxs("div",{className:"message-composer","data-testid":"message-composer",children:[t.jsxs("div",{className:"message-composer-header",children:[t.jsx("span",{children:n?"Reply":"New Message"}),t.jsx("button",{className:"btn-icon",onClick:o,"aria-label":"Cancel","data-testid":"message-composer-cancel",children:t.jsx(mn,{size:16})})]}),t.jsxs("div",{className:"message-composer-body",children:[!e&&t.jsxs("div",{className:"message-composer-field",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-recipient",children:"To:"}),t.jsxs("select",{id:"message-recipient",className:"message-composer-select",value:d,onChange:U=>K(U.target.value),disabled:c||s.length===0,"data-testid":"message-composer-recipient",children:[t.jsx("option",{value:"",children:c?"Loading agents…":s.length===0?"No agents available":"Select agent…"}),s.map(U=>t.jsx("option",{value:U.id,children:U.name||U.id},U.id))]})]}),e&&t.jsxs("div",{className:"message-composer-field",children:[t.jsx("span",{className:"message-composer-label",children:"To:"}),t.jsxs("span",{className:"message-composer-recipient-fixed",children:[t.jsx(Qn,{size:14}),x?.name||e.id]})]}),n&&t.jsxs("div",{className:"message-composer-field","data-testid":"message-composer-reply-context",children:[t.jsx("span",{className:"message-composer-label",children:"Replying to:"}),t.jsx("span",{className:"message-composer-recipient-fixed",children:n.preview?.trim()?n.preview:`Message ${n.messageId}`})]}),t.jsxs("div",{className:"message-composer-field message-composer-field--content",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-content",children:"Message:"}),t.jsx("textarea",{id:"message-content",ref:j,className:"message-composer-textarea",placeholder:"Type your message…",value:f,onChange:U=>p(U.target.value),maxLength:_l,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>_l?"over-limit":"",children:[f.length,"/",_l]})})]}),N&&t.jsx("div",{className:"message-composer-field message-composer-field--wake",children:t.jsxs("label",{className:"message-composer-wake-label",children:[t.jsx("input",{type:"checkbox",checked:F,disabled:R,onChange:U=>w(U.target.checked),"data-testid":"message-composer-wake"}),t.jsxs("span",{children:["Wake agent immediately",t.jsx("span",{className:"message-composer-wake-hint","data-testid":"message-composer-wake-hint",children:R?"(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(Vs,{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:_,disabled:!E||v,"data-testid":"message-composer-send",children:v?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:14,className:"spin"}),t.jsx("span",{children:"Sending…"})]}):t.jsxs(t.Fragment,{children:[t.jsx(Da,{size:14}),t.jsx("span",{children:"Send"})]})})]})]})}const Ts="__all_agents__",oc=280,Au=.65,Ld=16,Pf=320;function Ru(e){return Math.max(oc,e*Au)}function Od(e,n){const s=Ru(n);return Math.min(Math.max(e,oc),s)}function $f(e){try{const n=Gn("kb-dashboard-mailbox-sidebar-width",e);if(!n)return Pf;const s=Number(n);if(Number.isFinite(s)&&s>0)return s}catch{}return Pf}function Yi(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 c4(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 d4(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 Df(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function Lf(){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 co(e){return`mailbox-list-message-${e}`}function Fd(e){return`mailbox-detail-message-${e}`}function u4(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 m4({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),[w,v]=i.useState([]),[b,y]=i.useState(!1),[S,j]=i.useState(null),[C,x]=i.useState(null),[N,R]=i.useState(Ts),[F,E]=i.useState("inbox"),[_,K]=i.useState(null),[U,A]=i.useState(null),[T,H]=i.useState([]),[Q,se]=i.useState("pending"),[O,M]=i.useState([]),[D,$]=i.useState(0),[k,X]=i.useState(null),[le,ke]=i.useState(""),[He,ye]=i.useState(!1),je=i.useMemo(()=>new Map(T.map(J=>[J.id,J.name??""])),[T]),ne=i.useCallback((J,me)=>c4(J,me,je),[je]),Z=oi()==="mobile",re=!Z,[q,L]=i.useState(()=>$f(e)),xe=i.useRef(null),{keyboardOverlap:he,viewportHeight:B,viewportOffsetTop:pe,keyboardOpen:ze}=aa({enabled:Z}),ae=i.useMemo(()=>{if(ze)return{"--keyboard-overlap":`${he}px`,"--vv-offset-top":`${pe}px`,...B!=null?{"--vv-height":`${B}px`}:{}}},[ze,he,B,pe]);i.useEffect(()=>{L($f(e))},[e]),i.useEffect(()=>{if(!re)return;const J=xe.current?.clientWidth;J&&L(me=>Od(me,J))},[re]),i.useEffect(()=>{if(re)try{fs("kb-dashboard-mailbox-sidebar-width",String(q),e)}catch{}},[re,e,q]);const Ve=i.useCallback(J=>{if(!re)return;J.preventDefault();const me=xe.current;if(!me)return;const Ze=me.getBoundingClientRect(),be=$t=>{const Ie=$t.clientX-Ze.left;L(Od(Ie,Ze.width))},gt=()=>{window.removeEventListener("mousemove",be),window.removeEventListener("mouseup",gt)};window.addEventListener("mousemove",be),window.addEventListener("mouseup",gt)},[re]),Te=i.useCallback(J=>{if(!re)return;const me=xe.current?.clientWidth??0,Ze=q/Au+Ld,be=Math.max(me,Ze),gt=Ru(be);if(J.key==="ArrowLeft"||J.key==="ArrowRight"){J.preventDefault();const $t=J.key==="ArrowLeft"?-Ld:Ld;L(Ie=>Od(Ie+$t,be));return}if(J.key==="Home"){J.preventDefault(),L(oc);return}J.key==="End"&&(J.preventDefault(),L(gt))},[re,q]),rt=i.useCallback(async()=>{f(!0);try{const J=await R0({limit:50},e);l(J),m(J.unreadCount),s?.(J.unreadCount)}catch{}finally{f(!1)}},[e,s]),Be=i.useCallback(async()=>{f(!0);try{const J=await I0({limit:50},e);d(J)}catch{}finally{f(!1)}},[e]),ce=i.useCallback(async J=>{f(!0);try{const me=await O0(J,e);K(me)}catch{}finally{f(!1)}},[e]),Re=i.useCallback(async()=>{f(!0);try{const J=await F0(e);A(J)}catch{}finally{f(!1)}},[e]),Le=i.useCallback(async()=>{try{const J=await Ur(void 0,e);H(J)}catch{}},[e]),ct=i.useCallback(async()=>{try{const J=await Nb(e);m(J.unreadCount),s?.(J.unreadCount)}catch{}},[e,s]),Ue=i.useCallback(async J=>{f(!0);try{const me=await ol({status:J==="pending"?"pending":void 0,limit:100},e);if(J==="pending")M(me.requests);else{const[Ze,be,gt]=await Promise.all([ol({status:"approved",limit:100},e),ol({status:"denied",limit:100},e),ol({status:"completed",limit:100},e)]);M([...Ze.requests,...be.requests,...gt.requests].sort(($t,Ie)=>Ie.updatedAt.localeCompare($t.updatedAt)))}$(me.pendingCount)}catch{}finally{f(!1)}},[e]);i.useEffect(()=>{a==="inbox"?rt():a==="outbox"?Be():a==="agents"?Le():a==="approvals"&&Ue(Q)},[a,rt,Be,Le,Ue,Q]),i.useEffect(()=>{if(N===Ts){Re();return}ce(N)},[N,ce,Re]),i.useEffect(()=>{ct()},[ct]),i.useEffect(()=>{Le()},[Le]),i.useEffect(()=>{if(typeof EventSource>"u")return;const J=e?`?projectId=${encodeURIComponent(e)}`:"",me=()=>{ct(),a==="inbox"?rt():a==="outbox"?Be():a==="approvals"&&Ue(Q),N===Ts?Re():N&&ce(N)};return yi(`/api/events${J}`,{events:{"message:sent":me,"message:received":me,"message:read":me,"message:deleted":me,"approval:requested":me,"approval:updated":me,"approval:decided":me}})},[e,a,N,ct,rt,Be,ce,Re,Ue,Q]);const ue=i.useCallback(async J=>{if(g(J),!J.read&&a==="inbox")try{const me=await P0(J.id,e);me&&l(be=>be&&{...be,messages:be.messages.map(gt=>gt.id===me.id?me:gt),unreadCount:Math.max(0,be.unreadCount-1)});const Ze=Math.max(0,u-1);m(Ze),s?.(Ze)}catch{}try{const me=await L0(J.fromId,J.fromType,e);v(me)}catch{v([J])}},[e,u,s,a]);i.useEffect(()=>{const J=Lf();if(!J)return;const me=[...o?.messages??[],...c?.messages??[],..._?.inbox??[],..._?.outbox??[],...U?.messages??[],...w].find(Ze=>Ze.id===J);me&&ue(me)},[o,c,_,U,w,ue]),i.useEffect(()=>{const J=Lf();if(!J)return;const me=document.getElementById(Fd(J));if(!me)return;me.scrollIntoView({behavior:"smooth",block:"center"}),me.classList.add("mailbox-message-highlight");const Ze=window.setTimeout(()=>{me.classList.remove("mailbox-message-highlight")},2e3);return()=>{window.clearTimeout(Ze)}},[p,w]);const oe=i.useCallback(()=>{g(null),v([])},[]),Ee=i.useCallback(async()=>{try{const J=await $0(e);m(0),s?.(0),l(me=>me&&{...me,messages:me.messages.map(Ze=>({...Ze,read:!0})),unreadCount:0}),n?.(`Marked ${J.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[e,n,s]),ft=i.useCallback(async J=>{try{await D0(J,e),g(null),v([]),a==="inbox"?rt():a==="outbox"?Be():N===Ts?Re():N&&ce(N),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,a,N,rt,Be,ce,Re,n]),ht=i.useCallback(J=>{j({id:J.fromId,type:J.fromType}),x({messageId:J.id,preview:Df(J.content,120)}),y(!0)},[]),tt=i.useCallback(()=>{y(!1),j(null),x(null),n?.("Message sent","success"),a==="outbox"?Be():a==="agents"&&N===Ts?Re():a==="agents"&&N&&ce(N),ct()},[a,Be,N,ce,Re,n,ct]),xt=i.useCallback(()=>{j(a==="agents"&&N&&N!==Ts?{id:N,type:"agent"}:null),x(null),y(!0)},[a,N]),Me=i.useCallback(()=>{y(!1),j(null),x(null)},[]),Ye=i.useCallback(async J=>{try{const me=await dh(J.id,e);X(me),ke("")}catch{n?.("Failed to load approval request","error")}},[e,n]),dt=i.useCallback(async J=>{if(!(!k||He)){ye(J);try{await z0(k.id,{decision:J,comment:le||void 0},e),await Ue(Q);const me=await dh(k.id,e);X(me),ke(""),n?.(`Request ${J==="approve"?"approved":"denied"}`,"success")}catch{n?.("Failed to submit decision","error")}finally{ye(!1)}}},[k,He,le,e,Ue,Q,n]),wt=()=>{if(!p||b)return null;const J=u4(w,p);return t.jsxs("div",{className:"mailbox-message-detail","data-testid":"mailbox-message-detail",id:Fd(p.id),children:[t.jsxs("div",{className:"mailbox-message-detail-header",children:[Z&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:oe,"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:d4(p.type)}),t.jsx("span",{className:"mailbox-message-time",children:Yi(p.createdAt)})]}),t.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>ht(p),"data-testid":"mailbox-reply",children:[t.jsx(Zi,{size:14}),t.jsx("span",{children:"Reply"})]}),t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>ft(p.id),"data-testid":"mailbox-delete",children:[t.jsx(Tn,{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(Qn,{size:14}):t.jsx(Ra,{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(Qn,{size:14}):t.jsx(Ra,{size:14}),ne(p.toId,p.toType)]})]})]}),J.length>1&&t.jsxs("div",{className:"mailbox-conversation","data-testid":"mailbox-conversation",children:[t.jsx("div",{className:"mailbox-conversation-label",children:"Conversation"}),J.map(me=>{const Ze=me.metadata?.replyTo?.messageId,be=Ze?J.find(gt=>gt.id===Ze):void 0;return t.jsxs("div",{id:Fd(me.id),className:`mailbox-conversation-msg ${me.id===p.id?"current":""}`,children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:ne(me.fromId,me.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:Yi(me.createdAt)})]}),Ze&&t.jsxs("div",{className:"mailbox-reply-context-static","data-testid":`mailbox-reply-context-${me.id}`,children:["↪ Replying to ",be?Df(be.content,60):`message ${Ze}`]}),t.jsx(If,{content:me.content,className:"mailbox-conversation-msg-body"})]},me.id)})]}),J.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(If,{content:p.content,className:"mailbox-message-body",testId:"mailbox-message-body"})]})]})},St=()=>t.jsxs(t.Fragment,{children:[a==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!o&&t.jsx(Ml,{}),o&&o.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[t.jsx(ma,{size:32}),t.jsx("p",{children:"No messages in your inbox"})]}),o?.messages.map(J=>t.jsxs("div",{id:co(J.id),className:`mailbox-item ${J.read?"":"unread"}`,onClick:()=>ue(J),"data-testid":`mailbox-item-${J.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:J.fromType==="agent"?t.jsx(Qn,{size:16}):t.jsx(Ra,{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(J.fromId,J.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:Yi(J.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[J.content.slice(0,80),J.content.length>80?"…":""]})]}),!J.read&&t.jsx("div",{className:"mailbox-item-unread-dot","data-testid":`mailbox-unread-dot-${J.id}`})]},J.id))]}),a==="outbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!c&&t.jsx(Ml,{}),c&&c.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[t.jsx(Da,{size:32}),t.jsx("p",{children:"No sent messages"})]}),c?.messages.map(J=>t.jsxs("div",{id:co(J.id),className:"mailbox-item",onClick:()=>ue(J),"data-testid":`mailbox-item-${J.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:J.toType==="agent"?t.jsx(Qn,{size:16}):t.jsx(Ra,{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(J.toId,J.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:Yi(J.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[J.content.slice(0,80),J.content.length>80?"…":""]})]})]},J.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 ${Q==="pending"?"active":""}`,onClick:()=>{se("pending"),X(null)},"data-testid":"mailbox-approval-filter-pending",children:"Pending"}),t.jsx("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${Q==="history"?"active":""}`,onClick:()=>{se("history"),X(null)},"data-testid":"mailbox-approval-filter-history",children:"History"})]}),t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-approval-list",children:[O.length===0&&!h&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-approval-empty",children:[t.jsx(ma,{size:32}),t.jsx("p",{children:Q==="pending"?"No pending approvals":"No historical approvals"})]}),O.map(J=>t.jsxs("div",{className:"mailbox-item mailbox-approval-item",onClick:()=>void Ye(J),"data-testid":`mailbox-approval-item-${J.id}`,children:[t.jsx("div",{className:`status-dot mailbox-approval-status-dot mailbox-approval-status-dot--${J.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:[J.agentId," · ",J.actionCategory]}),t.jsx("span",{className:"mailbox-item-time",children:Yi(J.createdAt)})]}),t.jsx("div",{className:"mailbox-item-preview",children:J.actionSummary})]}),t.jsx("span",{className:`mailbox-approval-status mailbox-approval-status--${J.status}`,children:J.status})]},J.id))]})]}),a==="agents"&&t.jsx("div",{className:"mailbox-agents","data-testid":"mailbox-agents",children:T.length===0?t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Qn,{size:32}),t.jsx("p",{children:"No agents found"})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"mailbox-agents-header",children:[t.jsx("div",{className:"mailbox-agents-dropdown",children:t.jsxs("select",{className:"message-composer-select mailbox-agent-select",value:N,onChange:J=>{R(J.target.value),E("inbox")},"data-testid":"mailbox-agent-select",children:[t.jsx("option",{value:Ts,children:"All agents"}),T.map(J=>t.jsx("option",{value:J.id,children:J.name||J.id},J.id))]})}),t.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:xt,"data-testid":"mailbox-compose-btn",children:[t.jsx(Zi,{size:14}),t.jsx("span",{children:"Compose"})]})]}),N&&N!==Ts&&t.jsxs("div",{className:"mailbox-agent-subtabs","data-testid":"mailbox-agent-subtabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${F==="inbox"?"active":""}`,onClick:()=>E("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[t.jsx(ma,{size:12}),t.jsx("span",{children:"Inbox"}),_&&_.unreadCount>0&&t.jsx("span",{className:"mailbox-tab-badge",children:_.unreadCount})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${F==="outbox"?"active":""}`,onClick:()=>E("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[t.jsx(Da,{size:12}),t.jsx("span",{children:"Outbox"})]})]}),t.jsxs("div",{className:"mailbox-agents-content",children:[N===Ts&&h&&!U&&t.jsx(Ml,{}),N===Ts&&U&&U.messages.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(ma,{size:32}),t.jsx("p",{children:"No agent-to-agent messages"})]}),N===Ts&&U&&U.messages.map(J=>t.jsxs("div",{id:co(J.id),className:`mailbox-item ${J.read?"":"unread"}`,onClick:()=>ue(J),"data-testid":`mailbox-item-${J.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:J.fromType==="agent"?t.jsx(Qn,{size:16}):t.jsx(Ra,{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(J.fromId,J.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:Yi(J.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-participants","data-testid":`mailbox-item-participants-${J.id}`,children:[t.jsxs("span",{children:["From: ",ne(J.fromId,J.fromType)]}),t.jsxs("span",{children:["To: ",ne(J.toId,J.toType)]})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[J.content.slice(0,80),J.content.length>80?"…":""]})]})]},J.id)),N&&N!==Ts&&h&&!_&&t.jsx(Ml,{}),N&&N!==Ts&&_&&F==="inbox"&&_.inbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(ma,{size:32}),t.jsx("p",{children:"No received messages for this agent"})]}),N&&N!==Ts&&_&&F==="outbox"&&_.outbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Da,{size:32}),t.jsx("p",{children:"No sent messages for this agent"})]}),N&&N!==Ts&&_&&F==="inbox"&&_.inbox.map(J=>t.jsxs("div",{id:co(J.id),className:`mailbox-item ${J.read?"":"unread"}`,onClick:()=>ue(J),"data-testid":`mailbox-item-${J.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:J.fromType==="agent"?t.jsx(Qn,{size:16}):t.jsx(Ra,{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(J.fromId,J.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:Yi(J.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[J.content.slice(0,80),J.content.length>80?"…":""]})]})]},J.id)),N&&N!==Ts&&_&&F==="outbox"&&_.outbox.map(J=>t.jsxs("div",{id:co(J.id),className:"mailbox-item",onClick:()=>ue(J),"data-testid":`mailbox-item-${J.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:J.toType==="agent"?t.jsx(Qn,{size:16}):t.jsx(Ra,{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(J.toId,J.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:Yi(J.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[J.content.slice(0,80),J.content.length>80?"…":""]})]})]},J.id))]})]})})]}),Fe=()=>b?t.jsx(Tf,{recipient:S,replyContext:C,agents:T,projectId:e,onSend:tt,onCancel:Me,addToast:n}):p?wt():a==="approvals"&&k?t.jsxs("div",{className:"mailbox-message-detail mailbox-approval-detail","data-testid":"mailbox-approval-detail",children:[Z&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:()=>X(null),"data-testid":"mailbox-approval-back-to-list",children:"← Back"}),t.jsx("div",{className:"mailbox-message-detail-header",children:t.jsxs("div",{className:"mailbox-message-detail-meta",children:[t.jsx("span",{className:"mailbox-message-type",children:k.actionCategory}),t.jsx("span",{className:"mailbox-message-time",children:k.status})]})}),t.jsxs("div",{className:"mailbox-message-body",children:[t.jsx("strong",{children:k.actionSummary}),t.jsxs("p",{children:["Requester: ",k.requester.actorName," (",k.agentId,")"]}),k.taskId&&t.jsxs("p",{children:["Task: ",k.taskId]}),t.jsxs("p",{children:["Requested: ",Yi(k.createdAt)]})]}),t.jsx("div",{className:"mailbox-conversation","data-testid":"mailbox-approval-history",children:k.history.map(J=>t.jsxs("div",{className:"mailbox-conversation-msg",children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:J.eventType}),t.jsx("span",{children:J.actor.actorName})]}),J.note&&t.jsx("div",{className:"mailbox-item-preview",children:J.note})]},J.id))}),k.status==="pending"&&t.jsxs("div",{className:"mailbox-approval-decision","data-testid":"mailbox-approval-decision",children:[t.jsx("textarea",{className:"message-composer-textarea mailbox-approval-comment",value:le,onChange:J=>ke(J.target.value),placeholder:"Optional comment","data-testid":"mailbox-approval-comment"}),t.jsxs("div",{className:"mailbox-header-actions",children:[t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:()=>void dt("deny"),disabled:He!==!1,"data-testid":"mailbox-approval-deny",children:"Deny"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>void dt("approve"),disabled:He!==!1,"data-testid":"mailbox-approval-approve",children:"Approve"})]})]})]}):t.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[t.jsx(za,{size:24}),t.jsx("p",{children:"Select a message to read"})]});return t.jsxs("div",{className:"mailbox-view",style:ae,"data-testid":"mailbox-view",children:[t.jsxs("div",{className:"mailbox-header",children:[t.jsxs("div",{className:"mailbox-title",children:[t.jsx(za,{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:xt,title:"Compose message","data-testid":"mailbox-header-compose",children:[t.jsx(Zi,{size:14}),t.jsx("span",{children:"Compose"})]}),a==="inbox"&&u>0&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:Ee,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[t.jsx(Im,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{a==="inbox"?rt():a==="outbox"?Be():a==="approvals"?Ue(Q):N===Ts?Re():N&&ce(N)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?t.jsx(jt,{size:14,className:"spin"}):t.jsx(ps,{size:14})})]})]}),t.jsxs("div",{className:"mailbox-tabs","data-testid":"mailbox-tabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${a==="inbox"?"active":""}`,onClick:()=>{r("inbox"),g(null)},"data-testid":"mailbox-tab-inbox",children:[t.jsx(ma,{size:14}),t.jsx("span",{children:"Inbox"}),u>0&&t.jsx("span",{className:"mailbox-tab-badge",children:u})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${a==="outbox"?"active":""}`,onClick:()=>{r("outbox"),g(null)},"data-testid":"mailbox-tab-outbox",children:[t.jsx(Da,{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),X(null)},"data-testid":"mailbox-tab-agents",children:[t.jsx(Qn,{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),X(null)},"data-testid":"mailbox-tab-approvals",children:[t.jsx(Im,{size:14}),t.jsx("span",{children:"Approvals"}),D>0&&t.jsx("span",{className:"mailbox-tab-badge","data-testid":"mailbox-approvals-pending-badge",children:D})]})]}),t.jsx("div",{className:"mailbox-content","data-testid":"mailbox-content",children:re?t.jsxs("div",{className:"mailbox-split-layout","data-testid":"mailbox-split-layout",ref:xe,children:[t.jsx("div",{className:"mailbox-split-list-pane","data-testid":"mailbox-split-list-pane",style:{width:`${q}px`},children:St()}),t.jsx("div",{className:"mailbox-split-resize-handle","data-testid":"mailbox-split-resize-handle",role:"separator","aria-orientation":"vertical","aria-label":"Resize message list pane",tabIndex:0,"aria-valuemin":oc,"aria-valuemax":Math.round(Ru(xe.current?.clientWidth??q/Au)),"aria-valuenow":Math.round(q),onMouseDown:Ve,onKeyDown:Te}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:Fe()})]}):t.jsxs(t.Fragment,{children:[wt(),a==="approvals"&&k&&Fe(),b&&t.jsx(Tf,{recipient:S,replyContext:C,agents:T,projectId:e,onSend:tt,onCancel:Me,addToast:n}),!p&&!k&&!b&&St()]})})]})}function Ml(){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 h4=640;function p4({isOpen:e,onClose:n,onImport:s,tasks:a,projectId:r}){Mi(e);const[o,l]=i.useState(""),[c,d]=i.useState(""),[u,m]=i.useState(""),[h,f]=i.useState(!1),[p,g]=i.useState("issues"),[w,v]=i.useState([]),[b,y]=i.useState(null),[S,j]=i.useState([]),[C,x]=i.useState(null),[N,R]=i.useState(null),[F,E]=i.useState(!1),[_,K]=i.useState([]),[U,A]=i.useState(!1),[T,H]=i.useState(""),Q=i.useRef(!1),se=i.useRef(null);zi(se,e,"fusion:github-modal-size");const O=sa(n),[M,D]=i.useState(!1),[$,k]=i.useState("list"),X=i.useRef(null),le=new Set;for(const ue of a){const oe=ue.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);oe&&le.add(oe[1]);const Ee=ue.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);Ee&&le.add(Ee[1])}i.useEffect(()=>{if(e)return l(""),d(""),m(""),v([]),y(null),j([]),x(null),g("issues"),R(null),E(!1),K([]),A(!0),H(""),X.current=null,Q.current=!0,PN().then(ue=>{if(Q.current)if(K(ue),A(!1),ue.length===1){const oe=ue[0];l(oe.owner),d(oe.repo),H(oe.name)}else ue.length>1&&(l(""),d(""),H(""))}).catch(()=>{Q.current&&A(!1)}),()=>{Q.current=!1}},[e]);const ke=i.useCallback(ue=>{if(H(ue),ue==="")l(""),d("");else{const oe=_.find(Ee=>Ee.name===ue);oe&&(l(oe.owner),d(oe.repo))}},[_]),He=i.useCallback(async()=>{if(!o.trim()||!c.trim()){R("Repository must be selected");return}f(!0),R(null),v([]),y(null);try{const ue=u.split(",").map(Ee=>Ee.trim()).filter(Boolean),oe=await AN(o.trim(),c.trim(),30,ue.length>0?ue:void 0);v(oe),oe.length===0&&R("No open issues found")}catch(ue){R(Se(ue)||"Failed to fetch issues")}finally{f(!1)}},[o,c,u]),ye=i.useCallback(async()=>{if(!o.trim()||!c.trim()){R("Repository must be selected");return}f(!0),R(null),j([]),x(null);try{const ue=await IN(o.trim(),c.trim(),30);j(ue),ue.length===0&&R("No open pull requests found")}catch(ue){R(Se(ue)||"Failed to fetch pull requests")}finally{f(!1)}},[o,c]);i.useEffect(()=>{if(!e||!o.trim()||!c.trim()||h||F)return;const ue={owner:o.trim(),repo:c.trim(),labels:u.trim(),tab:p};X.current?.owner===ue.owner&&X.current?.repo===ue.repo&&X.current?.labels===ue.labels&&X.current?.tab===ue.tab||(X.current=ue,p==="issues"?He():ye())},[o,c,u,p,e,h,F,He,ye]),i.useEffect(()=>{if(!e)return;const ue=oe=>{oe.key==="Escape"&&n()};return document.addEventListener("keydown",ue),()=>document.removeEventListener("keydown",ue)},[e,n]),i.useEffect(()=>{if(!e)return;const ue=()=>{D(window.innerWidth<=h4)};return ue(),window.addEventListener("resize",ue),()=>window.removeEventListener("resize",ue)},[e]);const je=i.useCallback(ue=>{y(ue),M&&k("preview")},[M]),ne=i.useCallback(ue=>{x(ue),M&&k("preview")},[M]),fe=i.useCallback(()=>{k("list")},[]),Z=i.useCallback(async()=>{if(p==="issues"){if(b===null)return;E(!0),R(null);try{const ue=await RN(o.trim(),c.trim(),b,r);s(ue),y(null),M&&$==="preview"&&k("list")}catch(ue){const oe=Se(ue);oe?.includes("already imported")?R(oe):R(oe||"Failed to import issue")}finally{E(!1)}}else{if(C===null)return;E(!0),R(null);try{const ue=await TN(o.trim(),c.trim(),C,r);s(ue),x(null),M&&$==="preview"&&k("list")}catch(ue){const oe=Se(ue);oe?.includes("already imported")?R(oe):R(oe||"Failed to import pull request")}finally{E(!1)}}},[p,b,C,o,c,s,M,$]),re=w.find(ue=>ue.number===b),q=S.find(ue=>ue.number===C);if(!e)return null;const L=_.length>0,xe=_.length===1,he=w.filter(ue=>le.has(ue.html_url)).length,B=S.filter(ue=>le.has(ue.html_url)).length,pe=N==="No open issues found",ze=N==="No open pull requests found",ae=p==="issues"?pe:ze,Ve=!!N&&!pe&&w.length===0&&!h,Te=!!N&&!ze&&S.length===0&&!h,rt=p==="issues"?Ve:Te,Be=h||w.length>0||pe||Ve,ce=h||S.length>0||ze||Te,Re=p==="issues"?Be:ce,Le=!!N&&w.length>0&&!pe,ct=!!N&&S.length>0&&!ze,Ue=p==="issues"?Le:ct;return t.jsx("div",{className:"modal-overlay open",...O,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg github-import-modal",ref:se,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"),x(null)},disabled:h||F,children:[t.jsx(fc,{size:16}),t.jsx("span",{children:"Issues"})]}),t.jsxs("button",{role:"tab","aria-selected":p==="pulls","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="pulls"?"active":""}`,onClick:()=>{g("pulls"),y(null)},disabled:h||F,children:[t.jsx(ii,{size:16}),t.jsx("span",{children:"Pull Requests"})]})]}),t.jsxs("div",{className:"github-import-toolbar","data-testid":"github-import-toolbar",role:"toolbar","aria-label":"GitHub import controls",children:[t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--remote",children:U?t.jsxs("div",{className:"github-import-toolbar__loading",role:"status","aria-live":"polite",children:[t.jsx(jt,{size:16,className:"spin"}),t.jsx("span",{children:"Detecting…"})]}):L?xe?t.jsxs("div",{className:"github-import-remote-pill","data-testid":"github-import-single-remote",children:[t.jsx("span",{className:"github-import-remote-pill__name",children:_[0].name}),t.jsxs("span",{className:"github-import-remote-pill__repo",children:[_[0].owner,"/",_[0].repo]})]}):t.jsxs("div",{className:"github-import-remote-select",children:[t.jsx("label",{htmlFor:"gh-remote",className:"visually-hidden",children:"Repository"}),t.jsxs("select",{id:"gh-remote",value:T,onChange:ue=>ke(ue.target.value),disabled:h||F,"aria-label":"Select Git remote",children:[t.jsx("option",{value:"",children:"Select remote…"}),_.map(ue=>t.jsxs("option",{value:ue.name,children:[ue.name," (",ue.owner,"/",ue.repo,")"]},ue.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:ue=>m(ue.target.value),onKeyDown:ue=>ue.key==="Enter"&&He(),disabled:h||F||!L,"aria-label":"Filter issues by labels"})]}):t.jsxs("span",{className:"github-import-filter-hint",children:["Open pull requests from ",o||"selected remote"]})}),t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--action",children:t.jsxs("button",{id:"gh-load",className:"btn btn-primary github-import-load-button",onClick:p==="issues"?He:ye,disabled:h||F||!o.trim()||!c.trim(),"aria-label":h?`Loading ${p}`:`Load ${p} from repository`,title:h?"Loading…":`Load ${p}`,children:[h?t.jsx(jt,{size:14,className:"spin"}):t.jsx(ps,{size:14}),t.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!U&&!L&&t.jsxs("div",{className:"github-import-state github-import-state--warning",role:"alert",children:[t.jsxs("div",{children:[t.jsx("strong",{children:"No GitHub remotes detected"}),t.jsx("span",{children:"Add a GitHub remote to this repository, then reopen the modal."})]}),t.jsx("code",{className:"github-import-command",children:"git remote add origin https://github.com/owner/repo.git"})]}),Ue&&t.jsx("div",{className:"form-error github-import-banner",role:"alert",children:N}),t.jsxs("div",{className:"github-import-workspace",children:[t.jsxs("section",{className:`github-import-list-pane ${M?"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"&&w.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[w.length," issue",w.length===1?"":"s"]}),t.jsxs("span",{children:[he," imported"]})]}),p==="pulls"&&S.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[S.length," pull request",S.length===1?"":"s"]}),t.jsxs("span",{children:[B," imported"]})]})]}),t.jsxs("div",{className:"github-import-pane-content",children:[!Re&&t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-results-idle",children:t.jsxs("div",{children:[t.jsx("strong",{children:"Nothing loaded yet"}),t.jsx("span",{children:"Select a repository and click Load to start reviewing import candidates."})]})}),h&&t.jsxs("div",{className:"github-import-state github-import-state--loading",role:"status","aria-live":"polite",children:[t.jsx(jt,{size:16,className:"spin"}),t.jsxs("div",{children:[t.jsxs("strong",{children:["Loading open ",p==="issues"?"issues":"pull requests","…"]}),t.jsx("span",{children:"Fetching the latest list from GitHub."})]})]}),rt&&t.jsx("div",{className:"github-import-state github-import-state--error",role:"alert",children:t.jsxs("div",{children:[t.jsxs("strong",{children:["Could not load ",p==="issues"?"issues":"pull requests"]}),t.jsx("span",{children:N})]})}),ae&&t.jsx("div",{className:"github-import-state github-import-state--empty",role:"status",children:t.jsxs("div",{children:[t.jsxs("strong",{children:["No open ",p==="issues"?"issues":"pull requests"," found"]}),t.jsx("span",{children:p==="issues"?"Try a different label filter or choose another repository.":"Choose another repository."})]})}),p==="issues"&&w.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:w.map(ue=>{const oe=le.has(ue.html_url);return t.jsxs("div",{className:`issue-item ${b===ue.number?"selected":""} ${oe?"imported":""}`,onClick:()=>!oe&&je(ue.number),children:[t.jsx("input",{type:"radio",name:"issue",checked:b===ue.number,onChange:()=>je(ue.number),disabled:oe,"aria-label":`Select issue #${ue.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",ue.number]}),t.jsx("span",{className:"issue-title",children:ue.title})]}),ue.labels.length>0&&t.jsx("span",{className:"issue-labels",children:ue.labels.map(Ee=>t.jsx("span",{className:"label-chip",children:Ee.name},Ee.name))})]}),oe&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},ue.number)})}),p==="pulls"&&S.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:S.map(ue=>{const oe=le.has(ue.html_url);return t.jsxs("div",{className:`issue-item ${C===ue.number?"selected":""} ${oe?"imported":""}`,onClick:()=>!oe&&ne(ue.number),children:[t.jsx("input",{type:"radio",name:"pull",checked:C===ue.number,onChange:()=>ne(ue.number),disabled:oe,"aria-label":`Select pull request #${ue.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",ue.number]}),t.jsx("span",{className:"issue-title",children:ue.title})]}),t.jsxs("span",{className:"pull-branch-info",children:[ue.headBranch," → ",ue.baseBranch]})]}),oe&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},ue.number)})})]})]}),t.jsxs("section",{className:`github-import-preview-pane ${M?"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:[M&&t.jsxs("button",{className:"github-import-back-button",onClick:fe,"data-testid":"github-import-back-button","aria-label":`Back to ${p==="issues"?"issues":"pull requests"} list`,children:[t.jsx(Ga,{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"&&q?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Pull Request #",q.number]}),t.jsx("div",{className:"preview-title",children:q.title}),t.jsxs("div",{className:"preview-branch",children:[t.jsx("strong",{children:"Branch:"})," ",q.headBranch," → ",q.baseBranch]}),t.jsx("div",{className:"preview-body",children:q.body?q.body.slice(0,200)+(q.body.length>200?"…":""):"(no description)"})]}):p==="pulls"?t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-preview-empty",children:t.jsxs("div",{children:[t.jsx("strong",{children:"No pull request selected"}),t.jsx("span",{children:"Choose a pull request from the list to inspect its details."})]})}):null]})]})]})]}),t.jsxs("div",{className:"modal-actions github-import-modal__actions",children:[t.jsx("button",{className:"btn",onClick:n,disabled:F,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:Z,disabled:(p==="issues"?b===null:C===null)||F,children:F?t.jsx(jt,{size:14,className:"spin"}):"Import"})]})]})})}function fi({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(qn,{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 f4=["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 Va(e){return e&&wa.includes(e)?e:Ps}function zd(e){return{...e,priority:Va(e.priority)}}function g4(e,n){return e.length===n.length&&e.every((s,a)=>s===n[a])}function b4(e,n){const s=new Map(e.map(a=>[a.id,a]));return n.map(a=>{const r=s.get(a.id),o=Va(a.priority),l={id:a.id};return(!r||a.title!==r.title)&&(l.title=a.title),(!r||a.description!==r.description)&&(l.description=a.description),(!r||a.suggestedSize!==r.suggestedSize)&&(l.suggestedSize=a.suggestedSize),(!r||o!==Va(r.priority))&&(l.priority=o),(!r||!g4(a.dependsOn,r.dependsOn))&&(l.dependsOn=a.dependsOn),l})}function x4(e,n){return e&&n?`${e}/${n}`:""}function v4(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 y4({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,w]=i.useState([]),[v,b]=i.useState([]),[y,S]=i.useState(null),j=i.useRef(!1),C=i.useRef(!1),[x,N]=i.useState(""),[R,F]=i.useState(!0),[E,_]=i.useState(!1),[K,U]=i.useState(!1),[A,T]=i.useState(null),[H,Q]=i.useState(0),se=i.useRef(null),O=i.useRef(null),M=i.useRef(null),D=i.useRef(null),$=i.useRef(null),k=i.useRef(null),X=i.useRef(null),[le,ke]=i.useState(c??null),He=i.useMemo(()=>Ja(),[]),{isLockedByOther:ye,takeControl:je,isLoading:ne}=Tc(e?le:null),{activeTabMap:fe,broadcastUpdate:Z,broadcastCompleted:re,broadcastLock:q,broadcastUnlock:L,broadcastHeartbeat:xe}=Wr(),[he,B]=i.useState(void 0),[pe,ze]=i.useState(void 0),[ae,Ve]=i.useState("medium"),[Te,rt]=i.useState(""),[Be,ce]=i.useState([]),[Re,Le]=i.useState(!1),[ct,Ue]=i.useState(null),[ue,oe]=i.useState([]),[Ee,ft]=i.useState([]),[ht,tt]=i.useState({}),xt=i.useRef(null),[Me,Ye]=i.useState([]),[dt,wt]=i.useState(!1),[St,Fe]=i.useState(c??null),[J,me]=i.useState(!!c),[Ze,be]=i.useState(null),[gt,$t]=i.useState(!1),Ie=i.useRef(!1),ge=i.useRef(null),st=i.useRef(""),yt=i.useRef(null),pt=i.useRef(null);zi(O,e,"fusion:planning-modal-size");const vt=oi(),Ut=vt==="mobile",{pushNav:Dt}=wv(),{keyboardOverlap:nn,viewportHeight:on,viewportOffsetTop:sn,keyboardOpen:ln}=aa({enabled:vt==="mobile"});Mi(vt==="mobile"&&e),i.useEffect(()=>{const de=O.current;de&&(ln?(de.style.setProperty("--keyboard-overlap",`${nn}px`),de.style.setProperty("--vv-offset-top",`${sn}px`),on!==null?de.style.setProperty("--vv-height",`${on}px`):de.style.removeProperty("--vv-height")):(de.style.removeProperty("--keyboard-overlap"),de.style.removeProperty("--vv-offset-top"),de.style.removeProperty("--vv-height")))},[ln,nn,sn,on]),i.useEffect(()=>{st.current=x},[x]),i.useEffect(()=>{const de=ge.current;if(!de)return;de.scrollHeight-de.scrollTop-de.clientHeight<32&&(de.scrollTop=de.scrollHeight)},[x]),i.useEffect(()=>{if(m.type!=="loading"){T(null),Q(0);return}const de=Date.now();T(de),Q(0);const nt=setInterval(()=>{Q(Math.max(0,Math.floor((Date.now()-de)/1e3)))},1e3);return()=>clearInterval(nt)},[m.type]),i.useEffect(()=>{if(m.type!=="loading")return;const de=D.current;if(!de)return;let nt=!1;const _t=setInterval(async()=>{try{const G=await Di(de);if(nt||!G||D.current!==de)return;if(G.status==="awaiting_input"&&G.currentQuestion){const Oe=JSON.parse(G.currentQuestion);h({type:"question",session:{sessionId:de,currentQuestion:Oe,summary:null}}),N("")}else if(G.status==="complete"&&G.result){const Oe=zd(JSON.parse(G.result));h({type:"summary",session:{sessionId:de,currentQuestion:null,summary:Oe},summary:Oe}),S(Oe),N("")}}catch{}},8e3);return()=>{nt=!0,clearInterval(_t)}},[m.type]);const xn=i.useCallback(()=>{u(""),h({type:"initial"}),p(null),w([]),b([]),S(null),N(""),_(!1),U(!1),B(void 0),ze(void 0),Ve("medium"),rt(""),D.current=null,ke(null)},[]),qt=x4(he,pe),Qt=i.useCallback((de,nt)=>{if(!de||!nt)return ht.provider&&ht.modelId?`${ht.provider}/${ht.modelId}`:"Using default";const ot=Be.find(_t=>_t.provider===de&&_t.id===nt);return ot?`${ot.provider}/${ot.id}`:`${de}/${nt}`},[Be,ht.modelId,ht.provider]),hn=i.useCallback(async()=>{Le(!0),Ue(null);try{const de=await Ws();ce(de.models),oe(de.favoriteProviders),ft(de.favoriteModels),tt({provider:de.resolvedPlanningProvider,modelId:de.resolvedPlanningModelId})}catch(de){Ue(Se(de)||"Failed to load models")}finally{Le(!1)}},[]),Zt=i.useCallback(de=>{oe(nt=>{const ot=nt,G=ot.includes(de)?ot.filter(Oe=>Oe!==de):[de,...ot];return Bn({favoriteProviders:G,favoriteModels:Ee}).catch(()=>{oe(ot)}),G})},[Ee]),ve=i.useCallback(de=>{ft(nt=>{const ot=nt,G=ot.includes(de)?ot.filter(Oe=>Oe!==de):[de,...ot];return Bn({favoriteProviders:ue,favoriteModels:G}).catch(()=>{ft(ot)}),G})},[ue]),Pe=i.useCallback(de=>{M.current?.close();const nt=()=>D.current!==de,ot=DS(de,l,{onThinking:_t=>{nt()||(N(G=>G+_t),Z({sessionId:de,status:"generating",needsInput:!1,owningTabId:He,type:"planning",title:d.trim()||void 0,projectId:l??null}))},onQuestion:_t=>{if(nt())return;_(!1),U(!1),hr(l);const G=st.current.trim();G&&b(Oe=>Oe[Oe.length-1]?.thinkingOutput===G?Oe:[...Oe,{thinkingOutput:G}]),h({type:"question",session:{sessionId:de,currentQuestion:_t,summary:null}}),N(""),Z({sessionId:de,status:"awaiting_input",needsInput:!0,owningTabId:He,type:"planning",title:d.trim()||void 0,projectId:l??null})},onSummary:_t=>{if(nt())return;_(!1),U(!1),hr(l);const G=st.current.trim();G&&b(Oe=>Oe[Oe.length-1]?.thinkingOutput===G?Oe:[...Oe,{thinkingOutput:G}]),h({type:"summary",session:{sessionId:de,currentQuestion:null,summary:_t},summary:_t}),S(_t),N(""),Z({sessionId:de,status:"complete",needsInput:!1,owningTabId:He,type:"planning",title:d.trim()||void 0,projectId:l??null})},onError:_t=>{const G=_t||"Session failed while contacting the AI.";_(!0),(async()=>{try{const Oe=await Di(de);if(Oe&&(Oe.status==="generating"||Oe.status==="awaiting_input")){Pe(de);return}}catch{}_(!1),U(!1),p(null),h(Oe=>Oe.type==="question"||Oe.type==="summary"||Oe.type==="error"?{type:"error",session:Oe.session,errorMessage:G}:{type:"error",session:{sessionId:de,currentQuestion:null,summary:null},errorMessage:G}),N(""),D.current=de,Z({sessionId:de,status:"error",needsInput:!1,owningTabId:He,type:"planning",title:d.trim()||void 0,projectId:l??null}),re({sessionId:de,status:"error"})})()},onComplete:()=>{_(!1),U(!1),D.current=null,re({sessionId:de,status:"complete"})},onConnectionStateChange:_t=>{_(_t==="reconnecting")}});M.current=ot},[re,Z,d,l,He]),Ke=i.useCallback(async de=>{const nt=de??d;if(nt.trim()){p(null),N(""),b([]),w([]),_(!1),h({type:"loading"});try{const ot=he&&pe?{planningModelProvider:he,planningModelId:pe}:void 0,_t=Te.trim()?Number.parseInt(Te,10):void 0,G=$.current,{sessionId:Oe}=await xS(nt.trim(),l,ot,{planningDepth:ae,customQuestionCount:Number.isInteger(_t)?_t:void 0},G??void 0);$.current=null,D.current=Oe,ke(Oe),Fe(Oe),Pe(Oe),w([])}catch(ot){_(!1),p(Se(ot)||"Failed to start planning session"),h({type:"initial"}),D.current=null,ke(null)}}},[Pe,Te,d,ae,pe,he,l]);i.useEffect(()=>{e&&m.type==="initial"&&se.current?.focus()},[e,m.type]),i.useEffect(()=>{e&&hn()},[e,hn]),i.useEffect(()=>{if(e&&o&&!j.current&&m.type==="initial"){u(o);const de=setTimeout(()=>{j.current=!0,Ke(o)},0);return()=>clearTimeout(de)}else if(e&&!o&&!j.current&&!C.current&&m.type==="initial"){C.current=!0;const de=y$(l);de&&u(de)}},[e,o,m.type,Ke,l]);const at=i.useCallback(async de=>{M.current?.close(),M.current=null,p(null),N(""),w([]),b([]),S(null),U(!1),h({type:"loading"});try{const nt=await Di(de);if(!nt){Fe(null),me(!1),h({type:"initial"});return}D.current=de,ke(de);const ot=Mr(nt.conversationHistory);if(b(ot),w(ot.map(_t=>_t.response).filter(_t=>!!(_t&&typeof _t=="object"&&!Array.isArray(_t)))),nt.status==="draft"){let _t="",G,Oe;try{const Mt=nt.inputPayload?JSON.parse(nt.inputPayload):null;Mt&&typeof Mt.initialPlan=="string"&&(_t=Mt.initialPlan),Mt&&typeof Mt.modelProvider=="string"&&typeof Mt.modelId=="string"&&(G=Mt.modelProvider,Oe=Mt.modelId)}catch{}u(_t),B(G),ze(Oe),$.current=de,pt.current=_t?{sessionId:de,initialPlan:_t.trim(),modelProvider:G,modelId:Oe}:null,h({type:"initial"})}else if(nt.status==="awaiting_input"&&nt.currentQuestion){hr(l);const _t=JSON.parse(nt.currentQuestion);if(h({type:"question",session:{sessionId:de,currentQuestion:_t,summary:null}}),nt.thinkingOutput){const G=nt.thinkingOutput.trim();G&&b(Oe=>Oe[Oe.length-1]?.thinkingOutput===G?Oe:[...Oe,{thinkingOutput:G}])}Pe(de)}else if(nt.status==="complete"&&nt.result){hr(l);const _t=zd(JSON.parse(nt.result));h({type:"summary",session:{sessionId:de,currentQuestion:null,summary:_t},summary:_t}),S(_t)}else nt.status==="generating"?(h({type:"loading"}),nt.thinkingOutput&&N(nt.thinkingOutput),Pe(de)):nt.status==="error"&&h({type:"error",session:{sessionId:de,currentQuestion:null,summary:null},errorMessage:nt.error||"Session failed"})}catch{p("Failed to load session"),h({type:"initial"})}},[Pe,l]);i.useEffect(()=>{!e||!c||D.current!==c&&X.current!==c&&(Fe(c),me(!0),at(c))},[e,c]),i.useEffect(()=>{e&&St&&(c&&c===St||at(St))},[e]);const We=i.useCallback(async()=>{wt(!0);try{const nt=(await Wu(l,{includeCompleted:!0,includeArchived:gt})).filter(ot=>ot.type==="planning").sort((ot,_t)=>Date.parse(_t.updatedAt)-Date.parse(ot.updatedAt));Ye(nt)}catch{}finally{wt(!1)}},[l,gt]);i.useEffect(()=>{e&&We()},[e,We]);const It=i.useRef(!1);i.useEffect(()=>{const de=It.current&&!dt;It.current=dt,de&&vt==="mobile"&&(J||c||St||Me.length>0||me(!0))},[vt,J,c,St,dt,Me.length]),i.useEffect(()=>{if(!e)return;const de=l?`?projectId=${encodeURIComponent(l)}`:"",nt=_t=>{try{const G=JSON.parse(_t.data);if(G.type!=="planning")return;Ye(Oe=>{const Mt=Oe.findIndex(_n=>_n.id===G.id);return(Mt>=0?[...Oe.slice(0,Mt),G,...Oe.slice(Mt+1)]:[G,...Oe]).sort((_n,Pn)=>Date.parse(Pn.updatedAt)-Date.parse(_n.updatedAt))})}catch{}},ot=_t=>{try{const G=JSON.parse(_t.data);Ye(Oe=>Oe.filter(Mt=>Mt.id!==G))}catch{}};return yi(`/api/events${de}`,{events:{"ai_session:updated":nt,"ai_session:deleted":ot},onReconnect:()=>{We()}})},[e,l,We]);const Lt=i.useCallback(de=>{if(St===de){me(!0);return}Fe(de),me(!0),at(de)},[at,St]),Bt=i.useCallback(()=>{M.current?.close(),M.current=null,$.current=null,k.current&&(clearTimeout(k.current),k.current=null),c&&(X.current=c),xn(),Fe(null),me(!0)},[xn,c]),Gt=i.useCallback(()=>{me(!1)},[]),bt=i.useRef(!1);i.useEffect(()=>{e||(bt.current=!1)},[e]),i.useEffect(()=>{const de=bt.current;if(Ut){if(!J){bt.current=!1;return}de||Dt({type:"view",revert:Gt}),bt.current=!0}},[Gt,Ut,J,Dt]);const Ot=i.useCallback(async(de,nt)=>{const ot=nt.trim();if(!(!ot||pt.current?.sessionId===de&&pt.current.initialPlan===ot&&pt.current.modelProvider===he&&pt.current.modelId===pe))try{await M0(de,{initialPlan:ot,modelProvider:he&&pe?he:void 0,modelId:he&&pe?pe:void 0},l),pt.current={sessionId:de,initialPlan:ot,modelProvider:he,modelId:pe}}catch{}},[pe,he,l]);i.useEffect(()=>{if(yt.current&&(clearTimeout(yt.current),yt.current=null),!(!e||m.type!=="initial"||!St))return yt.current=setTimeout(()=>{Ot(St,d)},500),()=>{yt.current&&(clearTimeout(yt.current),yt.current=null)}},[d,e,St,Ot,m.type]),i.useEffect(()=>{pt.current=null},[St]),i.useEffect(()=>()=>{yt.current&&(clearTimeout(yt.current),yt.current=null)},[]);const en=i.useCallback(async de=>{const nt=_t=>_t==="generating"||_t==="awaiting_input",ot=Me.find(_t=>_t.id===de);if(ot&&nt(ot.status))try{await pb(de,l,He)}catch{}try{await jb(de)}catch{}re({sessionId:de,status:"complete",timestamp:Date.now()}),Ye(_t=>_t.filter(G=>G.id!==de)),St===de&&(M.current?.close(),M.current=null,xn(),Fe(null),me(!1)),be(null)},[re,Me,l,xn,St,He]),Kt=i.useCallback(async de=>{const ot=Me.find(_t=>_t.id===de)?.archived===!0;try{ot?await N0(de):await j0(de)}catch{return}Ye(_t=>!ot&&!gt?_t.filter(G=>G.id!==de):_t.map(G=>G.id===de?{...G,archived:!ot}:G)),!ot&&St===de&&!gt&&(M.current?.close(),M.current=null,xn(),Fe(null),me(!1))},[Me,xn,St,me,gt]);i.useEffect(()=>{e||(j.current=!1,C.current=!1,_(!1),U(!1),ke(null))},[e]),i.useEffect(()=>{if(!e){xt.current&&(L(xt.current,He),xt.current=null);return}if(le&&xt.current!==le){xt.current&&L(xt.current,He),q(le,He),xt.current=le;return}!le&&xt.current&&(L(xt.current,He),xt.current=null)},[q,L,e,le,He]),i.useEffect(()=>{if(!e||!le||xt.current!==le)return;xe(He);const de=setInterval(()=>{xe(He)},3e4);return()=>{clearInterval(de)}},[xe,e,le,He]),i.useEffect(()=>()=>{k.current&&(clearTimeout(k.current),k.current=null),M.current?.close(),M.current=null,xt.current&&(L(xt.current,He),xt.current=null)},[L,He]),i.useEffect(()=>{if(!e)return;const de=()=>{M.current?.close(),M.current=null};return window.addEventListener("beforeunload",de),()=>window.removeEventListener("beforeunload",de)},[e]);const Sn=i.useCallback((de,nt)=>{yt.current&&(clearTimeout(yt.current),yt.current=null),(async()=>{try{await Ot(de,nt),await A0(de,l)}catch{}})()},[l,Ot]),dn=i.useCallback(()=>{if(vt!=="mobile")return;const de=document.activeElement;de instanceof HTMLElement&&de.blur(),window.scrollTo(0,0),requestAnimationFrame(()=>{window.scrollTo(0,0)})},[vt]),Jt=i.useCallback(()=>{d&&m.type==="initial"&&v$(d,l);const de=$.current;de&&d.trim()&&Sn(de,d),$.current=null,k.current&&(clearTimeout(k.current),k.current=null),M.current?.close(),M.current=null,_(!1),U(!1),dn(),n()},[Sn,d,n,l,dn,m.type]);i.useEffect(()=>{if(!e)return;const de=nt=>{nt.key==="Escape"&&Jt()};return document.addEventListener("keydown",de),()=>document.removeEventListener("keydown",de)},[e,Jt]);const tn=i.useCallback(async de=>{if(m.type!=="question")return;const{session:nt}=m,ot=nt.sessionId,_t=nt.currentQuestion;if(!_t){p("No active question in session");return}p(null),w(G=>[...G,de]),b(G=>{const Oe=st.current.trim();let Mt=G;return Oe&&Mt[Mt.length-1]?.thinkingOutput!==Oe&&(Mt=[...Mt,{thinkingOutput:Oe}]),[...Mt,{question:_t,response:de}]}),h({type:"loading"}),N("");try{await Ym(ot,de,l,He)}catch(G){p(Se(G)||"Failed to submit response"),h({type:"question",session:nt})}},[l,He,m]),Ne=i.useCallback(async()=>{if(m.type!=="summary")return;const{session:de,summary:nt}=m,ot=de.sessionId;D.current=ot,ke(ot),p(null),U(!1),N(""),h({type:"loading"}),Pe(ot);try{await Ym(ot,{refine:!0},l,He)}catch(_t){M.current?.close(),M.current=null,p(Se(_t)||"Failed to refine plan"),h({type:"summary",session:de,summary:y??nt})}},[Pe,y,l,He,m]),W=i.useCallback(async()=>{const de=D.current;if(de){try{await wS(de,l,He)}catch{}M.current?.close(),M.current=null,_(!1),U(!1),h({type:"error",session:{sessionId:de,currentQuestion:null,summary:null},errorMessage:"Generation stopped by user. You can retry or start a new session."}),N("")}},[l,He]),Y=i.useCallback(async()=>{if(m.type!=="error")return;const de=m.session;p(null),U(!0),N(""),h({type:"loading"}),Pe(de.sessionId);try{D.current=de.sessionId,ke(de.sessionId),await yS(de.sessionId,l,He)}catch(nt){let ot=nt;if((Se(nt)||"").includes("not in an error state"))try{const G=await Di(de.sessionId);if(!G)throw new Error("Failed to refresh planning session.");if(D.current=G.id,ke(G.id),G.status==="generating")N(G.thinkingOutput??""),h({type:"loading"});else if(G.status==="awaiting_input"){if(!G.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const Oe=JSON.parse(G.currentQuestion);if(hr(l),h({type:"question",session:{sessionId:G.id,currentQuestion:Oe,summary:null}}),G.thinkingOutput){const Mt=G.thinkingOutput.trim();Mt&&b(Xt=>Xt[Xt.length-1]?.thinkingOutput===Mt?Xt:[...Xt,{thinkingOutput:Mt}])}M.current?.isConnected()||Pe(G.id)}else if(G.status==="complete"){if(!G.result)throw new Error("Planning session is complete but has no result.");const Oe=zd(JSON.parse(G.result));hr(l),h({type:"summary",session:{sessionId:G.id,currentQuestion:null,summary:Oe},summary:Oe}),S(Oe)}else G.status==="error"&&h({type:"error",session:{sessionId:G.id,currentQuestion:null,summary:null},errorMessage:G.error||"Retry failed. Please try again."});_(!1);return}catch(G){ot=G}M.current?.close(),M.current=null,h({type:"error",session:de,errorMessage:Se(ot)||"Retry failed. Please try again."}),_(!1)}finally{U(!1)}},[Pe,l,He,m]),_e=i.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const de=m.session.sessionId,nt=await kS(de,y??void 0,l);s(nt),Fe(null),Ye(ot=>ot.filter(_t=>_t.id!==de)),re({sessionId:de,status:"complete",timestamp:Date.now()}),Jt()}catch(de){p(Se(de)||"Failed to create task"),h({type:"summary",session:m.session,summary:m.summary})}}},[re,y,m,l,s,Jt]),ut=i.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const de=await jS(m.session.sessionId,y??void 0,l),nt=de.subtasks.map(ot=>({...ot,priority:Va(ot.priority),dependsOn:[...ot.dependsOn]}));ke(de.sessionId),h({type:"breakdown",sessionId:de.sessionId,originalSubtasks:nt.map(ot=>({...ot,dependsOn:[...ot.dependsOn]})),subtasks:nt.map(ot=>({...ot,dependsOn:[...ot.dependsOn]})),dirty:!1})}catch(de){p(Se(de)||"Failed to start breakdown"),h({type:"summary",session:m.session,summary:m.summary})}}},[y,m,l]),At=i.useCallback(async()=>{if(m.type==="breakdown"){p(null),h({type:"creating"});try{const de=m.sessionId,nt=await NS(de,b4(m.originalSubtasks,m.subtasks.map(ot=>({...ot,priority:Va(ot.priority)}))),l);a(nt.tasks),Ye(ot=>ot.filter(_t=>_t.id!==de)),re({sessionId:de,status:"complete",timestamp:Date.now()}),u(""),h({type:"initial"}),p(null),w([]),b([]),S(null),N(""),B(void 0),ze(void 0),Ve("medium"),rt(""),D.current=null,ke(null),Fe(null),Jt()}catch(de){p(Se(de)||"Failed to create tasks"),h({type:"breakdown",sessionId:m.sessionId,originalSubtasks:m.originalSubtasks,subtasks:m.subtasks,dirty:m.dirty})}}},[re,Jt,m,a,l]),zt=i.useCallback(async()=>{if(m.type!=="question"||g.length===0)return;const de=m.session.sessionId;p(null),h({type:"loading"});try{const nt=await vS(de,l,He);w(nt.history.map(ot=>ot.response&&typeof ot.response=="object"&&!Array.isArray(ot.response)?ot.response:{[ot.question.id]:ot.response})),b(nt.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}))),N(""),h({type:"question",session:{...m.session,currentQuestion:nt.currentQuestion,summary:null}})}catch(nt){p(Se(nt)||"Failed to go back to the previous question"),h({type:"question",session:m.session})}},[l,g.length,He,m]),yn=()=>m.type==="question"?Math.min(g.length+1,3):3,Zn=le?fe.get(le):null,vn=Zn&&Zn.tabId!==He,Dn=ye&&(!vn||Zn.stale);return e?t.jsx("div",{className:"modal-overlay open",onMouseDown:de=>{Ie.current=de.target===de.currentTarget},onClick:de=>{de.target===de.currentTarget&&Ie.current&&Jt(),Ie.current=!1},role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",ref:O,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[J&&t.jsx("button",{className:"modal-back planning-mobile-back",onClick:Gt,"aria-label":"Back to sessions",title:"Back to sessions",children:t.jsx(pc,{size:18})}),t.jsx(Oi,{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:Jt,"aria-label":"Close",children:t.jsx(mn,{size:20})})})]}),t.jsxs("div",{className:`planning-modal-body planning-modal-body--split ${J?"planning-modal-body--show-detail":"planning-modal-body--show-list"}`,children:[t.jsx(S4,{sessions:Me,loading:dt,selectedSessionId:St,pendingDeleteId:Ze,showArchived:gt,onToggleShowArchived:()=>$t(de=>!de),onArchive:de=>void Kt(de),onSelectSession:Lt,onNewSession:Bt,onRequestDelete:be,onConfirmDelete:de=>void en(de),onCancelDelete:()=>be(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(ms,{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:se,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:de=>{const nt=de.target.value;u(nt),!($.current||nt.trim().length===0)&&(k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{if($.current)return;const ot=nt.trim();if(!ot)return;bS(ot,l,he&&pe?{planningModelProvider:he,planningModelId:pe}:void 0).then(G=>{$.current=G.sessionId,Ye(Oe=>Oe.some(Xt=>Xt.id===G.sessionId)?Oe:[{id:G.sessionId,type:"planning",status:"draft",title:G.title,preview:ot.length>80?`${ot.slice(0,79).trimEnd()}…`:ot,projectId:l??null,lockedByTab:null,updatedAt:new Date().toISOString(),archived:!1},...Oe].sort((Xt,_n)=>Date.parse(_n.updatedAt)-Date.parse(Xt.updatedAt))),Fe(G.sessionId)}).catch(()=>{})},300))},onKeyDown:de=>{de.key==="Enter"&&!de.shiftKey&&d.trim()&&(de.preventDefault(),Ke())},onBlur:()=>{const de=$.current;de&&d.trim()&&Sn(de,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:f4.map((de,nt)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>u(de),children:de.length>40?de.slice(0,40)+"...":de},nt))})]}),t.jsx(fi,{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",Re&&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(_s,{id:"planning-modal-model",label:"Planning Model",value:qt,onChange:de=>{const{provider:nt,modelId:ot}=v4(de);B(nt),ze(ot)},models:Be,disabled:Re,favoriteProviders:ue,onToggleFavorite:Zt,favoriteModels:Ee,onToggleModelFavorite:ve}),ct&&t.jsxs("div",{className:"form-hint form-hint-error",children:[ct," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{hn()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${he&&pe?"model-badge-custom":"model-badge-default"}`,children:Qt(he,pe)})})]}),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(de=>t.jsx("button",{type:"button",className:`planning-depth-chip btn ${ae===de.value?"btn-primary planning-depth-chip-active":""}`,onClick:()=>Ve(de.value),"aria-pressed":ae===de.value,children:de.label},de.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:Te,onChange:de=>rt(de.target.value),placeholder:"Auto"})]})]})]})]})})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>Ke(),disabled:!d.trim(),children:[t.jsx(Oi,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),m.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(jt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:x?"AI is thinking...":"Generating next question..."}),A&&t.jsxs("div",{className:"planning-elapsed",children:["Thinking… (",H,"s)"]}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>F(!R),type:"button",children:R?"Hide thinking":"Show thinking"}),t.jsx("div",{className:"planning-loading-actions",children:t.jsxs("button",{className:"btn planning-stop-btn",type:"button",onClick:()=>void W(),children:[t.jsx(Xy,{size:14}),t.jsx("span",{className:"icon-ml-6",children:"Stop"})]})}),R&&x&&t.jsx("div",{className:"planning-thinking-output",ref:ge,children:t.jsx("pre",{children:x})})]})]}),m.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[v.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(bi,{entries:v}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:m.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void Y(),disabled:K,children:[K?t.jsx(jt,{size:14,className:"spin"}):t.jsx(ps,{size:14}),t.jsx("span",{className:"icon-ml-6",children:K?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Jt,disabled:K,children:"Dismiss"})]})]})]})}),m.type==="creating"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(jt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:"Creating tasks..."})]}),m.type==="question"&&m.session.currentQuestion&&t.jsx("div",{className:"planning-question",children:t.jsx(w4,{question:m.session.currentQuestion,progress:yn(),historyEntries:v,onSubmit:tn,onBack:g.length>0?zt:void 0})}),m.type==="summary"&&y&&t.jsx(k4,{summary:y,historyEntries:v,onSummaryChange:S,tasks:r,onCreateTask:_e,onBreakIntoTasks:ut,onRefine:()=>{Ne()},isLoading:!1}),m.type==="breakdown"&&t.jsx(N4,{subtasks:m.subtasks,isLoading:!1,onUpdateSubtasks:de=>h({...m,subtasks:de,dirty:!0}),onCreateTasks:At,onBack:()=>{const nt={sessionId:m.sessionId,currentQuestion:null,summary:y??null};y&&h({type:"summary",session:nt,summary:y})}})]}),ye&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(yc,{size:16}),t.jsx("span",{children:Dn?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Dn&&t.jsx("button",{type:"button",onClick:()=>{je()},disabled:ne,className:"btn btn-primary session-lock-take-control",children:ne?"Taking control...":"Take Control"})]})})]})]})}):null}function w4({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(bi,{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:w=>{const v=w.target.checked?[...g,p.id]:g.filter(b=>b!==p.id);l({[e.id]:v})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:p.label}),p.description&&t.jsx("span",{className:"planning-option-desc",children:p.description})]})]},p.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!0?"selected":""}`,onClick:()=>l({[e.id]:!0}),children:[t.jsx(Xn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!1?"selected":""}`,onClick:()=>l({[e.id]:!1}),children:[t.jsx(mn,{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(Ga,{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(Uo,{size:16,className:"icon-ml-4"})]})]})]})}function k4({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=Va(e.priority),p=g=>{const w=m.includes(g)?m.filter(v=>v!==g):[...m,g];h(w),s({...e,suggestedDependencies:w})};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(fi,{summary:"Show user Q&A",className:"planning-summary-qa-disclosure",children:[t.jsx(bi,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Xn,{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:wa.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,w)=>t.jsx("li",{children:g},w))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:l,disabled:c,children:[t.jsx(Ga,{size:16,className:"icon-mr-4"}),"Refine Further"]}),t.jsxs("div",{className:"planning-summary-actions-right",children:[t.jsx("button",{className:"btn",onClick:r,disabled:c,children:c?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:16,className:"spin icon-mr-8"}),"Creating..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Xn,{size:16,className:"icon-mr-8"}),"Create Single Task"]})}),t.jsx("button",{className:"btn btn-primary",onClick:o,disabled:c,title:"Break the plan into multiple tasks with dependencies",children:c?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):t.jsxs(t.Fragment,{children:[t.jsx(vc,{size:16,className:"icon-mr-8"}),"Break into Tasks"]})})]})]})]})}function Of(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 j4(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",priority:Ps,dependsOn:[]}}function N4({subtasks:e,isLoading:n,onUpdateSubtasks:s,onCreateTasks:a,onBack:r}){const[o,l]=i.useState(null),[c,d]=i.useState(null),[u,m]=i.useState(null),h=i.useRef([]),f=i.useMemo(()=>e.length===0||e.some(x=>!x.title.trim())?!0:Of(e),[e]),p=i.useCallback((x,N)=>{s(e.map(R=>R.id===x?{...R,...N}:R))},[e,s]),g=i.useCallback(()=>{s([...e,j4(e.length+1)])},[e,s]),w=i.useCallback(x=>{s(e.filter(N=>N.id!==x).map(N=>({...N,dependsOn:N.dependsOn.filter(R=>R!==x)})))},[e,s]),v=i.useCallback((x,N)=>{if(N<0||N>=e.length)return;const R=[...e],[F]=R.splice(x,1);R.splice(N,0,F),s(R)},[e,s]),b=i.useCallback(x=>N=>{l(x),N.dataTransfer.setData("text/plain",x),N.dataTransfer.effectAllowed="move"},[]),y=i.useCallback(()=>{l(null),d(null),m(null)},[]),S=i.useCallback(x=>N=>{if(N.preventDefault(),x===o)return;const R=N.currentTarget.getBoundingClientRect(),F=R.top+R.height/2,E=N.clientY<F?"before":"after";d(x),m(E)},[o]),j=i.useCallback(x=>N=>{N.preventDefault();const R=N.dataTransfer.getData("text/plain");if(!R||R===x){y();return}const F=e.findIndex(A=>A.id===R),E=e.findIndex(A=>A.id===x);if(F===-1||E===-1){y();return}const _=[...e],[K]=_.splice(F,1);let U=E;u==="after"&&F<E&&U--,u==="after"&&U++,_.splice(U,0,K),s(_),y()},[e,u,s,y]),C=i.useCallback(x=>{const N=x.currentTarget.getBoundingClientRect(),R=x.clientX,F=x.clientY;(R<N.left||R>N.right||F<N.top||F>N.bottom)&&(d(null),m(null))},[]);return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(vc,{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((x,N)=>{const R=o===x.id,F=c===x.id,E=["task-detail-section","subtask-item",R?"subtask-item-dragging":"",F?"subtask-item-drop-target":"",F&&u==="before"?"subtask-item-drop-before":"",F&&u==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:E,"data-testid":`subtask-item-${N}`,draggable:!n,onDragStart:b(x.id),onDragEnd:y,onDragOver:S(x.id),onDrop:j(x.id),onDragLeave:C,children:[t.jsxs("div",{className:"detail-title-row subtask-item-header subtask-item-header--between",children:[t.jsxs("div",{className:"subtask-drag-handle",title:"Drag to reorder",children:[t.jsx(xc,{size:16}),t.jsx("strong",{children:x.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>v(N,N-1),disabled:n||N===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(La,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>v(N,N+1),disabled:n||N===e.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(Bo,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>w(x.id),disabled:n,children:[t.jsx(Tn,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:_=>{h.current[N]=_},value:x.title,onChange:_=>p(x.id,{title:_.target.value}),onKeyDown:_=>{_.key==="Enter"&&(_.preventDefault(),N<e.length-1&&h.current[N+1]?.focus())},disabled:n})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:x.description,onChange:_=>p(x.id,{description:_.target.value}),disabled:n})]}),t.jsxs("div",{className:"planning-summary-meta-row",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`${x.id}-size`,children:"Size"}),t.jsxs("select",{id:`${x.id}-size`,className:"planning-size-select",value:x.suggestedSize,onChange:_=>p(x.id,{suggestedSize:_.target.value}),disabled:n,children:[t.jsx("option",{value:"S",children:"S"}),t.jsx("option",{value:"M",children:"M"}),t.jsx("option",{value:"L",children:"L"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`${x.id}-priority`,children:"Priority"}),t.jsx("select",{id:`${x.id}-priority`,className:"planning-size-select",value:Va(x.priority),onChange:_=>p(x.id,{priority:_.target.value}),disabled:n,children:wa.map(_=>t.jsx("option",{value:_,children:_[0].toUpperCase()+_.slice(1)},_))})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[e.slice(0,N).filter(_=>_.id!==x.id).map(_=>{const K=x.dependsOn.includes(_.id);return t.jsxs("label",{className:`planning-dep-chip ${K?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:K,onChange:()=>{const U=K?x.dependsOn.filter(A=>A!==_.id):[...x.dependsOn,_.id];p(x.id,{dependsOn:U})},disabled:n}),t.jsx("span",{className:"planning-dep-id",children:_.id}),t.jsx("span",{className:"planning-dep-title",children:_.title||"Untitled"})]},_.id)}),N===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),N>0&&e.slice(0,N).filter(_=>_.id!==x.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},x.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:g,disabled:n,children:[t.jsx($n,{size:16,className:"icon-mr-6"})," Add subtask"]}),Of(e)&&t.jsx("div",{className:"form-error planning-error",children:"Dependencies contain a cycle. Remove circular references before creating tasks."})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:n,children:[t.jsx(Ga,{size:16,className:"icon-mr-4"}),"Back to Summary"]}),t.jsx("button",{className:"btn btn-primary",onClick:a,disabled:n||f,children:n?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]})}function S4({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(pk,{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,w=f.archived===!0,v=f.status==="complete"||f.status==="error";return t.jsxs("div",{className:`planning-sidebar-item ${p?"selected":""} ${g?"pending-delete":""} ${w?"archived":""}`,children:[t.jsxs("button",{type:"button",className:"planning-sidebar-item-button",onClick:()=>c(f.id),children:[t.jsx(C4,{status:f.status}),t.jsxs("span",{className:"planning-sidebar-item-body",children:[t.jsx("span",{className:"planning-sidebar-item-title",children:f.status==="draft"&&(!f.title||f.title==="New planning session")?f.preview??"New planning session":f.title||"Untitled session"}),t.jsxs("span",{className:"planning-sidebar-item-meta",children:[t.jsx(E4,{status:f.status}),t.jsx("span",{"aria-hidden":!0,children:" · "}),t.jsx("span",{children:_4(f.updatedAt)})]})]})]}),g?t.jsxs("div",{className:"planning-sidebar-confirm",children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>m(f.id),children:"Delete"}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,children:"Cancel"})]}):t.jsxs("div",{className:"planning-sidebar-item-actions",children:[v&&t.jsx("button",{type:"button",className:"planning-sidebar-item-archive",onClick:b=>{b.stopPropagation(),l(f.id)},"aria-label":w?"Unarchive session":"Archive session",title:w?"Unarchive session":"Archive session",children:w?t.jsx(_y,{size:14}):t.jsx(zo,{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(Tn,{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 C4({status:e}){switch(e){case"generating":return t.jsx(jt,{size:14,className:"spin planning-sidebar-status-icon planning-sidebar-status-generating"});case"awaiting_input":return t.jsx(tu,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-awaiting"});case"complete":return t.jsx(Xn,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-complete"});case"error":return t.jsx(Vs,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-error"});default:return t.jsx(ta,{size:14,className:"planning-sidebar-status-icon"})}}function E4({status:e}){switch(e){case"generating":return t.jsx("span",{children:"Generating"});case"awaiting_input":return t.jsx("span",{children:"Needs input"});case"complete":return t.jsx("span",{children:"Complete"});case"error":return t.jsx("span",{children:"Error"});default:return t.jsx("span",{children:e})}}function _4(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 M4(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function Ff(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 A4({isOpen:e,onClose:n,initialDescription:s,onTasksCreated:a,parentTaskId:r,projectId:o,resumeSessionId:l}){const c=oi();Mi(e);const{keyboardOverlap:d,viewportHeight:u,viewportOffsetTop:m,keyboardOpen:h}=aa({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"}),[w,v]=i.useState([]),[b,y]=i.useState([]),[S,j]=i.useState(""),[C,x]=i.useState(!0),[N,R]=i.useState(!1),[F,E]=i.useState(!1),[_,K]=i.useState(s),[U,A]=i.useState(null),[T,H]=i.useState(!1),[Q,se]=i.useState("project-default"),[O,M]=i.useState(""),[D,$]=i.useState(""),[k,X]=i.useState("shared"),[le,ke]=i.useState(null),[He,ye]=i.useState(null),[je,ne]=i.useState(null),fe=i.useRef(null),Z=i.useRef([]),re=i.useRef(!1),q=i.useRef(null),L=p.type==="generating"||p.type==="editing"||p.type==="creating"||p.type==="error"?p.sessionId:null,xe=i.useMemo(()=>Ja(),[]),{isLockedByOther:he,takeControl:B,isLoading:pe}=Tc(e?L:null),{activeTabMap:ze,broadcastUpdate:ae,broadcastCompleted:Ve,broadcastLock:Te,broadcastUnlock:rt,broadcastHeartbeat:Be}=Wr(),ce=i.useMemo(()=>w.length===0||w.some(Ie=>!Ie.title.trim())||(Q==="existing"||Q==="custom-new")&&!O.trim()?!0:Ff(w),[Q,O,w]),Re=p.type==="generating"||p.type==="editing"||p.type==="error",Le=L?ze.get(L):null,{confirm:ct}=li(),Ue=Le&&Le.tabId!==xe,ue=!!(Ue&&!Le.stale),oe=he&&(!Ue||Le.stale),Ee=i.useCallback(()=>{_&&w$(_,o),fe.current?.close(),fe.current=null,g({type:"initial"}),v([]),y([]),j(""),x(!0),R(!1),E(!1),A(null),H(!1),se("project-default"),M(""),$(""),X("shared"),re.current=!1},[_,o]),ft=i.useCallback(()=>{fe.current?.close(),fe.current=null,n()},[n]),ht=i.useCallback(async()=>{if(!((T||p.type==="editing"||p.type==="creating")&&!await ct({title:"Discard Changes",message:"Close subtask breakdown? Unsaved changes will be lost.",danger:!0}))){if(L)try{await bb(L,o,xe)}catch{}Ee(),n()}},[T,n,Ee,L,xe,p.type,o,ct]),tt=i.useCallback(Ie=>{fe.current?.close(),fe.current=ZS(Ie,o,{onThinking:ge=>{j(st=>st+ge),ae({sessionId:Ie,status:"generating",needsInput:!1,owningTabId:xe,type:"subtask",title:_.trim()||void 0,projectId:o??null})},onSubtasks:ge=>{R(!1),E(!1),Id(o),v(ge),g({type:"editing",sessionId:Ie}),H(!1),ae({sessionId:Ie,status:"awaiting_input",needsInput:!0,owningTabId:xe,type:"subtask",title:_.trim()||void 0,projectId:o??null})},onError:ge=>{const st=ge||"Session failed while contacting the AI.";R(!1),E(!1),A(null),g({type:"error",sessionId:Ie,errorMessage:st}),ae({sessionId:Ie,status:"error",needsInput:!1,owningTabId:xe,type:"subtask",title:_.trim()||void 0,projectId:o??null}),Ve({sessionId:Ie,status:"error"})},onComplete:()=>{Ve({sessionId:Ie,status:"complete"})},onConnectionStateChange:ge=>{R(ge==="reconnecting")}})},[Ve,ae,_,o,xe]),xt=i.useCallback(async()=>{if(_.trim()){A(null),y([]),j(""),R(!1);try{const{sessionId:Ie}=await YS(_.trim(),o);g({type:"generating",sessionId:Ie}),tt(Ie)}catch(Ie){A(Se(Ie)||"Failed to start subtask breakdown"),g({type:"initial"})}}},[tt,_,o]);i.useEffect(()=>{if(!e){Ee();return}if(e&&s&&!re.current)K(s),re.current=!0,xt();else if(e&&!s&&!re.current){const Ie=k$(o);Ie&&K(Ie)}},[e,s,xt,Ee]),i.useEffect(()=>{!e||!l||p.type!=="initial"||(async()=>{try{const Ie=await Di(l);if(!Ie)return;const ge=Mr(Ie.conversationHistory);if(y(ge),Ie.status==="generating"||Ie.status==="awaiting_input")j(Ie.thinkingOutput??""),g({type:"generating",sessionId:l}),tt(l);else if(Ie.status==="complete"&&Ie.result){Id(o);const st=JSON.parse(Ie.result);v(st),g({type:"editing",sessionId:l})}else Ie.status==="error"&&(A(null),g({type:"error",sessionId:l,errorMessage:Ie.error??"Session encountered an error"}))}catch(Ie){A(Se(Ie)||"Failed to resume session")}})()},[tt,e,l,p.type,o]),i.useEffect(()=>{if(!e){q.current&&(rt(q.current,xe),q.current=null);return}if(L&&q.current!==L){q.current&&rt(q.current,xe),Te(L,xe),q.current=L;return}!L&&q.current&&(rt(q.current,xe),q.current=null)},[Te,rt,e,L,xe]),i.useEffect(()=>{if(!e||!L||q.current!==L)return;Be(xe);const Ie=setInterval(()=>{Be(xe)},3e4);return()=>{clearInterval(Ie)}},[Be,e,L,xe]),i.useEffect(()=>()=>{fe.current?.close(),q.current&&(rt(q.current,xe),q.current=null)},[rt,xe]),i.useEffect(()=>{if(!e)return;const Ie=ge=>{ge.key==="Escape"&&(ge.preventDefault(),ht())};return document.addEventListener("keydown",Ie),()=>document.removeEventListener("keydown",Ie)},[e,ht]);const Me=i.useCallback((Ie,ge)=>{v(st=>st.map(yt=>yt.id===Ie?{...yt,...ge}:yt)),H(!0)},[]),Ye=i.useCallback(()=>{v(Ie=>[...Ie,M4(Ie.length+1)]),H(!0)},[]),dt=i.useCallback(Ie=>{v(ge=>ge.filter(st=>st.id!==Ie).map(st=>({...st,dependsOn:st.dependsOn.filter(yt=>yt!==Ie)}))),H(!0)},[]),wt=i.useCallback(Ie=>ge=>{ke(Ie),ge.dataTransfer.setData("text/plain",Ie),ge.dataTransfer.effectAllowed="move"},[]),St=i.useCallback(()=>{ke(null),ye(null),ne(null)},[]),Fe=i.useCallback(Ie=>ge=>{if(ge.preventDefault(),Ie===le)return;const st=ge.currentTarget.getBoundingClientRect(),yt=st.top+st.height/2,pt=ge.clientY<yt?"before":"after";ye(Ie),ne(pt)},[le]),J=i.useCallback(Ie=>ge=>{ge.preventDefault();const st=ge.dataTransfer.getData("text/plain");if(!st||st===Ie){ke(null),ye(null),ne(null);return}v(yt=>{const pt=yt.findIndex(on=>on.id===st),vt=yt.findIndex(on=>on.id===Ie);if(pt===-1||vt===-1)return yt;const Ut=[...yt],[Dt]=Ut.splice(pt,1);let nn=vt;return je==="after"&&pt<vt&&nn--,je==="after"&&nn++,Ut.splice(nn,0,Dt),Ut}),H(!0),ke(null),ye(null),ne(null)},[je]),me=i.useCallback(Ie=>{const ge=Ie.currentTarget.getBoundingClientRect(),st=Ie.clientX,yt=Ie.clientY;(st<ge.left||st>ge.right||yt<ge.top||yt>ge.bottom)&&(ye(null),ne(null))},[]),Ze=i.useCallback((Ie,ge)=>{ge<0||ge>=w.length||(v(st=>{const yt=[...st],[pt]=yt.splice(Ie,1);return yt.splice(ge,0,pt),yt}),H(!0))},[w.length]),be=i.useCallback(Ie=>{Z.current[Ie+1]?.focus()},[]),gt=i.useCallback(async()=>{if(!(!L||ce)){A(null),g({type:"creating",sessionId:L});try{const Ie=await e1(L,w,r,o,{branchSelection:{mode:Q,...Q==="existing"||Q==="custom-new"?{branchName:O}:{},...D.trim()?{baseBranch:D.trim()}:{}},branchAssignment:{mode:k}});a(Ie.tasks),Ee(),n()}catch(Ie){A(Se(Ie)||"Failed to create tasks"),g({type:"editing",sessionId:L})}}},[D,k,Q,O,ce,n,a,r,o,Ee,L,w]),$t=i.useCallback(async()=>{if(p.type!=="error")return;const Ie=p.sessionId;A(null),E(!0),j(""),g({type:"generating",sessionId:Ie}),tt(Ie);try{await QS(Ie,o,xe)}catch(ge){let st=ge;if((Se(ge)||"").includes("not in an error state"))try{const pt=await Di(Ie);if(!pt)throw new Error("Failed to refresh subtask session.");if(y(Mr(pt.conversationHistory)),pt.status==="generating"||pt.status==="awaiting_input")j(pt.thinkingOutput??""),g({type:"generating",sessionId:pt.id}),fe.current?.isConnected()||tt(pt.id);else if(pt.status==="complete"){if(!pt.result)throw new Error("Subtask session is complete but has no result.");Id(o);const vt=JSON.parse(pt.result);v(vt),g({type:"editing",sessionId:pt.id}),H(!1)}else pt.status==="error"&&g({type:"error",sessionId:pt.id,errorMessage:pt.error??"Retry failed. Please try again."});R(!1);return}catch(pt){st=pt}fe.current?.close(),fe.current=null,g({type:"error",sessionId:Ie,errorMessage:Se(st)||"Retry failed. Please try again."}),R(!1)}finally{E(!1)}},[tt,o,xe,p]);return e?t.jsx("div",{className:"modal-overlay open",onClick:Ie=>Ie.target===Ie.currentTarget&&void ht(),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(vc,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Subtask Breakdown"})]}),t.jsxs("div",{className:"modal-header-actions",children:[Re&&t.jsx("button",{className:"modal-send-to-background",onClick:ft,title:"Send to background","aria-label":"Send to background",children:t.jsx(qo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:()=>void ht(),"aria-label":"Close",children:t.jsx(mn,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[U&&t.jsx("div",{className:"form-error planning-error",children:U}),N&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),ue&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),p.type==="initial"&&t.jsx("div",{className:"planning-initial",children:t.jsxs("div",{className:"planning-view-scroll",children:[t.jsx("p",{className:"text-muted",children:"Preparing to break this task into subtasks."}),t.jsx("pre",{className:"planning-thinking-output",children:_})]})}),p.type==="generating"&&t.jsxs("div",{className:"planning-loading",children:[b.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(bi,{entries:b,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsx(jt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:"AI is generating subtasks..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>x(!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(bi,{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 $t(),disabled:F,children:[F?t.jsx(jt,{size:14,className:"spin"}):t.jsx(ps,{size:14}),t.jsx("span",{className:"icon-ml-6",children:F?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:()=>void ht(),disabled:F,children:"Cancel"})]})]})]})}),(p.type==="editing"||p.type==="creating")&&t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[b.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(bi,{entries:b}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Xn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Review your subtasks"}),t.jsx("p",{className:"text-muted",children:"Edit titles, descriptions, sizes, and dependencies before creating all tasks at once."})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"task-detail-section",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Branch strategy"}),t.jsxs("select",{value:Q,onChange:Ie=>se(Ie.target.value),disabled:p.type==="creating",children:[t.jsx("option",{value:"project-default",children:"Use project/default branch"}),t.jsx("option",{value:"auto-new",children:"Create auto-named branch per task"}),t.jsx("option",{value:"existing",children:"Use existing branch"}),t.jsx("option",{value:"custom-new",children:"Create custom new branch"})]})]}),(Q==="existing"||Q==="custom-new")&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Branch name"}),t.jsx("input",{value:O,onChange:Ie=>M(Ie.target.value),disabled:p.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Merge target / base branch (optional)"}),t.jsx("input",{value:D,onChange:Ie=>$(Ie.target.value),disabled:p.type==="creating",placeholder:"main"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Planning branch mode"}),t.jsxs("select",{value:k,onChange:Ie=>X(Ie.target.value),disabled:p.type==="creating",children:[t.jsx("option",{value:"shared",children:"Shared branch for all subtasks"}),t.jsx("option",{value:"per-task-derived",children:"Per-task branch derived from planning branch"})]})]})]}),w.map((Ie,ge)=>{const st=le===Ie.id,yt=He===Ie.id,pt=["task-detail-section","subtask-item",st?"subtask-item-dragging":"",yt?"subtask-item-drop-target":"",yt&&je==="before"?"subtask-item-drop-before":"",yt&&je==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:pt,"data-testid":`subtask-item-${ge}`,draggable:p.type!=="creating",onDragStart:wt(Ie.id),onDragEnd:St,onDragOver:Fe(Ie.id),onDrop:J(Ie.id),onDragLeave:me,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(xc,{size:16}),t.jsx("strong",{children:Ie.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ze(ge,ge-1),disabled:p.type==="creating"||ge===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(La,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ze(ge,ge+1),disabled:p.type==="creating"||ge===w.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(Bo,{})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>dt(Ie.id),disabled:p.type==="creating",children:[t.jsx(Tn,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:vt=>{Z.current[ge]=vt},value:Ie.title,onChange:vt=>Me(Ie.id,{title:vt.target.value}),onKeyDown:vt=>{vt.key==="Enter"&&(vt.preventDefault(),be(ge))},disabled:p.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:8,value:Ie.description,onChange:vt=>Me(Ie.id,{description:vt.target.value}),disabled:p.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:Ie.suggestedSize,onChange:vt=>Me(Ie.id,{suggestedSize:vt.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:[w.slice(0,ge).filter(vt=>vt.id!==Ie.id).map(vt=>{const Ut=Ie.dependsOn.includes(vt.id);return t.jsxs("label",{className:`planning-dep-chip ${Ut?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:Ut,onChange:()=>{const Dt=Ut?Ie.dependsOn.filter(nn=>nn!==vt.id):[...Ie.dependsOn,vt.id];Me(Ie.id,{dependsOn:Dt})},disabled:p.type==="creating"}),t.jsx("span",{className:"planning-dep-id",children:vt.id}),t.jsx("span",{className:"planning-dep-title",children:vt.title||"Untitled"})]},vt.id)}),ge===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),ge>0&&w.slice(0,ge).filter(vt=>vt.id!==Ie.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},Ie.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:Ye,disabled:p.type==="creating",children:[t.jsx($n,{size:16,className:"icon-mr-6"})," Add subtask"]}),Ff(w)&&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 ht(),disabled:p.type==="creating",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:()=>void gt(),disabled:p.type==="creating"||ce,children:p.type==="creating"?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]}),he&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(yc,{size:16}),t.jsx("span",{children:oe?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),oe&&t.jsx("button",{type:"button",onClick:()=>{B()},disabled:pe,className:"btn btn-primary session-lock-take-control",children:pe?"Taking control...":"Take Control"})]})})]})]})}):null}const R4=5,I4=1e3,T4=45e3;function Al(){return{scrollback:null,connected:null,data:[]}}function P4(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),w=i.useRef(new Set),v=i.useRef(new Set),b=i.useRef(new Set),y=i.useRef(Al()),S=i.useCallback(A=>{p.current.add(A);const T=y.current;return T.data.length>0&&(T.data.forEach(H=>A(H)),T.data=[]),()=>p.current.delete(A)},[]),j=i.useCallback(A=>(g.current.add(A),()=>g.current.delete(A)),[]),C=i.useCallback(A=>{w.current.add(A);const T=y.current;return T.connected&&(A(T.connected),T.connected=null),()=>w.current.delete(A)},[]),x=i.useCallback(A=>{v.current.add(A);const T=y.current;return T.scrollback&&(A(T.scrollback),T.scrollback=null),()=>v.current.delete(A)},[]),N=i.useCallback(A=>(b.current.add(A),()=>b.current.delete(A)),[]),R=i.useCallback(A=>{const T=d.current;T?.readyState===WebSocket.OPEN&&T.send(JSON.stringify({type:"input",data:A}))},[]),F=i.useCallback((A,T)=>{const H=d.current;H?.readyState===WebSocket.OPEN&&H.send(JSON.stringify({type:"resize",cols:A,rows:T}))},[]),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=Al()},[]),_=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=Al()},[]),K=i.useCallback(()=>{if(!e){a("disconnected");return}if(d.current?.readyState===WebSocket.OPEN)return;d.current&&(f.current=!0,d.current.onopen=null,d.current.onmessage=null,d.current.onclose=null,d.current.onerror=null,d.current.close(),d.current=null),f.current=!1,a("connecting");const A=r.current;let H=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(e)}`;n&&(H+=`&projectId=${encodeURIComponent(n)}`);const Q=new WebSocket(Fi(H));d.current=Q,Q.onopen=()=>{if(r.current!==A){Q.close();return}y.current=Al(),a("connected"),u.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===A&&Q.readyState===WebSocket.OPEN&&Q.send(JSON.stringify({type:"ping"}))},T4)},Q.onmessage=se=>{if(r.current===A)try{const O=JSON.parse(se.data),M=y.current;switch(O.type){case"data":O.data&&(p.current.size===0&&M.data.push(O.data),p.current.forEach(D=>D(O.data)));break;case"scrollback":O.data&&(M.scrollback=O.data,v.current.forEach(D=>D(O.data)));break;case"connected":O.shell&&O.cwd&&(M.connected={shell:O.shell,cwd:O.cwd},w.current.forEach(D=>D({shell:O.shell,cwd:O.cwd})));break;case"exit":O.exitCode!==void 0&&g.current.forEach(D=>D(O.exitCode));break;case"ping":Q.readyState===WebSocket.OPEN&&Q.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},Q.onclose=se=>{if(r.current!==A)return;if(d.current=null,h.current&&(clearInterval(h.current),h.current=null),f.current){a("disconnected");return}if(se.code===4e3||se.code===4004){a("disconnected"),se.code===4004&&b.current.forEach(D=>D());return}if(u.current++,u.current>R4){a("disconnected");return}const O=I4*Math.pow(2,u.current-1);a("reconnecting");const M=r.current;m.current=setTimeout(()=>{r.current===M&&(f.current||K())},Math.min(O,16e3))},Q.onerror=()=>{}},[e,n]),U=i.useCallback(()=>{u.current=0,_(),K()},[_,K]);return i.useEffect(()=>(c&&(E(),u.current=0,a("disconnected")),e?K():a("disconnected"),_),[e,n,c,K,_,E]),{connectionStatus:s,sendInput:R,resize:F,onData:S,onExit:j,onConnect:C,onScrollback:x,reconnect:U,onSessionInvalid:N}}const Ev="kb-terminal-tabs",$4=15e3,D4=15e3;function zf(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function Bf(e){if(typeof window>"u")return[];try{const n=Gn(Ev,e);if(n)return JSON.parse(n)}catch{}return[]}function Bd(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function Uf(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 L4(e){const[n,s]=i.useState(()=>Bf(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(Bf(e)),r(!1),l(!0),d(null)},[e]),i.useEffect(()=>{try{fs(Ev,JSON.stringify(n),e)}catch{}},[e,n]),i.useEffect(()=>{let C=!1;const x=h.current;return(async()=>{if(!C)try{const R=await Uf(HN(e),$4,"listTerminalSessions");if(C||x!==h.current)return;const F=new Set(R.map(E=>E.id));l(!0),s(E=>{if(C||x!==h.current)return E;const K=E.map(T=>({...T,_verified:F.has(T.sessionId)})).filter(T=>T._verified);if(K.length===0)return[];const U=K.map(({_verified:T,...H})=>H);return U.find(T=>T.isActive)?U:U.map((T,H)=>({...T,isActive:H===0}))}),r(!0)}catch(R){if(C||x!==h.current)return;const F=Bd(R);F||console.warn("Failed to validate terminal sessions with server:",R),l(!F),r(!0)}})(),()=>{C=!0}},[e]),i.useEffect(()=>{if(n.length===0&&a&&o){const C=h.current,x=setTimeout(()=>{Uf(il(void 0,void 0,void 0,e),D4,"createTerminalSession").then(N=>{if(C!==h.current)return;const R={id:zf(),sessionId:N.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(F=>F.length>0?F:[...F.map(_=>({..._,isActive:!1})),R]),d(null)}).catch(N=>{if(C!==h.current)return;Bd(N)||console.error(N);const R=N instanceof Error?N.message:typeof N=="string"?N:"Failed to create terminal session";d(R)})},0);return()=>clearTimeout(x)}},[a,o,n.length,u]);const f=i.useCallback(async()=>{const C=await il(void 0,void 0,void 0,e),x={id:zf(),sessionId:C.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(N=>[...N.map(F=>({...F,isActive:!1})),x]),x},[n.length]),p=i.useCallback(async()=>f(),[f]),g=i.useCallback(C=>{s(x=>{const N=x.find(_=>_.id===C);if(!N)return x;Wm(N.sessionId,e).catch(_=>{console.warn(`Failed to kill terminal session ${N.sessionId}:`,_)});const R=x.findIndex(_=>_.id===C),F=N.isActive,E=x.filter(_=>_.id!==C);if(E.length===0)return[];if(F){const _=Math.min(R,E.length-1);return E.map((K,U)=>({...K,isActive:U===_}))}return E})},[]),w=i.useCallback(C=>{s(x=>{let N=!1;const R=x.map(F=>F.id===C?(N=!0,{...F,isActive:!0}):{...F,isActive:!1});return N?R:x})},[]),v=i.useCallback((C,x)=>{s(N=>N.map(R=>R.id===C?{...R,title:x}:R))},[]),b=i.useCallback(async()=>{s(N=>{const R=N.find(F=>F.isActive);return R&&Wm(R.sessionId,e).catch(F=>{console.warn(`Failed to kill old session ${R.sessionId}:`,F)}),N});const C=n.find(N=>N.isActive);if(!C)return;const x=await il(void 0,void 0,void 0,e);s(N=>N.map(R=>R.id===C.id?{...R,sessionId:x.sessionId}:R))},[n]),y=i.useCallback(async()=>{const C=n.find(x=>x.isActive);if(C)try{const x=await il(void 0,void 0,void 0,e);s(N=>N.map(R=>R.id===C.id?{...R,sessionId:x.sessionId}:R)),d(null)}catch(x){Bd(x)||console.error(x);const N=x instanceof Error?x.message:typeof x=="string"?x:"Failed to create terminal session";d(N)}},[n]),S=n.find(C=>C.isActive)??null,j=i.useCallback(()=>{d(null),h.current+=1,m(C=>C+1)},[]);return{tabs:n,activeTab:S,isReady:a,bootstrapError:c,createTab:p,closeTab:g,setActiveTab:w,updateTabTitle:v,restartActiveTab:b,retryBootstrap:j,replaceActiveTabSession:y}}const O4=1e4,F4=[500,1500,3e3],_v="kb-terminal-font-size",jo=14,z4=8,B4=32,U4='"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 q4(e){return`\x1B${e}`}const V4=[{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 No(e){return Math.min(B4,Math.max(z4,e))}function W4(){if(typeof window>"u")return jo;try{const e=window.localStorage.getItem(_v);if(!e)return jo;const n=Number.parseInt(e,10);return Number.isFinite(n)?No(n):jo}catch{return jo}}function G4(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 K4(e){return new Promise(n=>setTimeout(n,e))}async function J4(e,n=F4){let s;for(let a=0;a<=n.length;a+=1)try{return await e()}catch(r){if(!G4(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 K4(o)}throw s??new Error("Dynamic import failed")}function Hf(){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=Q4()-e.offsetTop-e.height;return a>=30&&a>80?a:0}let Ud=null;function Q4(){return Ud===null&&(Ud=window.innerHeight),Ud}function X4({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,w]=i.useState(0),[v,b]=i.useState(null),[y,S]=i.useState(()=>W4()),[j,C]=i.useState(!1),[x,N]=i.useState(null),R=i.useRef(null),F=i.useRef(null),E=i.useRef(!1);zi(F,e,"fusion:terminal-modal-size");const _=i.useRef(null),K=i.useRef(null),U=i.useRef(!1),A=i.useRef(!1),T=i.useRef(null),H=i.useRef(()=>{}),Q=i.useRef(null),se=i.useRef(0),O=i.useRef(y),M=i.useRef(null),D=i.useRef(a);se.current=g,O.current=y;const $=i.useCallback(Me=>{if(Me&&A.current!==Me)return;const Ye=K.current,dt=_.current,wt=T.current;if(!(!Ye||!dt)&&!(Me&&A.current!==Me))try{Ye.fit(),wt&&wt(dt.cols,dt.rows)}catch{}},[]);i.useEffect(()=>{e&&p(Me=>Me+1)},[e]),i.useEffect(()=>{if(!e||!Hf())return;const Me=window.visualViewport;if(!Me)return;const Ye=()=>{const dt=Y4();w(dt),b(Me.height),dt>0&&F.current?.scrollIntoView&&F.current.scrollIntoView({block:"end",behavior:"smooth"}),M.current!==null&&(cancelAnimationFrame(M.current),M.current=null);const wt=typeof A.current=="string"?A.current:void 0;M.current=requestAnimationFrame(()=>{M.current=null,$(wt)})};return Ye(),Me.addEventListener("resize",Ye),Me.addEventListener("scroll",Ye),()=>{Me.removeEventListener("resize",Ye),Me.removeEventListener("scroll",Ye),M.current!==null&&(cancelAnimationFrame(M.current),M.current=null),w(0),b(null)}},[$,e]),i.useEffect(()=>{if(!e)return;const Me=F.current;if(!Me||typeof ResizeObserver>"u")return;let Ye=null;const dt=new ResizeObserver(()=>{Ye!==null&&cancelAnimationFrame(Ye),Ye=requestAnimationFrame(()=>{Ye=null;const wt=typeof A.current=="string"?A.current:void 0;$(wt)})});return dt.observe(Me),()=>{dt.disconnect(),Ye!==null&&cancelAnimationFrame(Ye)}},[$,e]);const{tabs:k,activeTab:X,isReady:le,bootstrapError:ke,createTab:He,closeTab:ye,setActiveTab:je,updateTabTitle:ne,restartActiveTab:fe,retryBootstrap:Z,replaceActiveTabSession:re}=L4(a),{connectionStatus:q,sendInput:L,resize:xe,onData:he,onConnect:B,onExit:pe,onScrollback:ze,reconnect:ae,onSessionInvalid:Ve}=P4(X?.sessionId??null,a);T.current=xe,H.current=L,i.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(_v,String(y))}catch{}},[y]);const Te=i.useCallback(()=>{const Me=_.current;if(Me)try{K.current?.fit(),xe(Me.cols,Me.rows)}catch{}},[xe]);i.useEffect(()=>{if(!e||!le)return;const Me=X?.sessionId;if(!Me)return;const Ye=D.current!==a;if(Ye&&(D.current=a),A.current===Me&&_.current&&!Ye)return;_.current&&(A.current!==Me||Ye)&&(_.current.dispose(),_.current=null,K.current=null,A.current=!1,Q.current&&(window.removeEventListener("resize",Q.current),Q.current=null),u(!1),h(null));let dt=!0,wt;return(async()=>{const Fe=J4(()=>Promise.all([En(()=>import("./vendor-xterm-DzcZoU0P.js").then(be=>be.x),__vite__mapDeps([5,1,6])),En(()=>import("./addon-fit-C7jRorKK.js").then(be=>be.a),__vite__mapDeps([8,1])),En(()=>import("./addon-web-links-CkJwd4cQ.js").then(be=>be.a),__vite__mapDeps([9,1]))])),J=new Promise((be,gt)=>{wt=setTimeout(()=>{gt(new Error("xterm initialization timed out"))},O4)});let me,Ze;try{const[{Terminal:be},{FitAddon:gt},{WebLinksAddon:$t}]=await Promise.race([Fe,J]);if(!dt||!R.current||_.current)return;me=new be({cursorBlink:!0,cursorStyle:"block",fontSize:O.current,fontFamily:U4,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}),Ze=new gt,me.loadAddon(Ze);const Ie=new $t;if(me.loadAddon(Ie),!Hf())try{const{WebglAddon:yt}=await En(async()=>{const{WebglAddon:vt}=await import("./addon-webgl-BjvOw43o.js").then(Ut=>Ut.a);return{WebglAddon:vt}},__vite__mapDeps([10,1])),pt=new yt;pt.onContextLoss(()=>{pt.dispose()}),me.loadAddon(pt)}catch{}me.open(R.current),wt&&clearTimeout(wt);const ge=R.current?.querySelector(".xterm-helper-textarea");if(ge&&ge.focus(),R.current)try{R.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{Ze.fit();const yt=R.current?.querySelector(".xterm-helper-textarea");yt&&yt.focus()},50),_.current=me,K.current=Ze,A.current=Me,se.current>0&&(M.current!==null&&(cancelAnimationFrame(M.current),M.current=null),M.current=requestAnimationFrame(()=>{M.current=null,$(Me)})),me.onData(yt=>{A.current===Me&&H.current(yt)});const st=()=>{if(A.current===Me&&K.current&&_.current)try{K.current.fit();const{cols:yt,rows:pt}=_.current;T.current?.(yt,pt)}catch{}};window.addEventListener("resize",st),Q.current&&window.removeEventListener("resize",Q.current),Q.current=st,u(!0),h(null)}catch(be){if(wt&&clearTimeout(wt),!dt)return;const gt=be instanceof Error?be.message:"xterm initialization failed";h(gt)}})(),()=>{dt=!1,wt&&clearTimeout(wt)}},[$,e,le,X?.sessionId,a]),i.useEffect(()=>{e||(_.current&&(_.current.dispose(),_.current=null),K.current=null,A.current=!1,Q.current&&(window.removeEventListener("resize",Q.current),Q.current=null),u(!1),h(null),U.current=!1,o(null),c(null),C(!1),N(null))},[e]),i.useEffect(()=>{if(!d||!_.current||!X)return;const Me=X.sessionId,Ye=J=>{A.current===Me&&_.current?.write(J)},dt=he(J=>{Ye(J)}),wt=ze(J=>{Ye(J)}),St=B(J=>{ne(X.id,Ju(J.shell)||J.shell)}),Fe=pe(J=>{A.current===Me&&(c(J),_.current?.write(`\r
|
|
687
|
+
\x1B[33m[Process exited with code ${J}]\x1B[0m\r
|
|
688
|
+
`))});return()=>{dt(),wt(),St(),Fe()}},[d,X?.sessionId,X?.id,X,q,he,ze,B,pe,ne]),i.useEffect(()=>{q==="connected"&&s&&U.current!==s&&X&&(U.current=s,setTimeout(()=>{L(s+`
|
|
689
|
+
`)},500))},[q,s,L,X,f]),i.useEffect(()=>{if(!d||!_.current)return;_.current.options.fontSize=y,M.current!==null&&(cancelAnimationFrame(M.current),M.current=null);const Me=requestAnimationFrame(()=>{M.current=null,Te()});return M.current=Me,()=>{M.current===Me&&(cancelAnimationFrame(Me),M.current=null)}},[y,d,Te]),i.useEffect(()=>{if(!e)return;const Me=Ye=>{if(!(!Ye.ctrlKey&&!Ye.metaKey)){if(Ye.code==="Equal"||Ye.code==="NumpadAdd"){Ye.preventDefault(),S(dt=>No(dt+1));return}if(Ye.code==="Minus"||Ye.code==="NumpadSubtract"){Ye.preventDefault(),S(dt=>No(dt-1));return}if(Ye.code==="Digit0"||Ye.code==="Numpad0"){Ye.preventDefault(),S(jo);return}}};return window.addEventListener("keydown",Me),()=>window.removeEventListener("keydown",Me)},[e,Te]),i.useEffect(()=>{if(!e)return;const Me=Ye=>{Ye.key==="Escape"&&n()};return document.addEventListener("keydown",Me),()=>document.removeEventListener("keydown",Me)},[e,n]),i.useEffect(()=>{q==="connected"&&_.current&&setTimeout(()=>{if(!_.current||!R.current)return;const Me=R.current.querySelector(".xterm-helper-textarea");Me&&Me.focus();try{R.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[q]);const rt=i.useCallback(()=>{if(!R.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;_.current?.focus();const Ye=R.current.querySelector(".xterm-helper-textarea");if(!Ye)return;Ye.autocapitalize="off",Ye.autocomplete="off",Ye.autocorrect="off",Ye.spellcheck=!1,Ye.setAttribute("inputmode","text");try{Ye.focus({preventScroll:!0})}catch{Ye.focus()}const dt=Ye.value.length;Ye.setSelectionRange(dt,dt)},[]);i.useEffect(()=>Ve(()=>{_.current?.clear(),c(null),U.current=!1,_.current&&(_.current.dispose(),_.current=null),K.current=null,A.current=!1,Q.current&&(window.removeEventListener("resize",Q.current),Q.current=null),u(!1),h(null),re().catch(Ye=>{console.error("Failed to replace invalid terminal session:",Ye)})}),[Ve,re]);const Be=i.useCallback(Me=>{Me.target===Me.currentTarget&&(E.current=!0)},[]),ce=i.useCallback(Me=>{E.current&&Me.target===Me.currentTarget&&n(),E.current=!1},[n]),Re=i.useCallback(()=>{_.current?.clear()},[]),Le=i.useCallback(async()=>{_.current?.clear(),c(null),U.current=!1;try{await fe()}catch(Me){o(Se(Me)||"Failed to restart terminal session")}},[fe]),ct=i.useCallback(()=>{_.current&&(_.current.dispose(),_.current=null),K.current=null,A.current=!1,Q.current&&(window.removeEventListener("resize",Q.current),Q.current=null),h(null),u(!1)},[]),Ue=i.useCallback(()=>{window.location.reload()},[]),ue=i.useCallback(()=>{S(Me=>No(Me+1))},[]),oe=i.useCallback(()=>{S(Me=>No(Me-1))},[]),Ee=i.useCallback(Me=>{N(Ye=>Ye===Me?null:Me)},[]),ft=i.useCallback(Me=>{if(x==="ctrl"){L(H4(Me)),N(null);return}if(x==="alt"){L(q4(Me)),N(null);return}L(Me)},[L,x]),ht=i.useCallback(Me=>{L(Me),N(null)},[L]);if(!e)return null;const tt=()=>{switch(q){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}},xt=!le||!X&&!ke;return t.jsx("div",{className:"modal-overlay open",onMouseDown:Be,onMouseUp:ce,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:g>0?{"--overlay-padding-top":"0px"}:void 0,children:t.jsxs("div",{ref:F,className:"modal terminal-modal","data-testid":"terminal-modal",style:g>0?{"--keyboard-overlap":`${g}px`,"--vv-height":v?`${v}px`:void 0}:void 0,children:[t.jsxs("div",{className:"terminal-header",children:[t.jsxs("div",{className:"terminal-tabs","data-testid":"terminal-tabs",children:[k.map(Me=>t.jsxs("div",{className:`terminal-tab ${Me.isActive?"terminal-tab--active":""}`,onClick:()=>je(Me.id),title:Me.title,role:"tab","aria-selected":Me.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:Me.title}),k.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:Ye=>{Ye.stopPropagation(),ye(Me.id)},title:"Close tab",children:"×"})]},Me.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:He,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(ea,{size:16}),tt()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[q==="disconnected"&&X&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:ae,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(ps,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:Le,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(ps,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:Re,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[t.jsx(Tn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),t.jsxs("button",{className:"terminal-clear-btn terminal-clear-btn--shortcut",onClick:()=>C(Me=>!Me),"data-testid":"terminal-shortcut-toggle",title:"Shortcuts","aria-pressed":j,children:[t.jsx(Jw,{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(mn,{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:[xt&&!ke&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),ke&&!X&&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: ",ke]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:Z,"data-testid":"terminal-retry-btn",children:[t.jsx(ps,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Ue,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(ps,{size:14}),"Refresh page"]})]})]})}),m&&X&&t.jsx("div",{className:"terminal-loading","data-testid":"terminal-xterm-init-error",children:t.jsxs("div",{className:"terminal-error-content",children:[t.jsxs("span",{children:["Terminal UI failed to initialize: ",m]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:ct,"data-testid":"terminal-reinit-btn",children:[t.jsx(ps,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Ue,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(ps,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:R,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:rt,onTouchStart:rt},X?.sessionId)]}),j&&t.jsxs("div",{className:"terminal-shortcut-panel","data-testid":"terminal-shortcut-panel",children:[t.jsxs("div",{className:"terminal-shortcut-modifier-row",children:[t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${x==="ctrl"?"is-active":""}`,"data-testid":"terminal-modifier-ctrl",onClick:()=>Ee("ctrl"),"aria-pressed":x==="ctrl",children:"Ctrl"}),t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${x==="alt"?"is-active":""}`,"data-testid":"terminal-modifier-alt",onClick:()=>Ee("alt"),"aria-pressed":x==="alt",children:"Alt"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>ht("\x1B"),children:"ESC"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>ht(" "),children:"Tab"})]}),V4.map(Me=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>ft(Me.key),title:Me.description,children:Me.label},Me.label))]}),t.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[t.jsxs("span",{className:`terminal-connection-status ${q}`,children:[q==="connected"&&"Connected",q==="connecting"&&"Connecting...",q==="reconnecting"&&"Reconnecting...",q==="disconnected"&&"Disconnected"]}),l!==null&&t.jsxs("span",{className:"terminal-exit-code","data-testid":"terminal-exit-code",children:["Exit: ",l]}),t.jsxs("span",{className:"terminal-font-size-controls",children:[t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:oe,"data-testid":"terminal-font-size-decrease","aria-label":"Decrease terminal font size",children:t.jsx(xk,{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:ue,"data-testid":"terminal-font-size-increase","aria-label":"Increase terminal font size",children:t.jsx($n,{size:14})})]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • ⌨ Shortcuts panel • Esc close"})]})]})})}const uo={name:"",command:""};function qf(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function Z4(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function eD({isOpen:e,onClose:n,addToast:s,projectId:a,onRunScript:r}){Mi(e);const[o,l]=i.useState({}),[c,d]=i.useState(!0),[u,m]=i.useState(!1),[h,f]=i.useState(null),[p,g]=i.useState(uo),[w,v]=i.useState(!1),[b,y]=i.useState(null),[S,j]=i.useState(null),C=sa(n),x=i.useCallback(async()=>{try{d(!0);const H=await $o(a);l(H)}catch(H){s(Se(H)||"Failed to load scripts","error")}finally{d(!1)}},[s,a]);i.useEffect(()=>{e&&x()},[e,x]);const N=i.useCallback(()=>{m(!0),f(null),g(uo),j(null)},[]),R=i.useCallback((H,Q)=>{f(H),m(!1),g({name:H,command:Q}),j(null)},[]),F=i.useCallback(()=>{f(null),m(!1),g(uo),j(null)},[]),E=i.useCallback(H=>{g(Q=>({...Q,name:H})),H&&!qf(H)?j("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):j(null)},[]),_=i.useCallback(async()=>{const H=p.name.trim(),Q=p.command.trim();if(!H){s("Script name is required","error");return}if(!qf(H)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!Q){s("Script command is required","error");return}v(!0);try{await KS(H,Q,a),s(h?"Script updated":"Script created","success"),f(null),m(!1),g(uo),j(null),await x()}catch(se){const O=Se(se);O?.includes("already exists")?s("A script with this name already exists","error"):s(O||"Failed to save script","error")}finally{v(!1)}},[p,h,s,x,a]),K=i.useCallback(async H=>{try{await JS(H,a),s("Script deleted","success"),y(null),h===H&&(f(null),g(uo)),await x()}catch(Q){s(Se(Q)||"Failed to delete script","error")}},[h,s,x,a]),U=i.useCallback((H,Q)=>{r&&r(H,Q)},[r]);if(!e)return null;const A=u||h!==null,T=Object.entries(o).map(([H,Q])=>({name:H,command:Q}));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(ea,{size:18,style:{marginRight:"8px",verticalAlign:"middle"}}),"Scripts"]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"modal-body scripts-modal-body",children:c?t.jsxs("div",{style:{textAlign:"center",padding:"32px",color:"var(--text-muted)"},children:[t.jsx(jt,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),"Loading scripts..."]}):A?t.jsxs("div",{className:"scripts-modal-form",style:{display:"flex",flexDirection:"column",gap:"16px"},children:[t.jsxs("div",{children:[t.jsx("label",{htmlFor:"script-name",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Script Name"}),t.jsx("input",{id:"script-name",type:"text",className:"input",value:p.name,onChange:H=>E(H.target.value),placeholder:"e.g., build, test, lint",disabled:w||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:H=>g(Q=>({...Q,command:H.target.value})),placeholder:"e.g., npm run build",rows:3,disabled:w,"data-testid":"script-command-input",style:{width:"100%",resize:"vertical",fontFamily:"monospace"}})]}),t.jsxs("div",{className:"scripts-modal-form-actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end"},children:[t.jsx("button",{className:"btn btn-secondary",onClick:F,disabled:w,"data-testid":"script-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:_,disabled:w||!!S,"data-testid":"script-save-btn",children:w?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:14,className:"spin",style:{marginRight:"6px"}}),"Saving..."]}):h?"Update":"Create"})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"scripts-modal-list-header",style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[t.jsx("div",{style:{fontSize:"13px",color:"var(--text-muted)"},children:T.length===0?"No scripts defined":`${T.length} script${T.length===1?"":"s"}`}),t.jsxs("button",{className:"btn btn-primary",onClick:N,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx($n,{size:14}),"Add Script"]})]}),T.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(ea,{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:T.map(H=>t.jsx("div",{className:"script-card","data-testid":`script-${H.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:H.name})}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:H.command,children:Z4(H.command)})]}),t.jsxs("div",{className:"script-card-actions",style:{display:"flex",gap:"4px",marginLeft:"8px",flexShrink:0},children:[t.jsxs("button",{className:"btn btn-secondary",onClick:()=>U(H.name,H.command),title:"Run script","aria-label":`Run ${H.name}`,"data-testid":`run-script-${H.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[t.jsx(os,{size:12}),"Run"]}),t.jsx("button",{className:"btn-icon",onClick:()=>R(H.name,H.command),title:"Edit","aria-label":`Edit ${H.name}`,"data-testid":`edit-script-${H.name}`,children:t.jsx($n,{size:14,style:{transform:"rotate(45deg)"}})}),b===H.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>K(H.name),title:"Confirm delete","aria-label":`Confirm delete ${H.name}`,"data-testid":`confirm-delete-script-${H.name}`,style:{color:"var(--color-error)"},children:t.jsx(Tn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>y(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${H.name}`,children:t.jsx(mn,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>y(H.name),title:"Delete","aria-label":`Delete ${H.name}`,"data-testid":`delete-script-${H.name}`,children:t.jsx(Tn,{size:14})})]})]})},H.name))})]})})]})})}function tD(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(w=>w+1)},[]),g=i.useCallback(w=>{l(w),m(null)},[]);return i.useEffect(()=>{l("."),m(null),r([])},[e]),i.useEffect(()=>{if(!n||!e)return;let w=!1;async function v(){d(!0),m(null);try{const b=await lS(e,o==="."?void 0:o,s);w||r(b.entries)}catch(b){w||(m(Se(b)||"Failed to load files"),r([]))}finally{w||d(!1)}}return v(),()=>{w=!0}},[e,o,n,h,s]),{entries:a,currentPath:o,setPath:g,loading:c,error:u,refresh:p}}function nD(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,w]=i.useState(null),v=i.useCallback(S=>{o(S),w(null)},[]);i.useEffect(()=>{if(!e||!n){o(""),c(""),u(null),w(null);return}let S=!1;async function j(){h(!0),w(null);try{const C=await cS(e,n,a);S||(o(C.content),c(C.content),u(C.mtime))}catch(C){S||(w(Se(C)||"Failed to load file"),o(""),c(""),u(null))}finally{S||h(!1)}}return j(),()=>{S=!0}},[e,n,s,a]);const b=r!==l,y=i.useCallback(async()=>{if(!(!e||!n||!b)){p(!0),w(null);try{const S=await dS(e,n,r,a);c(r),u(S.mtime)}catch(S){throw w(Se(S)||"Failed to save file"),S}finally{p(!1)}}},[e,n,r,b,a]);return{content:r,setContent:v,originalContent:l,loading:m,saving:f,error:g,save:y,hasChanges:b,mtime:d}}const sD=1e4;function iD(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function aD(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function rD(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 oS(e);if(u)return;s(iD(f.project)),r(f.tasks.map(aD)),d(null)}catch(f){u||d(Se(f)||"Failed to load workspaces")}finally{u||l(!1)}}m();const h=window.setInterval(()=>{m()},sD);return()=>{u=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:a,loading:o,error:c}}function oD(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function lD(e){return e?new Date(e).toLocaleDateString():""}function Vf(e,n){return SC(e,n)}const mo={visible:!1,x:0,y:0,entry:null,entryFullPath:""},Hd={type:null,entry:null,entryFullPath:""},cD=200,dD=500,Wf=10;function uD({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,w=f?.offsetLeft??0,v=f?.offsetTop??0,b=8;let y=e-w,S=n-v;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+w,y:S+v})},[e,n]),i.useEffect(()=>{const m=h=>{h.key==="Escape"&&r()};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[r]);const d=s.type==="directory",u=[{id:"copy",label:"Copy",icon:ba,disabled:!1},{id:"move",label:"Move",icon:wk,disabled:!1},{id:"rename",label:"Rename",icon:Hs,disabled:!1},...d?[{id:"download-zip",label:"Download as ZIP",icon:zo,disabled:!1}]:[{id:"download",label:"Download",icon:lw,disabled:!1}],{id:"divider",label:"",icon:ba,disabled:!0},{id:"delete",label:"Delete",icon:Tn,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 mD({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 hD({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(mo),[f,p]=i.useState(Hd),[g,w]=i.useState(!1),[v,b]=i.useState(null),[y,S]=i.useState(!1),[j,C]=i.useState(null),x=i.useRef(null),N=i.useRef(null),R=i.useRef(null),F=i.useRef(!1),E=i.useCallback(()=>{x.current!==null&&(window.clearTimeout(x.current),x.current=null),N.current!==null&&(window.clearTimeout(N.current),N.current=null)},[]),_=i.useCallback(()=>{E(),R.current=null,S(!1),C(null)},[E]);i.useEffect(()=>()=>{E()},[E]);const K=i.useCallback((D,$,k,X)=>{h({visible:!0,x:D,y:$,entry:k,entryFullPath:X})},[]),U=i.useCallback((D,$,k)=>{if(D.touches.length!==1)return;const X=D.touches[0];X&&(_(),R.current={x:X.clientX,y:X.clientY},N.current=window.setTimeout(()=>{S(!0),C(k)},cD),x.current=window.setTimeout(()=>{const le=R.current;le&&(F.current=!0,S(!1),C(null),E(),K(le.x,le.y,$,k))},dD))},[_,E,K]),A=i.useCallback(D=>{const $=R.current,k=D.touches[0];!$||!k||(Math.abs(k.clientX-$.x)>Wf||Math.abs(k.clientY-$.y)>Wf)&&_()},[_]),T=i.useCallback(()=>{_()},[_]);i.useEffect(()=>{if(!m.visible)return;const D=document.querySelector(".file-browser-list"),$=()=>{F.current=!1,_(),h(mo)};return D?.addEventListener("scroll",$),()=>D?.removeEventListener("scroll",$)},[_,m.visible]),i.useEffect(()=>{if(!m.visible)return;const D=$=>{$.key==="Escape"&&(F.current=!1,h(mo))};return document.addEventListener("keydown",D),()=>document.removeEventListener("keydown",D)},[m.visible]);const H=i.useCallback((D,$)=>{D.preventDefault(),D.stopPropagation(),_(),F.current=!1,K(D.clientX,D.clientY,$,Vf(n,$.name))},[_,n,K]),Q=i.useCallback(D=>{if(!m.entry)return;F.current=!1;const $=m.entry,k=m.entryFullPath;if(h(mo),D==="download"){if(!c)return;const X=hb(c,k,u);window.open(Fi(X),"_blank");return}if(D==="download-zip"){if(!c)return;const X=gS(c,k,u);window.open(Fi(X),"_blank");return}p({type:D,entry:$,entryFullPath:k}),b(null)},[m,c,u]),se=i.useCallback(async D=>{if(!(!f.type||!f.entry||!c)){w(!0),b(null);try{switch(f.type){case"copy":await mS(c,f.entryFullPath,D,u);break;case"move":await hS(c,f.entryFullPath,D,u);break;case"rename":await fS(c,f.entryFullPath,D,u);break;case"delete":await pS(c,f.entryFullPath,u);break}p(Hd),d?.()}catch($){b(Se($)||"Operation failed")}finally{w(!1)}}},[f,c,d,u]),O=i.useCallback(()=>{p(Hd),b(null)},[]),M=i.useCallback((D,$)=>{if(F.current){F.current=!1;return}m.visible||(D.type==="directory"?a($):s($))},[m.visible,a,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(jt,{className:"spin",size:24}),t.jsx("span",{children:"Loading files..."})]}):o?t.jsxs("div",{className:"file-browser-error",children:[t.jsxs("p",{children:["Error: ",o]}),l&&t.jsx("button",{className:"btn btn-sm",onClick:l,children:"Retry"})]}):t.jsxs("div",{className:"file-browser",children:[t.jsxs("div",{className:"file-browser-header",children:[n!=="."&&t.jsxs("button",{className:"file-browser-up",onClick:()=>{a(CC(n))},children:[t.jsx(qn,{size:16,style:{transform:"rotate(-90deg)"}}),"Up one level"]}),t.jsx("span",{className:"file-browser-path",children:n==="."?"Root":Hr(n)})]}),t.jsx("div",{className:"file-browser-list",children:e.length===0?t.jsx("div",{className:"file-browser-empty",children:"(empty directory)"}):e.map(D=>{const $=Vf(n,D.name),k=y&&j===$;return t.jsxs("div",{className:`file-node file-node--${D.type} ${k?"file-node--long-pressing":""}`,onClick:()=>M(D,$),onContextMenu:X=>H(X,D),onTouchStart:X=>U(X,D,$),onTouchMove:A,onTouchEnd:T,onTouchCancel:T,children:[t.jsx("div",{className:"file-node-icon",children:D.type==="directory"?t.jsx(js,{size:16}):t.jsx(nb,{size:16})}),t.jsx("div",{className:"file-node-name",children:D.name}),D.type==="file"&&D.size!==void 0&&t.jsx("div",{className:"file-node-size",children:oD(D.size)}),D.mtime&&t.jsx("div",{className:"file-node-time",children:lD(D.mtime)})]},D.name)})}),m.visible&&m.entry&&t.jsx(uD,{x:m.x,y:m.y,entry:m.entry,onAction:Q,onClose:()=>{F.current=!1,h(mo)}}),f.type&&f.entry&&t.jsx(mD,{type:f.type,entry:f.entry,entryFullPath:f.entryFullPath,onConfirm:se,onCancel:O,loading:g,error:v})]})}function pD(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function fD({content:e,onChange:n,readOnly:s,filePath:a,showLineNumbers:r=!1,onToggleLineNumbers:o,canToggleLineNumbers:l=!0}){const[c,d]=i.useState(!1),[u,m]=i.useState(!0),h=i.useRef(null),f=pD(a),p=f&&(s?!0:c),g=r&&!s&&!p,w=!!o&&l&&!s&&!p,v=i.useMemo(()=>g?e.split(`
|
|
690
|
+
`).length:0,[e,g]),b=i.useCallback(()=>{d(!1)},[]),y=i.useCallback(()=>{d(!0)},[]),S=i.useCallback(()=>{m(C=>!C)},[]),j=i.useCallback(C=>{h.current&&(h.current.scrollTop=C.currentTarget.scrollTop)},[]);return t.jsxs("div",{className:"file-editor-container",children:[f?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 ${p?"":"btn-primary"}`,onClick:b,disabled:!p,"aria-label":"Edit mode",children:[t.jsx(tb,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${p?"btn-primary":""}`,onClick:y,disabled:p,"aria-label":"Preview mode",children:[t.jsx(Fr,{size:14}),"Preview"]})]}),!s&&t.jsxs("div",{className:"file-editor-toolbar-actions",children:[w&&t.jsxs("button",{className:`btn btn-sm file-editor-line-numbers-button ${r?"btn-primary":""}`,onClick:o,"aria-label":"Toggle line numbers","aria-pressed":r,title:"Toggle line numbers",children:[t.jsx($m,{size:14}),t.jsx("span",{children:"Line #"})]}),t.jsx("button",{className:`btn btn-sm ${u?"btn-primary":""}`,onClick:S,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(Vl,{size:14})})]})]}):!s&&t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsx("div",{className:"file-editor-mode-toggle"}),t.jsxs("div",{className:"file-editor-toolbar-actions",children:[w&&t.jsxs("button",{className:`btn btn-sm file-editor-line-numbers-button ${r?"btn-primary":""}`,onClick:o,"aria-label":"Toggle line numbers","aria-pressed":r,title:"Toggle line numbers",children:[t.jsx($m,{size:14}),t.jsx("span",{children:"Line #"})]}),t.jsx("button",{className:`btn btn-sm ${u?"btn-primary":""}`,onClick:S,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(Vl,{size:14})})]})]}),p?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(xi,{remarkPlugins:[vi],children:e})}):t.jsxs("div",{className:`file-editor-textarea-shell ${g?"file-editor-textarea-shell--line-numbers":""}`,children:[g&&t.jsx("div",{className:"file-editor-line-numbers",ref:h,"aria-hidden":"true",children:Array.from({length:v},(C,x)=>t.jsx("div",{className:"file-editor-line-number",children:x+1},`line-${x+1}`))}),t.jsx("textarea",{className:`file-editor-textarea ${u?"file-editor-textarea--wrap":""}`,value:e,onChange:C=>n(C.target.value),onScroll:j,readOnly:s,spellCheck:!1,"aria-label":a?`Editor for ${a}`:"File editor"})]})]})}function gD(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function bD({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(Pm,{size:14}):t.jsx(iu,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(gn,{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(Pm,{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(iu,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:gD(c.title)})]},c.id))]})]})]})}const xD=768,vD=280,Rl=180,Il=500,Gf="fusion:file-browser-sidebar-width",Kf="kb-files-line-numbers",Mv=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),yD=new Set([...Mv,".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 Tl(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return yD.has(n)}function wD(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return Mv.has(n)}function kD(e){const n=e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/$/,""),s=n.lastIndexOf("/");return s>0?n.slice(0,s):"."}function jD({initialWorkspace:e="project",initialFile:n=null,onClose:s,onWorkspaceChange:a,projectId:r}){const{projectName:o,workspaces:l}=rD(r),c=i.useRef(null);zi(c,!0,"fusion:files-modal-size");const d=sa(s),[u,m]=i.useState(e),[h,f]=i.useState(null),[p,g]=i.useState(!1),[w,v]=i.useState("list"),[b,y]=i.useState(vD),[S,j]=i.useState(!1),{entries:C,currentPath:x,setPath:N,loading:R,error:F,refresh:E}=tD(u,!0,r),{content:_,setContent:K,originalContent:U,loading:A,saving:T,error:H,save:Q,hasChanges:se,mtime:O}=nD(u,h,!0,r);i.useEffect(()=>{m(e)},[e]),i.useEffect(()=>{const Z=()=>{g(window.innerWidth<=xD)};return Z(),window.addEventListener("resize",Z),()=>window.removeEventListener("resize",Z)},[]),i.useEffect(()=>{h||v("list")},[h]),i.useEffect(()=>{if(!n){f(null);return}f(n),N(kD(n)),p&&v("editor")},[n,p,N]),i.useEffect(()=>{try{const Z=localStorage.getItem(Gf);if(!Z)return;const re=Number.parseInt(Z,10);if(!Number.isNaN(re)){const q=Math.max(Rl,Math.min(Il,re));y(q)}}catch{}},[]),i.useEffect(()=>{const Z=Gn(Kf,r);j(Z==="true")},[r]),i.useEffect(()=>{const Z=re=>{re.key==="Escape"&&s(),(re.metaKey||re.ctrlKey)&&re.key==="s"&&(re.preventDefault(),se&&!T&&Q())};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[s,se,T,Q]);const M=i.useCallback(Z=>{f(Z),p&&v("editor")},[p]),D=i.useCallback(()=>{v("list")},[]),$=i.useCallback(()=>{K(U)},[U,K]),k=i.useCallback(Z=>{m(Z),f(null),v("list"),a?.(Z)},[a]),X=i.useCallback(Z=>{try{localStorage.setItem(Gf,String(Z))}catch{}},[]),le=i.useCallback(Z=>{if(p)return;Z.preventDefault(),Z.stopPropagation();const re=Z.currentTarget;typeof re.setPointerCapture=="function"&&re.setPointerCapture(Z.pointerId);const q=Z.clientX,L=b;let xe=L;document.body.style.userSelect="none";const he=pe=>{const ze=pe.clientX-q,ae=Math.max(Rl,Math.min(Il,L+ze));xe=ae,y(ae)},B=pe=>{typeof re.releasePointerCapture=="function"&&re.releasePointerCapture(pe.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",he),document.removeEventListener("pointerup",B),X(xe)};document.addEventListener("pointermove",he),document.addEventListener("pointerup",B)},[p,X,b]),ke=i.useCallback(Z=>{if(p)return;const re=20;if(Z.key!=="ArrowLeft"&&Z.key!=="ArrowRight")return;Z.preventDefault();const q=Z.key==="ArrowLeft"?-re:re,L=Math.max(Rl,Math.min(Il,b+q));y(L),X(L)},[p,X,b]),He=i.useCallback(()=>{j(Z=>{const re=!Z;return fs(Kf,String(re),r),re})},[r]),je=`Files — ${i.useMemo(()=>u==="project"?"Project":l.find(Z=>Z.id===u)?.id??u,[u,l])}`,ne=i.useMemo(()=>!h||!wD(h)?null:hb(u,h,r),[h,u,r]),fe=Z=>{const re=new Blob([Z]).size;return re<1024?`${re} B`:`${(re/1024).toFixed(1)} KB`};return t.jsx("div",{className:"modal-overlay open",...d,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal file-browser-modal",ref:c,children:[t.jsxs("div",{className:"modal-header file-browser-modal-header",children:[t.jsxs("div",{className:"file-browser-header-title",children:[t.jsx(js,{size:18}),t.jsx("span",{children:je}),h&&t.jsx("span",{className:"file-browser-header-path",children:h})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsx(bD,{currentWorkspace:u,projectName:o,workspaces:l,onSelect:k}),t.jsx("button",{className:"modal-close",onClick:s,"aria-label":"Close",children:t.jsx(mn,{size:20})})]})]}),t.jsxs("div",{className:"file-browser-body",children:[t.jsx("div",{className:`file-browser-sidebar ${p?"mobile":""} ${w==="list"?"active":""}`,style:p?void 0:{width:`${b}px`},children:t.jsx(hD,{entries:C,currentPath:x,onSelectFile:M,onNavigate:N,loading:R,error:F,onRetry:E,workspace:u,onRefresh:E,projectId:r})}),!p&&t.jsx("div",{className:"file-browser-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":Rl,"aria-valuemax":Il,"aria-valuenow":b,"aria-label":"Resize sidebar",tabIndex:0,onPointerDown:le,onKeyDown:ke}),t.jsx("div",{className:`file-browser-content ${p?"mobile":""} ${w==="editor"?"active":""}`,children:h?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"file-browser-toolbar",children:[t.jsxs("div",{className:"file-browser-file-info",children:[p&&w==="editor"&&t.jsxs("button",{className:"file-browser-back-button",onClick:D,"aria-label":"Back to file list",children:[t.jsx(Ga,{size:16}),t.jsx("span",{children:"Back"})]}),h,Tl(h)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(Cw,{size:12}),"Binary file — read only"]}),O&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(O).toLocaleString()]}),A&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!ne&&se&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:$,disabled:T,children:[t.jsx(Dk,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void Q(),disabled:T,children:[t.jsx(ob,{size:14}),T?"Saving...":"Save"]})]})})]}),H&&!ne&&t.jsx("div",{className:"file-browser-error-banner",children:H}),ne?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:ne,alt:h??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(fD,{content:_,onChange:K,filePath:h,readOnly:Tl(h),showLineNumbers:S&&!Tl(h),onToggleLineNumbers:He,canToggleLineNumbers:!Tl(h)})}),!ne&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:fe(_)}),se&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(js,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}const ND=i.lazy(()=>En(()=>import("./TodoView-uJRg4Cnl.js"),__vite__mapDeps([11,1,5,6,12])).then(e=>({default:e.TodoView})));function SD({onClose:e,projectId:n,addToast:s,onPlanningMode:a}){const r=sa(e),l=oi()==="mobile",{keyboardOverlap:c,viewportHeight:d,viewportOffsetTop:u,keyboardOpen:m}=aa({enabled:l});Mi(l);const h=m?{"--keyboard-overlap":`${c}px`,"--vv-offset-top":`${u}px`,...d!==null?{"--vv-height":`${d}px`}:{}}:{};return i.useEffect(()=>{const f=p=>{p.key==="Escape"&&e()};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[e]),t.jsx("div",{className:"modal-overlay open",...r,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal todo-modal",style:h,children:[t.jsxs("div",{className:"modal-header todo-modal-header",children:[t.jsxs("div",{className:"todo-modal-header-title",children:[t.jsx(tk,{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(mn,{size:20})})]}),t.jsx("div",{className:"todo-modal-body",children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(ND,{projectId:n,addToast:s,onPlanningMode:a,onClose:e,mobileKeyboardActive:l&&m})})})]})})}function CD(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 dN();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:Se(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 ED(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 _D(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const Av="kb-usage-hidden-windows",Rv="kb-usage-modal-size",Iv="kb-usage-provider-order";function Jf(e){const n=Gn(Rv,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 Yf(e){const n=Gn(Av,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 MD(e,n){fs(Av,JSON.stringify(e),n)}function Qf(e){const n=Gn(Iv,e);if(!n)return[];try{const s=JSON.parse(n);return Array.isArray(s)?s.filter(a=>typeof a=="string"):[]}catch{return[]}}function Xf(e,n){fs(Iv,JSON.stringify(e),n)}function Tv(e,n,s){return s[e]?.includes(n)??!1}function AD({window:e,viewMode:n,isHidden:s,onToggleHidden:a}){const r=_D(e.percentUsed),o=n==="remaining",l=Math.round(o?e.percentLeft:e.percentUsed),c=o?`${Math.round(e.percentLeft)}% remaining`:`${Math.round(e.percentUsed)}% used`,d=o?`${Math.round(e.percentUsed)}% used`:`${Math.round(e.percentLeft)}% left`;let u=e.resetText;if(!u&&e.resetAt){const v=new Date(e.resetAt).getTime()-Date.now();if(v>0){const b=Math.floor(v/36e5),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(v/6e4)}m`}}const m=e.pace,h=m!==void 0;let f=0;h&&(f=o?100-m.percentElapsed:m.percentElapsed);const p=m?.status==="ahead",g=m?.status==="behind",w=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(Fr,{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:ED(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(zr,{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(ij,{size:14,className:"pace-icon pace-behind"}),t.jsx("span",{className:"pace-text pace-behind",children:m.message})]}),w&&t.jsxs(t.Fragment,{children:[t.jsx(Xn,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:m.message})]})]})]})}function RD(e){const n=e.toLowerCase();return n.includes("claude")||n.includes("anthropic")?"anthropic":n.includes("codex")||n.includes("openai")||n.includes("gpt")?"openai":n.includes("gemini")||n.includes("google")||n.includes("antigravity")?"google":n.includes("ollama")?"ollama":n.includes("minimax")?"minimax":n.includes("zai")||n.includes("zhipu")?"zai":n.includes("kimi")||n.includes("moonshot")?"kimi":n.includes("bedrock")||n.includes("amazon")?"bedrock":n.includes("xai")||n.includes("grok")?"xai":n.includes("opencode")?"opencode":n.includes("copilot")||n==="github copilot"?"github-copilot":e}function ID({provider:e,viewMode:n,hiddenWindows:s,onToggleWindow:a,onShowAllHidden:r,isDragging:o,isDragOver:l,dragOverPosition:c,onDragStart:d,onDragOver:u,onDragLeave:m,onDrop:h,onDragEnd:f,isTouchReorderMode:p,canMoveUp:g,canMoveDown:w,onMoveUp:v,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(zn,{provider:RD(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:v,disabled:!g,"aria-label":`Move ${e.name} up`,children:t.jsx(Li,{size:14})}),t.jsx("button",{className:"btn-icon usage-provider-reorder-btn",type:"button",onClick:b,disabled:!w,"aria-label":`Move ${e.name} down`,children:t.jsx(gn,{size:14})})]}),S(),t.jsx("div",{className:"usage-provider-drag-handle","aria-hidden":"true",children:t.jsx(xc,{size:16})})]})]}),e.error&&t.jsx("div",{className:"usage-provider-error",children:e.error}),e.plan&&t.jsx("div",{className:"usage-provider-meta",children:t.jsx("span",{className:"usage-provider-plan",children:e.plan})}),e.windows.length>0?t.jsx("div",{className:"usage-provider-windows",children:e.windows.map((j,C)=>{const x=Tv(e.name,j.label,s);return t.jsx(AD,{window:j,viewMode:n,isHidden:x,onToggleHidden:()=>a(e.name,j.label)},`${e.name}-${j.label}-${C}`)})}):e.status==="ok"?t.jsx("div",{className:"usage-provider-empty",children:"No usage data available"}):null]})}function TD(){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 PD({isOpen:e,onClose:n,projectId:s,anchorRect:a}){const{providers:r,loading:o,error:l,lastUpdated:c,refresh:d}=CD({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),[w,v]=i.useState("used"),[b,y]=i.useState(()=>Yf(s)),[S,j]=i.useState(()=>Qf(s)),[C,x]=i.useState(null),[N,R]=i.useState(null),[F,E]=i.useState(null),_=i.useRef(null),K=i.useRef(null),U=i.useRef(e),A=i.useRef(!1),[T,H]=i.useState(()=>Jf(s));i.useEffect(()=>{H(Jf(s))},[s]),i.useEffect(()=>{if(!e||!h)return;const B=K.current;if(!B||typeof ResizeObserver>"u")return;let pe=null;const ze=new ResizeObserver(ae=>{const Ve=ae[0];if(!Ve)return;const{width:Te,height:rt}=Ve.contentRect;Te<=0||rt<=0||(pe&&clearTimeout(pe),pe=setTimeout(()=>{fs(Rv,JSON.stringify({width:Math.round(Te),height:Math.round(rt)}),s)},250))});return ze.observe(B),()=>{pe&&clearTimeout(pe),ze.disconnect()}},[e,h,s]),i.useEffect(()=>{e||(A.current=!1)},[e]),i.useEffect(()=>{r.length>0&&(A.current=!0)},[r.length]),i.useEffect(()=>{if(typeof window>"u")return;const B=window.matchMedia?.("(pointer: coarse)"),pe=()=>{f(window.innerWidth>=769),g(B?.matches??!1)};return pe(),window.addEventListener("resize",pe),B?.addEventListener?.("change",pe),()=>{window.removeEventListener("resize",pe),B?.removeEventListener?.("change",pe)}},[]),i.useEffect(()=>{!U.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&d(),U.current=e},[e,c,d]),i.useEffect(()=>{const B=Gn("kb-usage-view-mode",s);if(B==="used"||B==="remaining"){v(B);return}v("used")},[s]);const Q=i.useCallback(B=>{v(B),fs("kb-usage-view-mode",B,s)},[s]);i.useEffect(()=>{y(Yf(s)),j(Qf(s))},[s]),i.useEffect(()=>{MD(b,s)},[b,s]);const se=i.useCallback((B,pe)=>{y(ze=>{if(Tv(B,pe,ze)){const ae=(ze[B]??[]).filter(Ve=>Ve!==pe);if(ae.length===0){const{[B]:Ve,...Te}=ze;return Te}return{...ze,[B]:ae}}return{...ze,[B]:[...ze[B]??[],pe]}})},[]),O=i.useCallback(B=>{y(pe=>{if(!pe[B])return pe;const{[B]:ze,...ae}=pe;return ae})},[]),M=i.useCallback(B=>{if(S.length===0)return B;const pe=new Map(B.map(ae=>[ae.name,ae])),ze=[];for(const ae of S){const Ve=pe.get(ae);Ve&&(ze.push(Ve),pe.delete(ae))}return[...ze,...pe.values()]},[S]),D=i.useCallback((B,pe)=>{B.dataTransfer.effectAllowed="move",B.dataTransfer.setData("text/plain",pe),x(pe)},[]),$=i.useCallback((B,pe)=>{if(!C||C===pe)return;B.preventDefault(),B.dataTransfer.dropEffect="move";const{top:ze,height:ae}=B.currentTarget.getBoundingClientRect(),Ve=ze+ae/2,Te=B.clientY<Ve?"before":"after";R(pe),E(Te)},[C]),k=i.useCallback((B,pe)=>{B.preventDefault();const ze=C??B.dataTransfer.getData("text/plain");if(!ze||ze===pe){R(null),E(null);return}const Ve=M(r).map(Be=>Be.name).filter(Be=>Be!==ze),Te=Ve.indexOf(pe);if(Te<0){R(null),E(null);return}const rt=F==="after"?Te+1:Te;Ve.splice(rt,0,ze),Xf(Ve,s),j(Ve),R(null),E(null)},[C,F,s,r,M]),X=i.useCallback(()=>{x(null),R(null),E(null)},[]),le=i.useCallback((B,pe)=>{const ze=M(r).map(Be=>Be.name),ae=ze.indexOf(B),Ve=ae+pe;if(ae<0||Ve<0||Ve>=ze.length)return;const Te=[...ze],[rt]=Te.splice(ae,1);Te.splice(Ve,0,rt),Xf(Te,s),j(Te)},[s,r,M]),ke=i.useCallback(async()=>{m(!0),await d(),m(!1)},[d]);i.useEffect(()=>{if(!e)return;const B=pe=>{pe.key==="Escape"&&n()};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[e,n]);const He=i.useCallback(B=>{B.target===B.currentTarget&&n()},[n]);if(!e)return null;const ye=!!(a&&h),je=8,ne=12,Z=T?.width??420,re=ye?Math.min((a?.bottom??0)+je,window.innerHeight-ne):void 0,q=ye?Math.max(8,(a?.right??0)-Z):void 0,L=h&&T?{width:T.width,height:T.height}:{},xe=M(r),he=t.jsxs("div",{ref:K,className:`usage-modal${ye?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:ye?{position:"fixed",top:re,left:q,...L}:L,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Js,{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 ${w==="used"?"active":""}`,onClick:()=>Q("used"),"aria-pressed":w==="used","data-testid":"usage-view-toggle-used",children:"Used"}),t.jsx("button",{className:`usage-view-toggle-btn ${w==="remaining"?"active":""}`,onClick:()=>Q("remaining"),"aria-pressed":w==="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(mn,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:_,children:(o||!A.current&&!l)&&r.length===0?t.jsx(TD,{}):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:ke,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:xe.map((B,pe)=>t.jsx(ID,{provider:B,viewMode:w,hiddenWindows:b,onToggleWindow:se,onShowAllHidden:O,isDragging:C===B.name,isDragOver:N===B.name,dragOverPosition:N===B.name?F:null,onDragStart:ze=>D(ze,B.name),onDragOver:ze=>$(ze,B.name),onDragLeave:()=>{N===B.name&&(R(null),E(null))},onDrop:ze=>k(ze,B.name),onDragEnd:X,isTouchReorderMode:p,canMoveUp:pe>0,canMoveDown:pe<xe.length-1,onMoveUp:()=>le(B.name,-1),onMoveDown:()=>le(B.name,1)},B.name))})}),t.jsxs("div",{className:"modal-actions usage-actions",children:[t.jsx("div",{className:"modal-actions-left usage-actions-left",children:t.jsx("div",{className:"usage-last-updated",children:c&&t.jsxs("span",{children:["Last updated: ",c.toLocaleTimeString()]})})}),t.jsxs("div",{className:"modal-actions-right usage-actions-right",children:[t.jsxs("button",{className:"btn btn-sm",onClick:ke,disabled:o||u,"data-testid":"usage-refresh-btn",children:[t.jsx(ps,{size:14,className:u?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]});return ye?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"usage-popover-backdrop",onClick:n,"data-testid":"usage-modal-overlay"}),he]}):t.jsx("div",{className:"modal-overlay open",onClick:He,"data-testid":"usage-modal-overlay",children:he})}function Pv(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 lc(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 $D={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},$v={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},DD={cron:Qg,webhook:lb,api:Xg,manual:ls},LD={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},OD={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function FD({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(Xn,{size:12}):t.jsx(Ho,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:Pv(n)})]})}function zD({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"} ${lc(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(Xn,{size:12}):t.jsx(Ho,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:lc(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:$v[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:Pv(r)}),s?t.jsx(Li,{size:12}):t.jsx(gn,{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 BD({routine:e,onEdit:n,onDelete:s,onRun:a,onToggle:r,running:o,lastRunOutput:l}){const[c,d]=i.useState(!1),{confirm:u}=li(),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=$D[e.trigger.type],f=DD[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}),$v[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(gc,{size:10}):t.jsx(js,{size:10}),e.scope]})]}),e.description&&t.jsx("p",{className:"routine-card-description",children:e.description})]}),t.jsxs("div",{className:"routine-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>a(e),disabled:o,title:o?"Running…":"Run now","aria-label":o?"Running…":`Run ${e.name} now`,children:o?t.jsx(jt,{className:"spinner"}):t.jsx(os,{})}),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(Ci,{}):t.jsx(os,{})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(Hs,{})}),t.jsx("button",{className:"btn-icon",onClick:m,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(Tn,{})})]})]}),t.jsxs("div",{className:"routine-card-meta",children:[e.steps&&e.steps.length>0?t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(Fa,{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(ta,{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:LD[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:OD[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:lc(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:lc(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(FD,{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(Li,{size:12}):t.jsx(gn,{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,w)=>t.jsx(zD,{result:g,index:w},`${g.startedAt}-${w}`)),e.runHistory.length>10&&t.jsxs("div",{className:"schedule-history-more",children:["…and ",e.runHistory.length-10," more"]})]})]})]})}function UD({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(ea,{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(ik,{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(ms,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function qd(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function HD(e){return e==="command"?{id:qd(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:qd(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:qd(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function qD({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??""),[w,v]=i.useState(e.taskTitle??""),[b,y]=i.useState(e.taskDescription??""),[S,j]=i.useState(e.taskColumn??"triage"),[C,x]=i.useState(e.timeoutMs),[N,R]=i.useState(e.continueOnFailure??!1),[F,E]=i.useState({}),[_,K]=i.useState([]),[U,A]=i.useState(!1),[T,H]=i.useState(null);i.useEffect(()=>{let D=!1;return A(!0),H(null),Ws().then($=>{D||K($.models)}).catch($=>{D||H($ instanceof Error?$.message:"Failed to load models")}).finally(()=>{D||A(!1)}),()=>{D=!0}},[]);const Q=i.useCallback(()=>{const D={};return a.trim()||(D.name="Step name is required"),o==="command"&&!c.trim()&&(D.command="Command is required"),o==="ai-prompt"&&!u.trim()&&(D.prompt="Prompt is required"),o==="create-task"&&!b.trim()&&(D.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(h||p)&&(!h||!p)&&(D.modelProvider="Both model provider and model ID must be set together"),C!==void 0&&C<1e3&&(D.timeoutMs="Timeout must be at least 1 second (1000ms)"),E(D),Object.keys(D).length===0},[a,o,c,u,b,h,p,C]),se=h&&p?`${h}/${p}`:"",O=i.useCallback(D=>{if(!D)f(""),g("");else{const $=D.indexOf("/");$!==-1&&(f(D.slice(0,$)),g(D.slice($+1)))}},[]),M=i.useCallback(()=>{if(!Q())return;const D={...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"&&w.trim()?w.trim():void 0,taskDescription:o==="create-task"&&b.trim()?b.trim():void 0,taskColumn:o==="create-task"?S:void 0,modelProvider:(o==="ai-prompt"||o==="create-task")&&h.trim()?h.trim():void 0,modelId:(o==="ai-prompt"||o==="create-task")&&p.trim()?p.trim():void 0,timeoutMs:C||void 0,continueOnFailure:N};o!=="ai-prompt"&&delete D.prompt,o!=="create-task"&&(delete D.taskTitle,delete D.taskDescription,delete D.taskColumn),n(D)},[Q,n,e,a,o,c,u,w,b,S,h,p,C,N]);return t.jsxs("div",{className:"step-editor",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-name-${e.id}`,children:"Step Name"}),t.jsx("input",{id:`step-name-${e.id}`,type:"text",placeholder:"e.g. Run tests",value:a,onChange:D=>r(D.target.value),"aria-invalid":!!F.name}),F.name&&t.jsx("small",{className:"field-error",children:F.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-type-${e.id}`,children:"Step Type"}),t.jsxs("select",{id:`step-type-${e.id}`,value:o,onChange:D=>l(D.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:D=>d(D.target.value),rows:2,"aria-invalid":!!F.command}),F.command&&t.jsx("small",{className:"field-error",children:F.command})]}),o==="ai-prompt"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-prompt-${e.id}`,children:"Prompt"}),t.jsx("textarea",{id:`step-prompt-${e.id}`,placeholder:"e.g. Summarize the test results and highlight any failures",value:u,onChange:D=>m(D.target.value),rows:3,"aria-invalid":!!F.prompt}),F.prompt&&t.jsx("small",{className:"field-error",children:F.prompt})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-model-${e.id}`,children:"Model (optional)"}),t.jsx(_s,{id:`step-model-${e.id}`,label:"Model",models:_,value:se,onChange:O,placeholder:"Use default",disabled:U}),T&&t.jsx("small",{className:"field-error",children:T}),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:w,onChange:D=>v(D.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:D=>y(D.target.value),rows:4,"aria-invalid":!!F.taskDescription}),F.taskDescription&&t.jsx("small",{className:"field-error",children:F.taskDescription})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-column-${e.id}`,children:"Target Column"}),t.jsxs("select",{id:`step-task-column-${e.id}`,value:S,onChange:D=>j(D.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(_s,{id:`step-task-model-${e.id}`,label:"Model",models:_,value:se,onChange:O,placeholder:"Use default",disabled:U}),T&&t.jsx("small",{className:"field-error",children:T}),F.modelProvider&&t.jsx("small",{className:"field-error",children:F.modelProvider}),t.jsx("small",{children:"AI model for executing the created task. Uses default if not selected."})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-timeout-${e.id}`,children:"Timeout (ms, optional)"}),t.jsx("input",{id:`step-timeout-${e.id}`,type:"number",min:1e3,step:1e3,placeholder:"Override schedule timeout",value:C??"",onChange:D=>x(D.target.value?Number(D.target.value):void 0),"aria-invalid":!!F.timeoutMs}),F.timeoutMs&&t.jsx("small",{className:"field-error",children:F.timeoutMs})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:`step-continue-${e.id}`,className:"checkbox-label",children:[t.jsx("input",{id:`step-continue-${e.id}`,type:"checkbox",checked:N,onChange:D=>R(D.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:M,children:"Save Step"})]})]})}function VD({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=HD(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(qD,{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(xc,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(UD,{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(Li,{})}),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(gn,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(u.id),title:"Edit","aria-label":`Edit ${u.name}`,children:t.jsx(Hs,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(u.id),title:"Delete","aria-label":`Delete ${u.name}`,children:t.jsx(Tn,{})})]})]})},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($n,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx($n,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx($n,{size:14}),"Add Create Task Step"]})]})]})}const Dv={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},WD={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function GD(e){const n=e.trim();for(const[s,a]of Object.entries(Dv))if(a===n)return s;return"custom"}function KD(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function JD(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 YD(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 QD=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],XD=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function Zf(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function eg({routine:e,onSubmit:n,onCancel:s,scope:a,projectId:r,onScopeChange:o}){const l=!!e,c=e?YD(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,w]=i.useState(c.cronExpression),[v,b]=i.useState(()=>c.triggerType!=="cron"?"custom":GD(c.cronExpression)),[y,S]=i.useState(c.webhookPath),[j,C]=i.useState(c.webhookSecret),[x,N]=i.useState(c.endpoint),[R,F]=i.useState(e?.executionPolicy??"queue"),[E,_]=i.useState(e?.catchUpPolicy??"run_one"),[K,U]=i.useState(e?.enabled??!0),A=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,T=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[H,Q]=i.useState(e?.steps&&e.steps.length>0&&!A&&!T?"advanced":"simple"),[se,O]=i.useState(()=>A?"ai-prompt":T?"create-task":"command"),[M,D]=i.useState(e?.command??""),[$,k]=i.useState(e?.steps??[]),[X,le]=i.useState(!1),[ke,He]=i.useState(e?.timeoutMs??3e5),[ye,je]=i.useState(A?e.steps?.[0]?.prompt??"":""),[ne,fe]=i.useState(T?e.steps?.[0]?.taskTitle??"":""),[Z,re]=i.useState(T?e.steps?.[0]?.taskDescription??"":""),[q,L]=i.useState(T?e.steps?.[0]?.taskColumn??"triage":"triage"),[xe,he]=i.useState(A||T?e.steps?.[0]?.modelProvider??"":""),[B,pe]=i.useState(A||T?e.steps?.[0]?.modelId??"":""),[ze,ae]=i.useState([]),[Ve,Te]=i.useState(!1),[rt,Be]=i.useState(null),[ce,Re]=i.useState(a??"global"),[Le,ct]=i.useState({}),[Ue,ue]=i.useState(!1),oe=i.useRef(!0);i.useEffect(()=>()=>{oe.current=!1},[]),i.useEffect(()=>{a&&Re(a)},[a]),i.useEffect(()=>{let be=!1;return Te(!0),Be(null),Ws().then(gt=>{be||ae(gt.models)}).catch(gt=>{be||Be(gt instanceof Error?gt.message:"Failed to load models")}).finally(()=>{be||Te(!1)}),()=>{be=!0}},[]);const Ee=xe&&B?`${xe}/${B}`:"",ft=i.useCallback(be=>{if(!be){he(""),pe("");return}const gt=be.indexOf("/");gt!==-1&&(he(be.slice(0,gt)),pe(be.slice(gt+1)))},[]),ht=i.useCallback(()=>{const be={};if(d.trim()||(be.name="Name is required"),ce==="project"&&!r&&(be.scope="Project-specific entries require an active project."),f==="cron"&&v==="custom"&&(g.trim()?KD(g)||(be.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):be.cronExpression="Cron expression is required"),f==="webhook"&&!y.trim()&&(be.webhookPath="Webhook path is required"),f==="api"&&!x.trim()&&(be.endpoint="API endpoint is required"),H==="simple")se==="command"&&!M.trim()&&(be.command="Command is required"),se==="ai-prompt"&&!ye.trim()&&(be.prompt="Prompt is required"),se==="create-task"&&!Z.trim()&&(be.taskDescription="Task description is required"),(xe.trim()&&!B.trim()||!xe.trim()&&B.trim())&&(be.model="Both model provider and model ID must be set, or both must be empty");else{$.length===0&&(be.steps="At least one step is required"),X&&(be.stepsEditing="Please save or cancel all step edits before saving the routine");const gt=[];$.forEach(($t,Ie)=>{$t.name?.trim()||gt.push(`Step ${Ie+1}: Name is required`),$t.type==="command"&&!$t.command?.trim()&>.push(`Step ${Ie+1}: Command is required`),$t.type==="ai-prompt"&&!$t.prompt?.trim()&>.push(`Step ${Ie+1}: Prompt is required`),$t.type==="create-task"&&!$t.taskDescription?.trim()&>.push(`Step ${Ie+1}: Task description is required`)}),gt.length>0&&(be.steps=gt.join("; "))}return ke<1e3&&(be.timeoutMs="Timeout must be at least 1 second (1000ms)"),ct(be),Object.keys(be).length===0},[d,f,g,v,y,x,ce,r,H,se,M,ye,Z,xe,B,$,X,ke]),tt=i.useCallback(async be=>{if(be.preventDefault(),!!ht()){ue(!0);try{let gt=e?.scope??ce??(r?"project":"global");gt==="project"&&!r&&(gt="global");const $t=JD(f,g,y,j,x);let Ie,ge;H==="simple"?se==="command"?Ie=M.trim()||void 0:se==="ai-prompt"?ge=[{id:Zf(),type:"ai-prompt",name:d.trim(),prompt:ye.trim(),modelProvider:xe.trim()||void 0,modelId:B.trim()||void 0}]:ge=[{id:Zf(),type:"create-task",name:d.trim(),taskTitle:ne.trim()||void 0,taskDescription:Z.trim(),taskColumn:q,modelProvider:xe.trim()||void 0,modelId:B.trim()||void 0}]:ge=$;const st={name:d.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:$t,command:Ie,steps:ge,timeoutMs:ke,executionPolicy:R,catchUpPolicy:E,enabled:K,scope:gt};await n(st)}finally{oe.current&&ue(!1)}}},[ht,n,d,m,f,g,y,j,x,H,se,M,ye,xe,B,ne,Z,q,$,ke,R,E,K,ce,r,e?.scope,e?.agentId]),xt="routine-name-error",Me="routine-cron-error",Ye="routine-webhook-error",dt="routine-endpoint-error",wt="routine-command-error",St="routine-prompt-error",Fe="routine-task-description-error",J="routine-model-error",me="routine-timeout-error",Ze=i.useCallback(be=>{b(be),be!=="custom"&&w(Dv[be])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:tt,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:be=>u(be.target.value),"aria-invalid":!!Le.name,"aria-describedby":Le.name?xt:void 0}),Le.name&&t.jsx("small",{id:xt,className:"field-error",children:Le.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:be=>h(be.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${ce==="global"?" active":""}`,onClick:()=>{Re("global"),o?.("global")},role:"radio","aria-checked":ce==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:"Global scope",children:[t.jsx(gc,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${ce==="project"?" active":""}`,onClick:()=>{Re("project"),o?.("project")},role:"radio","aria-checked":ce==="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(js,{size:12}),"Project"]})]}),t.jsx("small",{children:!r&&!e?.scope?"No active project. Routines will be created at global scope.":ce==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),Le.scope&&t.jsx("small",{className:"field-error",children:Le.scope})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Trigger Type"}),t.jsxs("div",{className:"routine-trigger-type-selector",role:"radiogroup","aria-label":"Trigger type",children:[t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="cron"?" active":""}`,onClick:()=>p("cron"),role:"radio","aria-checked":f==="cron",children:[t.jsx(Qg,{size:14}),"Cron"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="webhook"?" active":""}`,onClick:()=>p("webhook"),role:"radio","aria-checked":f==="webhook",children:[t.jsx(lb,{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(Xg,{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(ls,{size:14}),"Manual"]})]})]}),f==="cron"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-frequency",children:"Frequency"}),t.jsx("select",{id:"routine-frequency",value:v,onChange:be=>Ze(be.target.value),children:Object.entries(WD).map(([be,gt])=>t.jsx("option",{value:be,children:gt},be))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:g,onChange:be=>w(be.target.value),disabled:v!=="custom","aria-invalid":!!Le.cronExpression,"aria-describedby":Le.cronExpression?Me:void 0}),Le.cronExpression?t.jsx("small",{id:Me,className:"field-error",children:Le.cronExpression}):t.jsx("small",{children:v==="custom"?t.jsxs(t.Fragment,{children:["min hour day month weekday — ",t.jsx("a",{href:"https://crontab.guru",target:"_blank",rel:"noopener noreferrer",children:"crontab.guru"})]}):`Auto-filled from preset: ${g}`})]}),f==="webhook"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-path",children:"Webhook Path"}),t.jsx("input",{id:"routine-webhook-path",type:"text",placeholder:"/trigger/my-routine",value:y,onChange:be=>S(be.target.value),"aria-invalid":!!Le.webhookPath,"aria-describedby":Le.webhookPath?Ye:void 0}),Le.webhookPath?t.jsx("small",{id:Ye,className:"field-error",children:Le.webhookPath}):t.jsx("small",{children:"URL path for the webhook endpoint"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-secret",children:"Webhook Secret (optional)"}),t.jsx("input",{id:"routine-webhook-secret",type:"password",placeholder:"Optional — leave empty for unauthenticated webhooks",value:j,onChange:be=>C(be.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:x,onChange:be=>N(be.target.value),"aria-invalid":!!Le.endpoint,"aria-describedby":Le.endpoint?dt:void 0}),Le.endpoint?t.jsx("small",{id:dt,className:"field-error",children:Le.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${H==="simple"?" active":""}`,onClick:()=>Q("simple"),role:"radio","aria-checked":H==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${H==="advanced"?" active":""}`,onClick:()=>Q("advanced"),role:"radio","aria-checked":H==="advanced",children:"Multi-Step"})]}),t.jsx("small",{children:H==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),H==="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${se==="command"?" active":""}`,onClick:()=>O("command"),role:"radio","aria-checked":se==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${se==="ai-prompt"?" active":""}`,onClick:()=>O("ai-prompt"),role:"radio","aria-checked":se==="ai-prompt",children:"AI Prompt"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${se==="create-task"?" active":""}`,onClick:()=>O("create-task"),role:"radio","aria-checked":se==="create-task",children:"Create Task"})]})]}),se==="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:M,onChange:be=>D(be.target.value),"aria-invalid":!!Le.command,"aria-describedby":Le.command?wt:void 0}),Le.command?t.jsx("small",{id:wt,className:"field-error",children:Le.command}):t.jsx("small",{children:"Shell command to execute."})]}):se==="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:ye,onChange:be=>je(be.target.value),rows:3,"aria-invalid":!!Le.prompt,"aria-describedby":Le.prompt?St:void 0}),Le.prompt?t.jsx("small",{id:St,className:"field-error",children:Le.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(_s,{id:"routine-model",label:"Model",models:ze,value:Ee,onChange:ft,placeholder:"Use default",disabled:Ve}),rt&&t.jsx("small",{className:"field-error",children:rt}),Le.model&&t.jsx("small",{id:J,className:"field-error",children:Le.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:ne,onChange:be=>fe(be.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:Z,onChange:be=>re(be.target.value),rows:4,"aria-invalid":!!Le.taskDescription,"aria-describedby":Le.taskDescription?Fe:void 0}),Le.taskDescription?t.jsx("small",{id:Fe,className:"field-error",children:Le.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:q,onChange:be=>L(be.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(_s,{id:"routine-task-model",label:"Executor Model",models:ze,value:Ee,onChange:ft,placeholder:"Use default",disabled:Ve}),rt&&t.jsx("small",{className:"field-error",children:rt}),Le.model&&t.jsx("small",{id:J,className:"field-error",children:Le.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(VD,{steps:$,onChange:k,onEditingChange:le}),Le.steps&&t.jsx("small",{className:"field-error",children:Le.steps}),Le.stepsEditing&&t.jsx("small",{className:"field-error",children:Le.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:ke,onChange:be=>He(Number(be.target.value)),"aria-invalid":!!Le.timeoutMs,"aria-describedby":Le.timeoutMs?me:void 0}),Le.timeoutMs?t.jsx("small",{id:me,className:"field-error",children:Le.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:R,onChange:be=>F(be.target.value),children:QD.map(be=>t.jsx("option",{value:be.value,children:be.label},be.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:be=>_(be.target.value),children:XD.map(be=>t.jsx("option",{value:be.value,children:be.label},be.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:K,onChange:be=>U(be.target.checked)}),"Enabled"]}),t.jsx("small",{children:"When disabled, the routine will not run automatically"})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,disabled:Ue,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:Ue,children:Ue?"Saving…":l?"Save Changes":"Create Routine"})]})]})}const ZD=3e4;function eL({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({}),w=i.useRef(null);zi(w,!0,"fusion:automation-modal-size");const v=i.useMemo(()=>({scope:a,projectId:a==="project"?s:void 0}),[a,s]),b=i.useCallback(async()=>{try{const A=await LS(v);l(A),g(T=>{const H={...T};for(const Q of A){const se=H[Q.id];if(!se||!Q.lastRunResult)continue;const O=Q.lastRunResult;O.success===se.success&&(O.output||"")===se.output&&(O.error||"")===(se.error||"")&&delete H[Q.id]}return H})}catch(A){n(Se(A)||"Failed to load routines","error")}},[n,v]);i.useEffect(()=>{b()},[b]),i.useEffect(()=>{const A=setInterval(()=>{b()},ZD);return()=>clearInterval(A)},[b]),i.useEffect(()=>{const A=T=>{T.key==="Escape"&&(c!=="list"?(d("list"),m(void 0)):e())};return document.addEventListener("keydown",A),()=>document.removeEventListener("keydown",A)},[e,c]);const y=sa(e),S=i.useCallback(async A=>{try{await OS(A,v),n("Routine created","success"),d("list"),await b()}catch(T){n(Se(T)||"Failed to create routine","error")}},[n,b,v]),j=i.useCallback(A=>{m(A),d("edit")},[]),C=i.useCallback(async A=>{if(u)try{await Zm(u.id,A,v),n("Routine updated","success"),d("list"),m(void 0),await b()}catch(T){n(Se(T)||"Failed to update routine","error")}},[u,n,b,v]),x=i.useCallback(async A=>{try{await FS(A.id,v),n(`Deleted "${A.name}"`,"success"),await b()}catch(T){n(Se(T)||"Failed to delete routine","error")}},[n,b,v]),N=i.useCallback(async A=>{f(A.id);try{const{result:T}=await zS(A.id,v);g(H=>({...H,[A.id]:{output:T.output||"",error:T.error,success:T.success}})),T.success?n(`"${A.name}" completed successfully`,"success"):n(`"${A.name}" failed: ${T.error||"Unknown error"}`,"error"),await b()}catch(T){n(Se(T)||"Failed to run routine","error")}finally{f(null)}},[n,b,v]),R=i.useCallback(async A=>{try{await Zm(A.id,{enabled:!A.enabled},v),n(`"${A.name}" ${A.enabled?"disabled":"enabled"}`,"success"),await b()}catch(T){n(Se(T)||"Failed to toggle routine","error")}},[n,b,v]),F=i.useCallback(()=>{d("list"),m(void 0)},[]);i.useEffect(()=>{c!=="list"&&g({})},[c]);const E=i.useCallback(A=>{r(A),d("list"),m(void 0),g({})},[]),_=()=>c==="create"?t.jsx(eg,{onSubmit:S,onCancel:F,scope:a,projectId:s}):c==="edit"&&u?t.jsx(eg,{routine:u,onSubmit:C,onCancel:F,scope:a,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(ls,{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($n,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map(A=>t.jsx(BD,{routine:A,onEdit:j,onDelete:x,onRun:N,onToggle:R,running:h===A.id,lastRunOutput:p[A.id]??null},A.id))}),K=()=>_(),U=c==="list"&&o.length>0;return t.jsx("div",{className:"modal-overlay open",...y,children:t.jsxs("div",{ref:w,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(ls,{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(mn,{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(gc,{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(js,{size:14}),"Project"]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(ls,{size:14}),o.length," automation",o.length===1?"":"s"]})]}),t.jsx("div",{className:"scheduling-toolbar-right",children:U&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>d("create"),"aria-label":"Create new automation",children:[t.jsx($n,{size:14}),"New Automation"]})})]}),t.jsx("div",{className:"schedule-modal-content",id:"scheduled-tasks-content",children:K()})]})})}const tL=3e4,Iu=new Map,Vd=new Map;function tg(e){return e??"default"}function ng(e){const n=Iu.get(e);return n?Date.now()>=n.expiresAt?(Iu.delete(e),null):n:null}function nL(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 sL(e){const n=Vd.get(e);if(n)return n;const s=Po().then(({providers:a,ghCli:r})=>{const l={...nL(a,r),ghCli:r,expiresAt:Date.now()+tL};return Iu.set(e,l),l}).finally(()=>{Vd.delete(e)});return Vd.set(e,s),s}function Lv(e){const n=tg(e),s=ng(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=tg(e),p=ng(f);if(p)return r(p.hasAiProvider),l(p.hasGithub),c(p.ghCli),u(!1),m.current=!0,()=>{h=!0};m.current=!1;async function g(){!m.current&&u(!0);try{const v=await sL(f);if(h)return;r(v.hasAiProvider),l(v.hasGithub),c(v.ghCli)}catch{}finally{h||(m.current=!0,u(!1))}}return g(),()=>{h=!0}},[e]),i.useMemo(()=>({hasAiProvider:a,hasGithub:o,loading:d,hasWarnings:!a||!o}),[a,o,d])}function Ov({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(mn,{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 iL({isOpen:e,onClose:n,projectId:s,tasks:a,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const{confirm:d}=li(),u=oi();Mi(e);const{keyboardOverlap:m,viewportHeight:h,viewportOffsetTop:f,keyboardOpen:p}=aa({enabled:u==="mobile"}),g=p?{"--keyboard-overlap":`${m}px`,"--vv-offset-top":`${f}px`,...h!==null?{"--vv-height":`${h}px`}:{}}:{},[w,v]=i.useState(""),[b,y]=i.useState([]),[S,j]=i.useState(""),[C,x]=i.useState(""),[N,R]=i.useState([]),[F,E]=i.useState(!1),[_,K]=i.useState(""),[U,A]=i.useState(""),[T,H]=i.useState(""),[Q,se]=i.useState(""),[O,M]=i.useState(""),[D,$]=i.useState("default"),[k,X]=i.useState(!1),[le,ke]=i.useState([]),[He,ye]=i.useState(!1),[je,ne]=i.useState(void 0),[fe,Z]=i.useState(Ps),[re,q]=i.useState(void 0),[L,xe]=i.useState(!1),[he,B]=i.useState(""),[pe,ze]=i.useState(null),[ae,Ve]=i.useState([]),[Te,rt]=i.useState(!1),[Be,ce]=i.useState(!1),Re=i.useRef(null),[Le,ct]=i.useState(!1),[Ue,ue]=i.useState(""),oe=i.useRef(null),{hasAiProvider:Ee,hasGithub:ft,loading:ht}=Lv(s),{nodes:tt}=Cc(),xt=i.useCallback(ge=>{ye(!0),ke(ge)},[]),Me=i.useCallback(()=>{ye(!1)},[]),Ye=i.useCallback(async()=>{if(ae.length>0){rt(!0);return}ce(!0);try{const ge=await Ur(void 0,s);Ve(ge),rt(!0)}catch(ge){const st=Se(ge);o(st?`Failed to load agents: ${st}`:"Failed to load agents","error"),rt(!1)}finally{ce(!1)}},[ae.length,s,o]);i.useEffect(()=>{if(!Te)return;const ge=st=>{Re.current&&!Re.current.contains(st.target)&&rt(!1)};return document.addEventListener("mousedown",ge),()=>document.removeEventListener("mousedown",ge)},[Te]),i.useEffect(()=>{if(!Le)return;const ge=st=>{oe.current&&!oe.current.contains(st.target)&&(ct(!1),ue(""))};return document.addEventListener("mousedown",ge),()=>document.removeEventListener("mousedown",ge)},[Le]);const dt=a.filter(ge=>!b.includes(ge.id)).sort((ge,st)=>{const yt=st.createdAt.localeCompare(ge.createdAt);if(yt!==0)return yt;const pt=parseInt(ge.id.slice(ge.id.lastIndexOf("-")+1),10)||0;return(parseInt(st.id.slice(st.id.lastIndexOf("-")+1),10)||0)-pt}),wt=Ue?dt.filter(ge=>ge.id.toLowerCase().includes(Ue.toLowerCase())||ge.title&&ge.title.toLowerCase().includes(Ue.toLowerCase())||ge.description&&ge.description.toLowerCase().includes(Ue.toLowerCase())):dt,St=(ge,st)=>ge.length>st?ge.slice(0,st)+"…":ge,Fe=he.trim(),J=Fe.length>0&&!Sc.test(Fe);i.useEffect(()=>{const ge=w.trim()!==""||b.length>0||N.length>0||_!==""||U!==""||T!==""||Q!==""||le.length>0||pe!==null||je!==void 0||fe!==Ps||re!==void 0||S!==""||C!==""||L||Fe!=="";X(ge)},[w,b,N,_,U,T,Q,le,pe,je,fe,re,S,C,L,Fe]);const me=i.useCallback(async()=>{k&&!await d({title:"Discard Changes",message:"You have unsaved changes. Discard them?",danger:!0})||(N.forEach(ge=>URL.revokeObjectURL(ge.previewUrl)),R([]),v(""),y([]),K(""),A(""),H(""),se(""),M(""),$("default"),ke([]),ye(!1),ze(null),rt(!1),ne(void 0),Z(Ps),q(void 0),j(""),x(""),X(!1),xe(!1),B(""),n())},[k,n,N,d]),Ze=i.useCallback(async()=>{const ge=w.trim();if(!(!ge||F||J)){E(!0);try{const st=_.indexOf("/"),yt=U.indexOf("/"),pt=T.indexOf("/"),vt=await r({title:void 0,description:ge,column:"triage",dependencies:b.length?b:void 0,enabledWorkflowSteps:He?le.length>0?le:[]:void 0,...pe?{assignedAgentId:pe}:{},modelPresetId:D==="preset"&&O||void 0,modelProvider:_&&st!==-1?_.slice(0,st):void 0,modelId:_&&st!==-1?_.slice(st+1):void 0,validatorModelProvider:U&&yt!==-1?U.slice(0,yt):void 0,validatorModelId:U&&yt!==-1?U.slice(yt+1):void 0,planningModelProvider:T&&pt!==-1?T.slice(0,pt):void 0,planningModelId:T&&pt!==-1?T.slice(pt+1):void 0,thinkingLevel:Q!==""?Q:void 0,reviewLevel:je,priority:fe,nodeId:re,branch:S.trim()===""?void 0:S.trim(),baseBranch:C.trim()===""?void 0:C.trim(),...L||Fe!==""?{githubTracking:{enabled:L,...Fe!==""?{repoOverride:Fe}:{}}}:{}});if(N.length>0){const Ut=[];for(const Dt of N)try{await jc(vt.id,Dt.file,s)}catch{Ut.push(Dt.file.name)}Ut.length>0&&o(`Failed to upload: ${Ut.join(", ")}`,"error")}N.forEach(Ut=>URL.revokeObjectURL(Ut.previewUrl)),R([]),v(""),y([]),K(""),A(""),H(""),se(""),M(""),$("default"),ke([]),ye(!1),ze(null),rt(!1),ne(void 0),Z(Ps),q(void 0),j(""),x(""),o(`Created ${vt.id}`,"success"),n()}catch(st){o(Se(st)||"Failed to create task","error")}finally{E(!1)}}},[w,b,N,_,U,T,Q,F,r,o,n,s,D,O,le,He,pe,je,fe,re,S,C]),be=i.useCallback(ge=>{ge.key==="Escape"&&(ge.preventDefault(),me())},[me]),$t=(pe?ae.find(ge=>ge.id===pe):void 0)?.name??pe,Ie=t.jsxs("div",{className:"new-task-quick-fields",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"dep-trigger-wrap",ref:oe,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>ct(ge=>!ge),disabled:F,"data-testid":"dep-trigger",children:b.length>0?`${b.length} selected`:"Add dependencies"}),Le&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Ue,onChange:ge=>ue(ge.target.value),onClick:ge=>ge.stopPropagation()}),wt.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):wt.map(ge=>t.jsxs("div",{className:`dep-dropdown-item${b.includes(ge.id)?" selected":""}`,onClick:()=>{y(b.includes(ge.id)?b.filter(st=>st!==ge.id):[...b,ge.id]),ct(!1),ue("")},onMouseDown:st=>st.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:ge.id}),t.jsx("span",{className:"dep-dropdown-title",children:St(ge.title||ge.description||ge.id,30)})]},ge.id))]})]}),b.length>0&&t.jsx("div",{className:"selected-deps",children:b.map(ge=>t.jsxs("span",{className:"dep-chip",children:[ge,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>y(b.filter(st=>st!==ge)),disabled:F,children:"×"})]},ge))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:Re,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{Te?rt(!1):Ye()},disabled:F,"data-testid":"new-task-agent-button",children:[t.jsx(Qn,{size:12,style:{verticalAlign:"middle"}}),$t?` ${$t}`:" Assign agent"]}),Te&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:ge=>ge.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),Be&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!Be&&ae.map(ge=>t.jsxs("div",{className:`dep-dropdown-item${pe===ge.id?" selected":""}`,onMouseDown:st=>st.preventDefault(),onClick:()=>{ze(ge.id===pe?null:ge.id),rt(!1)},"data-testid":`agent-option-${ge.id}`,children:[t.jsx(Qn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:ge.role}),t.jsx("span",{className:"dep-dropdown-title",children:ge.name})]},ge.id)),!Be&&ae.length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),pe&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:ge=>ge.preventDefault(),onClick:()=>{ze(null),rt(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:me,onKeyDown:be,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:ge=>ge.stopPropagation(),style:g,children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:me,disabled:F,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!ht&&t.jsx(Ov,{hasAiProvider:Ee,hasGithub:ft}),t.jsx(gv,{mode:"create",description:w,onDescriptionChange:v,dependencies:b,onDependenciesChange:y,executorModel:_,onExecutorModelChange:K,validatorModel:U,onValidatorModelChange:A,presetMode:D,onPresetModeChange:$,selectedPresetId:O,onSelectedPresetIdChange:M,selectedWorkflowSteps:le,onWorkflowStepsChange:xt,onDefaultOnApplied:Me,pendingImages:N,onImagesChange:R,tasks:a,projectId:s,disabled:F,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:me,planningModel:T,onPlanningModelChange:H,thinkingLevel:Q,onThinkingLevelChange:se,reviewLevel:je,onReviewLevelChange:ne,priority:fe,onPriorityChange:Z,branch:S,onBranchChange:j,baseBranch:C,onBaseBranchChange:x,nodeId:re,onNodeIdChange:q,nodeOptions:tt,githubTrackingEnabled:L,onGithubTrackingEnabledChange:xe,githubRepoOverride:he,onGithubRepoOverrideChange:B,renderBelowPrimary:Ie,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:me,disabled:F,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Ze,disabled:!w.trim()||F||J,children:F?"Creating...":"Create Task"})]})]})}):null}function Ni(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 sg(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function aL(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function rL(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function oL(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function lL(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 Pl(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function cL(e){if(!e)return"Not yet";const n=new Date(e);return Number.isNaN(n.getTime())?"Not yet":n.toLocaleString()}function dL({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),[w,v]=i.useState(!1),[b,y]=i.useState(null),[S,j]=i.useState(null),[C,x]=i.useState(null),N=i.useCallback(async ne=>{l(!0);try{const fe=await w1(s);r(fe),d(null),x(Date.now()),ne?.preserveKillResult||y(null)}catch(fe){d(fe instanceof Error?fe.message:"Failed to load system stats")}finally{l(!1)}},[s]);i.useEffect(()=>{if(!e)return;N();const ne=window.setInterval(()=>{N()},5e3);return()=>{window.clearInterval(ne)}},[e,N]),i.useEffect(()=>{if(!e)return;(async()=>{try{const fe=await na();m(fe.vitestAutoKillEnabled??!0),f(fe.vitestKillThresholdPct??90),j(null)}catch(fe){j(fe instanceof Error?fe.message:"Failed to load vitest settings")}})()},[e]),i.useEffect(()=>{if(!e)return;const ne=fe=>{fe.key==="Escape"&&n()};return document.addEventListener("keydown",ne),()=>document.removeEventListener("keydown",ne)},[e,n]);const R=i.useMemo(()=>{if(!a)return[];const ne=a.systemStats,fe=Pl(aL(ne.heapUsed,ne.heapLimit)),Z=Pl(rL(ne.rss,ne.systemTotalMem));return[{label:"RSS",value:Ni(ne.rss),detail:sg(ne.rss,ne.systemTotalMem),className:Z},{label:"Heap Used",value:Ni(ne.heapUsed),detail:`of ${Ni(ne.heapTotal)}`,className:fe},{label:"Heap Limit",value:Ni(ne.heapLimit),detail:"V8 limit"},{label:"External",value:Ni(ne.external)},{label:"Array Buffers",value:Ni(ne.arrayBuffers)}]},[a]),F=i.useCallback(async ne=>{m(ne);try{await Bn({vitestAutoKillEnabled:ne}),j(null)}catch(fe){j(fe instanceof Error?fe.message:"Failed to save vitest settings")}},[]),E=i.useCallback(async ne=>{const fe=Math.min(99,Math.max(50,Number.isFinite(ne)?Math.round(ne):90));f(fe);try{await Bn({vitestKillThresholdPct:fe}),j(null)}catch(Z){j(Z instanceof Error?Z.message:"Failed to save vitest settings")}},[]),_=i.useCallback(async()=>{if(!p){if(!w){v(!0);return}g(!0);try{const ne=await k1(s);y(ne),v(!1),await N({preserveKillResult:!0})}catch(ne){d(ne instanceof Error?ne.message:"Failed to kill vitest processes")}finally{g(!1)}}},[w,p,N,s]);if(!e)return null;const K=a?.systemStats,U=o&&!!a,A=C?`Updated ${new Date(C).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`:"Waiting for first update",T=a?.taskStats,H=K?K.systemTotalMem-K.systemFreeMem:0,Q=K?oL(H,K.systemTotalMem):"normal",se=K?Pl(Q):"",O=K&&Number.isFinite(K.systemTotalMem)&&K.systemTotalMem>0?Math.max(0,Math.min(100,H/K.systemTotalMem*100)):0,M=K?`System memory used: ${O.toFixed(1)}% (${Ni(H)} of ${Ni(K.systemTotalMem)})`:"System memory usage unavailable",D=a?.vitestProcessCount,$=lL(K?.cpuPercent??null,K?.cpuCount??0),k=Pl($),X=K?.cpuPercent??null,le=X===null?0:Math.max(0,Math.min(100,X)),ke=X===null?"Sampling…":`${X.toFixed(1)}%`,He=X===null?"App CPU usage unavailable: waiting for another sample":`App CPU usage: ${X.toFixed(1)}%`,ye=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":"",je=cL(a?.vitestLastAutoKillAt);return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"system-stats-modal-title",onClick:ne=>{ne.target===ne.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(Cr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("div",{className:"system-stats-modal__header-actions",children:[t.jsxs("span",{className:"system-stats-modal__auto-refresh","aria-live":"polite",children:[t.jsx("span",{children:"Auto-refresh · 5s"}),t.jsx("span",{className:"system-stats-modal__auto-refresh-time",children:A})]}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void N(),title:"Refresh","aria-label":"Refresh system stats",children:t.jsx(ps,{size:16,className:U?"system-stats-modal__refresh--spinning":void 0})}),t.jsx("button",{type:"button",className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(mn,{})})]})]}),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:R.map(ne=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:ne.label}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${ne.className}`.trim(),children:ne.value}),ne.detail?t.jsx("span",{className:"system-stats-modal__detail",children:ne.detail}):null]})]},ne.label))})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"CPU and load stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"CPU & Load"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row system-stats-modal__row--cpu-used",children:[t.jsx("dt",{children:"App CPU"}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${k}`.trim(),children:ke}),t.jsx("span",{className:"system-stats-modal__detail",children:X===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(le),"aria-valuemin":0,"aria-valuemax":100,"aria-label":He,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${$}`,style:{width:`${le}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Load Avg"}),t.jsx("dd",{children:K?.loadAvg.map(ne=>ne.toFixed(2)).join(" ")??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Cores"}),t.jsx("dd",{children:K?.cpuCount??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Platform"}),t.jsx("dd",{children:K?.platform??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Node"}),t.jsx("dd",{children:K?.nodeVersion??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"PID"}),t.jsx("dd",{children:K?.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 ${se}`.trim(),children:K?Ni(H):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:K?`${sg(H,K.systemTotalMem)} of ${Ni(K.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--${Q}`,role:"progressbar","aria-valuenow":Math.round(O),"aria-valuemin":0,"aria-valuemax":100,"aria-label":M,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${Q}`,style:{width:`${O}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Free"}),t.jsx("dd",{children:K?Ni(K.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:T?.total??0})]}),Object.entries(T?.byColumn??{}).map(([ne,fe])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:ne}),t.jsx("dd",{children:fe})]},ne))]})]}),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:T?.agents.idle??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"active"}),t.jsx("dd",{children:T?.agents.active??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"running"}),t.jsx("dd",{children:T?.agents.running??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"error"}),t.jsx("dd",{children:T?.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(Vk,{}),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:D??"—"})]})}),t.jsxs("div",{className:"system-stats-modal__vitest-controls",children:[t.jsx("div",{className:"system-stats-modal__kill-row",children:t.jsxs("button",{type:"button",className:"btn btn-danger",onClick:()=>void _(),disabled:p||D===0,children:[t.jsx(Jk,{}),t.jsx("span",{children:w?"Confirm Kill?":"Kill Vitest Processes"})]})}),t.jsxs("label",{className:"system-stats-modal__toggle-row",children:[t.jsx("input",{type:"checkbox",checked:u,onChange:ne=>{F(ne.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:ne=>{const fe=Number.parseInt(ne.target.value,10);E(Number.isNaN(fe)?90:fe)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:h,"aria-label":"Kill threshold (%)",onChange:ne=>{const fe=Number.parseInt(ne.target.value,10);E(Number.isNaN(fe)?90:fe)},onBlur:()=>{E(h)}})]})]}),b&&t.jsxs("p",{className:ye,children:["Killed ",b.killed," processes"]}),t.jsxs("p",{className:"system-stats-modal__last-kill",children:["Last auto-kill: ",je]}),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 uL=5e3;function mL(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),w=i.useRef(void 0),v=i.useCallback(async()=>{try{u(!0),h(null);let S;o?S=await oh({limit:a,projectId:n,type:s}):S=(await eh({limit:a,type:s,projectId:n})).map(C=>({...C,projectId:n??"",projectName:""})),c(S),p(S.length===a),S.length>0&&(w.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(w.current)try{u(!0);let S;o?S=await oh({limit:a,projectId:n,type:s,since:w.current}):S=(await eh({limit:a,type:s,since:w.current,projectId:n})).map(C=>({...C,projectId:n??"",projectName:""})),c(j=>[...j,...S]),p(S.length===a),S.length>0&&(w.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),w.current=void 0},[]);return i.useEffect(()=>{v()},[v]),i.useEffect(()=>{if(r)return g.current=setInterval(()=>{v()},uL),()=>{g.current&&(clearInterval(g.current),g.current=null)}},[r,v]),{entries:l,loading:d,error:m,refresh:v,clear:y,hasMore:f,loadMore:b}}const Wd={"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"},hL={"task:created":t.jsx($n,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(Uo,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(ps,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(mn,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(Xn,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(Ho,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(Co,{size:14,className:"activity-icon settings"})};function pL(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 fL({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,w=m==="all"?void 0:m,v=!c&&o.length>0,{entries:b,loading:y,error:S,refresh:j,hasMore:C}=mL({projectId:w,type:g,limit:100,autoRefresh:e,useCentralFeed:v}),x=b.map(_=>({id:_.id,timestamp:_.timestamp,type:_.type,taskId:_.taskId,taskTitle:_.taskTitle,details:_.details,metadata:_.metadata,projectId:_.projectId,projectName:_.projectName})),N=async()=>{try{await BS(),j(),p(!1)}catch{p(!1)}},R=_=>{a&&a(_)},F=_=>{h(_),l?.(_==="all"?void 0:_)};i.useEffect(()=>{if(!e)return;const _=K=>{K.key==="Escape"&&(f?p(!1):n())};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[e,n,f]);const E=d!=="all"||m!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:_=>{_.target===_.currentTarget&&n()},role:"dialog","aria-modal":"true","data-testid":"activity-log-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg activity-log-modal","data-testid":"activity-log-modal",children:[t.jsxs("div",{className:"modal-header activity-log-header",children:[t.jsxs("div",{className:"activity-log-title",children:[t.jsx(Oa,{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(js,{size:14}),t.jsxs("select",{value:m,onChange:_=>F(_.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map(_=>t.jsx("option",{value:_.id,children:_.name},_.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(ql,{size:14}),t.jsxs("select",{value:d,onChange:_=>u(_.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(Wd).map(([_,K])=>t.jsx("option",{value:_,children:K},_))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>j(),title:"Refresh","data-testid":"activity-refresh",children:y?t.jsx(jt,{size:14,className:"spin"}):t.jsx(ps,{size:14})}),x.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:t.jsx(Tn,{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(_=>_.id===m)?.name||m]}),d!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",Wd[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(Vs,{size:16}),t.jsx("span",{children:S})]}),x.length===0&&!y&&!S&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(Oa,{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:x.map(_=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:hL[_.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:Wd[_.type]}),t.jsx("span",{className:"activity-log-entry-time",children:pL(_.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[_.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>R(_.taskId),"data-testid":"activity-task-link",children:_.taskId}),_.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:_.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:Cs(_.details??"")})]}),_.metadata&&Object.keys(_.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof _.metadata.from=="string"&&typeof _.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[_.metadata.from," → ",_.metadata.to]}),typeof _.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${_.metadata.merged?"success":"error"}`,children:_.metadata.merged?"Merged":"Not merged"})]})]})]},_.id))}),C&&!y&&t.jsx("button",{className:"activity-log-load-more",onClick:j,"data-testid":"activity-load-more",children:"Load More"}),y&&x.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(jt,{size:20,className:"spin"})})]}),f&&t.jsx("div",{className:"activity-log-confirm-overlay",children:t.jsxs("div",{className:"activity-log-confirm-dialog",children:[t.jsx("h3",{children:"Clear Activity Log?"}),t.jsx("p",{children:"This will permanently delete all activity log entries. This action cannot be undone."}),t.jsxs("div",{className:"activity-log-confirm-actions",children:[t.jsx("button",{className:"activity-log-confirm-cancel",onClick:()=>p(!1),children:"Cancel"}),t.jsx("button",{className:"activity-log-confirm-clear",onClick:N,children:"Clear Log"})]})]})})]})}):null}const ho=[{id:"status",label:"Status",icon:rb},{id:"changes",label:"Changes",icon:su},{id:"commits",label:"Commits",icon:Nr},{id:"branches",label:"Branches",icon:Os},{id:"worktrees",label:"Worktrees",icon:Uw},{id:"stashes",label:"Stashes",icon:zo},{id:"remotes",label:"Remotes",icon:sb}];function ig({status:e}){switch(e){case"added":case"untracked":return t.jsx(ww,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(tb,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(xw,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(xa,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(jw,{size:14,className:"gm-file-icon"})}}function ag({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 gL(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 Tr(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 bL({isOpen:e,onClose:n,tasks:s,addToast:a,projectId:r}){const o=li(),l=oi();Mi(e);const{keyboardOverlap:c,viewportHeight:d,viewportOffsetTop:u,keyboardOpen:m}=aa({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 Y=document.activeElement;Y instanceof HTMLElement&&Y.blur(),window.scrollTo(0,0),requestAnimationFrame(()=>{window.scrollTo(0,0)})}n()},[n,l]),[p,g]=i.useState("status"),[w,v]=i.useState(!1),[b,y]=i.useState(null),S=i.useRef(null);zi(S,e,"fusion:git-modal-size");const j=sa(f),C=gL(a),[x,N]=i.useState(null),[R,F]=i.useState([]),[E,_]=i.useState(new Set),[K,U]=i.useState(""),[A,T]=i.useState(!1),[H,Q]=i.useState(null),[se,O]=i.useState(!1),[M,D]=i.useState(null),[$,k]=i.useState(null),X=i.useRef(0),[le,ke]=i.useState([]),[He,ye]=i.useState(null),[je,ne]=i.useState(null),[fe,Z]=i.useState(!1),[re,q]=i.useState(20),[L,xe]=i.useState(""),[he,B]=i.useState([]),[pe,ze]=i.useState(""),[ae,Ve]=i.useState(""),[Te,rt]=i.useState(""),[Be,ce]=i.useState(null),[Re,Le]=i.useState([]),[ct,Ue]=i.useState(!1),[ue,oe]=i.useState(null),[Ee,ft]=i.useState(null),[ht,tt]=i.useState(!1),[xt,Me]=i.useState([]),[Ye,dt]=i.useState([]),[wt,St]=i.useState(""),[Fe,J]=i.useState(null),[me,Ze]=i.useState(null),[be,gt]=i.useState(null),[$t,Ie]=i.useState(!1),[ge,st]=i.useState(null),yt=i.useRef(0),[pt,vt]=i.useState(null),[Ut,Dt]=i.useState(null),nn=i.useCallback(async()=>{if(e){v(!0),y(null);try{switch(p){case"status":{const Y=await ji(r);N(Y);break}case"changes":{const[Y,_e]=await Promise.all([ji(r),cr(r)]);N(Y),F(_e),_(new Set),k(null),Q(null),D(null);break}case"commits":{const Y=await qN(re,r);ke(Y);break}case"branches":{const[Y,_e]=await Promise.all([Xr(r),ji(r)]);B(Y),N(_e);break}case"worktrees":{const Y=await KN(r);Me(Y);break}case"stashes":{const Y=await al(r);dt(Y),Ze(null),gt(null),st(null),yt.current+=1;break}case"remotes":{const Y=await ji(r);N(Y);break}}}catch(Y){y(Se(Y)||"Failed to fetch git data"),a(Se(Y)||"Failed to fetch git data","error")}finally{v(!1)}}},[p,e,re,a,r]);i.useEffect(()=>{e&&nn()},[nn,e]),i.useEffect(()=>{if(!e)return;const Y=_e=>{if(_e.key==="Escape"){f();return}if((_e.key==="ArrowUp"||_e.key==="ArrowDown")&&_e.altKey){_e.preventDefault();const ut=ho.findIndex(At=>At.id===p);_e.key==="ArrowUp"&&ut>0?g(ho[ut-1].id):_e.key==="ArrowDown"&&ut<ho.length-1&&g(ho[ut+1].id)}};return document.addEventListener("keydown",Y),()=>document.removeEventListener("keydown",Y)},[e,f,p]);const on=i.useCallback(async Y=>{try{await Km(Y,r),a(`Staged ${Y.length} file(s)`,"success");const _e=await cr(r);F(_e),_(new Set),k(null),Q(null),D(null)}catch(_e){a(Se(_e)||"Failed to stage files","error")}},[a,r]),sn=i.useCallback(async Y=>{try{await aS(Y,r),a(`Unstaged ${Y.length} file(s)`,"success");const _e=await cr(r);F(_e),_(new Set),k(null),Q(null),D(null)}catch(_e){a(Se(_e)||"Failed to unstage files","error")}},[a,r]),ln=i.useCallback(async Y=>{if(await o.confirm({title:"Discard Changes",message:`Discard changes to ${Y.length} file(s)? This cannot be undone.`,danger:!0}))try{await rS(Y,r),a(`Discarded changes to ${Y.length} file(s)`,"success");const[ut,At]=await Promise.all([cr(r),ji(r)]);F(ut),N(At),_(new Set),k(null),Q(null),D(null)}catch(ut){a(Se(ut)||"Failed to discard changes","error")}},[a,r,o]),xn=i.useCallback(async Y=>{if(Y.preventDefault(),!!K.trim()){T(!0);try{const _e=await Jm(K.trim(),r);a(`Committed: ${_e.hash}`,"success"),U("");const[ut,At]=await Promise.all([cr(r),ji(r)]);F(ut),N(At),k(null),Q(null),D(null)}catch(_e){a(Se(_e)||"Failed to commit","error")}finally{T(!1)}}},[K,a,r]),qt=i.useCallback(async()=>{if(K.trim()){T(!0);try{const Y=R.filter(zt=>!zt.staged).map(zt=>zt.file);Y.length>0&&await Km(Y,r);const _e=await Jm(K.trim(),r);a(`Committed: ${_e.hash}`,"success"),U("");const[ut,At]=await Promise.all([cr(r),ji(r)]);F(ut),N(At),k(null),Q(null),D(null)}catch(Y){a(Se(Y)||"Failed to commit","error")}finally{T(!1)}}},[K,R,a,r]),Qt=i.useCallback(async(Y,_e)=>{k({file:Y,staged:_e}),O(!0),D(null);const ut=X.current+1;X.current=ut;try{const At=await iS(Y,_e,r);if(X.current!==ut)return;Q(At)}catch(At){if(X.current!==ut)return;const zt=Se(At)||"Failed to load file diff";Q(null),D(zt),a(zt,"error")}finally{X.current===ut&&O(!1)}},[a,r]),hn=i.useCallback(Y=>{_(_e=>{const ut=new Set(_e);return ut.has(Y)?ut.delete(Y):ut.add(Y),ut})},[]),Zt=i.useCallback(async Y=>{if(He===Y){ye(null),ne(null);return}ye(Y),Z(!0);try{const _e=await Jl(Y,r);ne(_e)}catch(_e){a(Se(_e)||"Failed to load diff","error"),ne(null)}finally{Z(!1)}},[He,a,r]),ve=i.useCallback(()=>{q(Y=>Math.min(Y+20,100))},[]),Pe=i.useMemo(()=>{if(!L.trim())return le;const Y=L.toLowerCase();return le.filter(_e=>_e.message.toLowerCase().includes(Y)||_e.author.toLowerCase().includes(Y)||_e.shortHash.toLowerCase().includes(Y))},[le,L]),Ke=i.useCallback(async Y=>{if(Y.preventDefault(),!!pe.trim()){v(!0);try{await JN(pe.trim(),ae.trim()||void 0,r),a(`Created branch ${pe}`,"success"),ze(""),Ve("");const _e=await Xr(r);B(_e)}catch(_e){a(Se(_e)||"Failed to create branch","error")}finally{v(!1)}}},[pe,ae,a,r]),at=i.useCallback(async Y=>{v(!0);try{await YN(Y,r),a(`Switched to ${Y}`,"success");const[_e,ut]=await Promise.all([ji(r),Xr(r)]);N(_e),B(ut)}catch(_e){a(Se(_e)||"Failed to checkout branch","error")}finally{v(!1)}},[a,r]),We=i.useCallback(async Y=>{if(await o.confirm({title:"Delete Branch",message:`Delete branch "${Y}"?`,danger:!0})){v(!0);try{await Gm(Y,void 0,r),a(`Deleted branch ${Y}`,"success");const ut=await Xr(r);B(ut)}catch(ut){if(Se(ut).includes("not fully merged")){if(await o.confirm({title:"Force Delete Branch",message:"Branch has unmerged commits. Force delete?",danger:!0}))try{await Gm(Y,!0,r),a(`Force deleted branch ${Y}`,"success");const zt=await Xr(r);B(zt)}catch(zt){a(Se(zt)||"Failed to delete branch","error")}}else a(Se(ut)||"Failed to delete branch","error")}finally{v(!1)}}},[a,r,o]),It=i.useMemo(()=>{if(!Te.trim())return he;const Y=Te.toLowerCase();return he.filter(_e=>_e.name.toLowerCase().includes(Y))},[he,Te]),Lt=i.useCallback(async Y=>{if(Be===Y){ce(null),Le([]),oe(null),ft(null);return}ce(Y),Le([]),oe(null),ft(null),Ue(!0);try{const _e=await GN(Y,10,r);Le(_e)}catch{Le([])}finally{Ue(!1)}},[Be,r]),Bt=i.useCallback(async Y=>{if(ue===Y){oe(null),ft(null);return}oe(Y),ft(null),tt(!0);try{const _e=await Jl(Y,r);ft(_e)}catch{ft(null)}finally{tt(!1)}},[ue,r]),Gt=i.useCallback(()=>{ce(null),Le([]),oe(null),ft(null)},[]),bt=i.useCallback(()=>{yt.current+=1,Ze(null),gt(null),st(null),Ie(!1)},[]),Ot=i.useCallback(async Y=>{Y.preventDefault(),J("create"),bt();try{await eS(wt.trim()||void 0,r),a("Changes stashed","success"),St("");const _e=await al(r);dt(_e)}catch(_e){a(Se(_e)||"Failed to stash changes","error")}finally{J(null)}},[wt,a,r,bt]),en=i.useCallback(async(Y,_e=!1)=>{J(`apply-${Y}`),bt();try{await tS(Y,_e,r),a(_e?"Stash popped":"Stash applied","success");const ut=await al(r);dt(ut)}catch(ut){a(Se(ut)||"Failed to apply stash","error")}finally{J(null)}},[a,r,bt]),Kt=i.useCallback(async Y=>{if(await o.confirm({title:"Drop Stash",message:`Drop stash@{${Y}}? This cannot be undone.`,danger:!0})){J(`drop-${Y}`),bt();try{await nS(Y,r),a("Stash dropped","success");const ut=await al(r);dt(ut)}catch(ut){a(Se(ut)||"Failed to drop stash","error")}finally{J(null)}}},[a,r,o,bt]),Sn=i.useCallback(async Y=>{if(me===Y){bt();return}const _e=yt.current+1;yt.current=_e,Ze(Y),gt(null),st(null),Ie(!0);try{const ut=await sS(Y,r);if(yt.current!==_e)return;gt(ut)}catch(ut){if(yt.current!==_e)return;gt(null),st(Se(ut)||"Failed to load stash diff")}finally{yt.current===_e&&Ie(!1)}},[me,r,bt]),dn=i.useCallback(async()=>{vt("fetch");try{const Y=await QN(void 0,r);Dt(Y),a(Y.message||"Fetch completed",Y.fetched?"success":"info");const _e=await ji(r);N(_e)}catch(Y){a(Se(Y)||"Fetch failed","error")}finally{vt(null)}},[a,r]),Jt=i.useCallback(async Y=>{vt("pull");try{const _e=await XN(Y,r);if(Dt(_e),_e.conflict)a("Merge conflict detected. Resolve manually.","error");else{const At=Y?.rebase?"Pull --rebase completed":"Pull completed";a(_e.message||At,"success")}const ut=await ji(r);N(ut)}catch(_e){a(Se(_e)||"Pull failed","error")}finally{vt(null)}},[a,r]),tn=i.useCallback(async()=>{vt("push");try{const Y=await ZN(r);Dt(Y),a(Y.message||"Push completed","success");const _e=await ji(r);N(_e)}catch(Y){a(Se(Y)||"Push failed","error")}finally{vt(null)}},[a,r]),Ne=i.useMemo(()=>R.filter(Y=>Y.staged),[R]),W=i.useMemo(()=>R.filter(Y=>!Y.staged),[R]);return e?t.jsx("div",{className:"modal-overlay open git-manager-modal-overlay",...j,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal gm-modal",ref:S,style:h,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h3",{children:[t.jsx(iu,{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:nn,disabled:w,title:"Refresh",children:t.jsx(ps,{size:14,className:w?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:f,"aria-label":"Close",children:t.jsx(mn,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:ho.map(Y=>{const _e=Y.icon;return t.jsxs("button",{role:"tab","aria-selected":p===Y.id,className:`gm-nav-item${p===Y.id?" active":""}`,onClick:()=>g(Y.id),children:[t.jsx(_e,{size:16}),t.jsx("span",{className:"gm-nav-label",children:Y.label})]},Y.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[w&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(jt,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),b&&!w&&t.jsxs("div",{className:"gm-error",children:[t.jsx(Vs,{size:18}),t.jsx("span",{children:b}),t.jsx("button",{className:"btn btn-sm",onClick:nn,children:"Retry"})]}),p==="status"&&!w&&x&&t.jsx(xL,{status:x,copyToClipboard:C}),p==="changes"&&!w&&t.jsx(vL,{status:x,stagedFiles:Ne,unstagedFiles:W,selectedFiles:E,toggleFileSelection:hn,onStageFiles:on,onUnstageFiles:sn,onDiscardChanges:ln,onSelectDiffFile:Qt,selectedDiffTarget:$,changeDiff:H,loadingChangeDiff:se,changeDiffError:M,commitMessage:K,setCommitMessage:U,onCommit:xn,onStageAllAndCommit:qt,committing:A}),p==="commits"&&!w&&t.jsx(yL,{commits:Pe,commitSearch:L,setCommitSearch:xe,selectedCommit:He,commitDiff:je,loadingDiff:fe,onCommitClick:Zt,onLoadMore:ve,canLoadMore:le.length>=re&&re<100,copyToClipboard:C}),p==="branches"&&!w&&t.jsx(wL,{branches:It,branchSearch:Te,setBranchSearch:rt,newBranchName:pe,setNewBranchName:ze,branchBase:ae,setBranchBase:Ve,onCreateBranch:Ke,onCheckoutBranch:at,onDeleteBranch:We,loading:w,allBranches:he,selectedBranch:Be,branchCommits:Re,loadingBranchCommits:ct,expandedBranchCommit:ue,branchCommitDiff:Ee,loadingBranchCommitDiff:ht,onSelectBranch:Lt,onBranchCommitClick:Bt,onCloseBranchDetails:Gt}),p==="worktrees"&&!w&&t.jsx(kL,{worktrees:xt}),p==="stashes"&&!w&&t.jsx(jL,{stashes:Ye,stashMessage:wt,setStashMessage:St,onCreateStash:Ot,onApplyStash:en,onDropStash:Kt,onToggleStashDiff:Sn,stashLoading:Fe,expandedStashIndex:me,stashDiff:be,loadingStashDiff:$t,stashDiffError:ge}),p==="remotes"&&!w&&t.jsx(NL,{status:x,remoteLoading:pt,lastRemoteResult:Ut,onFetch:dn,onPull:Jt,onPush:tn,addToast:a,projectId:r,copyToClipboard:C})]})]})]})}):null}function xL({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(Os,{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(ba,{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(Vs,{size:12}),"Modified"]}):t.jsxs(t.Fragment,{children:[t.jsx(Xn,{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(La,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx(Bo,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(Xn,{size:12}),"Up to date"]})]})]})]})]})}function vL({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:w,onStageAllAndCommit:v,committing:b}){const y=s.filter(j=>a.has(`unstaged:${j.file}`)),S=n.filter(j=>a.has(`staged:${j.file}`));return t.jsxs("div",{className:"gm-panel","data-testid":"changes-panel",children:[e&&t.jsxs("div",{className:"gm-changes-header",children:[t.jsxs("span",{className:"gm-branch-indicator",children:[t.jsx(Os,{size:14}),e.branch]}),e.isDirty&&t.jsx("span",{className:"gm-dirty-badge",children:"Modified"})]}),t.jsxs("div",{className:"gm-changes-split",children:[t.jsxs("div",{className:"gm-changes-lists",children:[t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Unstaged Changes (",s.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[y.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(y.map(j=>j.file)),title:"Stage selected",children:[t.jsx($n,{size:12})," Stage (",y.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(y.map(j=>j.file)),title:"Discard selected",children:t.jsx(Ho,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(j=>j.file)),title:"Stage all",children:"Stage All"})]})]}),t.jsx("div",{className:"gm-file-list gm-file-list-unstaged","data-testid":"gm-file-list-unstaged",children:s.length===0?t.jsx("div",{className:"gm-empty",children:"No unstaged changes"}):s.map(j=>{const C=u?.file===j.file&&u.staged===!1;return t.jsxs("div",{className:`gm-file-item${C?" active":""}`,onClick:()=>d(j.file,!1),role:"button",tabIndex:0,onKeyDown:x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),d(j.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:x=>x.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`unstaged:${j.file}`),onChange:()=>r(`unstaged:${j.file}`)})}),t.jsx(ig,{status:j.status}),t.jsx("span",{className:"gm-file-name",title:j.file,children:t.jsx("bdo",{dir:"ltr",children:j.file})}),t.jsx(ag,{status:j.status}),t.jsx("button",{className:"gm-icon-btn",onClick:x=>{x.stopPropagation(),o([j.file])},title:"Stage file",children:t.jsx($n,{size:12})})]},`unstaged:${j.file}`)})})]}),t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Staged Changes (",n.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[S.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(S.map(j=>j.file)),title:"Unstage selected",children:["Unstage (",S.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(j=>j.file)),title:"Unstage all",children:"Unstage All"})]})]}),t.jsx("div",{className:"gm-file-list gm-file-list-staged","data-testid":"gm-file-list-staged",children:n.length===0?t.jsx("div",{className:"gm-empty",children:"No staged changes"}):n.map(j=>{const C=u?.file===j.file&&u.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${C?" active":""}`,onClick:()=>d(j.file,!0),role:"button",tabIndex:0,onKeyDown:x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),d(j.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:x=>x.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`staged:${j.file}`),onChange:()=>r(`staged:${j.file}`)})}),t.jsx(ig,{status:j.status}),t.jsx("span",{className:"gm-file-name",title:j.file,children:t.jsx("bdo",{dir:"ltr",children:j.file})}),t.jsx(ag,{status:j.status}),t.jsx("button",{className:"gm-icon-btn",onClick:x=>{x.stopPropagation(),l([j.file])},title:"Unstage file",children:t.jsx(mn,{size:12})})]},`staged:${j.file}`)})})]})]}),t.jsx("div",{className:"gm-changes-diff",children:u||h||m||f?t.jsxs("div",{className:"gm-diff-section",children:[u&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(su,{size:14}),t.jsxs("span",{children:[u.staged?"Staged":"Unstaged"," diff: "]}),t.jsx("code",{children:u.file})]}),h&&t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading diff..."]}),f&&!h&&t.jsx("div",{className:"gm-diff-error",children:f}),m&&!h&&t.jsxs("div",{className:"gm-diff-viewer",children:[m.stat&&t.jsx("pre",{className:"gm-diff-stat",children:m.stat}),t.jsx("pre",{className:"gm-diff-patch",children:m.patch})]})]}):t.jsxs("div",{className:"gm-diff-empty",children:[t.jsx(su,{size:20}),t.jsx("span",{children:"Select a file to view its diff"})]})})]}),t.jsxs("form",{className:"gm-commit-form",onSubmit:w,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:j=>g(j.target.value),rows:3,disabled:b}),t.jsxs("div",{className:"gm-commit-actions",children:[t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:b||!p.trim()||n.length===0,title:n.length===0?"No staged changes to commit":"Commit staged changes",children:[b?t.jsx(jt,{size:14,className:"spin"}):t.jsx(Da,{size:14}),"Commit"]}),s.length>0&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:v,disabled:b||!p.trim(),title:"Stage all and commit",children:"Stage All & Commit"})]})]})]})}function yL({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(Xi,{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:Tr(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(ba,{size:12})})}),a===m.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading diff..."]}):r?t.jsxs(t.Fragment,{children:[m.body&&t.jsx("div",{className:"gm-commit-message-full",children:m.body}),r.stat&&t.jsx("pre",{className:"gm-diff-stat",children:r.stat}),t.jsx("pre",{className:"gm-diff-patch",children:r.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]})]},m.hash))}),d&&t.jsx("button",{className:"gm-load-more",onClick:c,children:"Load more commits"})]})}function wL({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:w,branchCommitDiff:v,loadingBranchCommitDiff:b,onSelectBranch:y,onBranchCommitClick:S,onCloseBranchDetails:j}){return t.jsxs("div",{className:"gm-panel","data-testid":"branches-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Branches"}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(Xi,{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($n,{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(ks,{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:Tr(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:x=>{x.stopPropagation(),d(C.name)},disabled:m,title:"Checkout",children:t.jsx(Os,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:x=>{x.stopPropagation(),u(C.name)},disabled:m,title:"Delete",children:t.jsx(Tn,{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(Nr,{size:14}),"Commits on ",C.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:j,title:"Close","data-testid":"close-branch-details",children:t.jsx(mn,{size:14})})]}),g?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading commits..."]}):p.length===0?t.jsx("div",{className:"gm-empty",children:"No commits found"}):t.jsx("div",{className:"gm-branch-commits-list",children:p.map(x=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>S(x.hash),"data-testid":`branch-commit-${x.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:x.shortHash}),t.jsx("span",{className:"gm-commit-message",title:x.message,children:x.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:x.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Tr(x.date)}),x.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),w===x.hash&&t.jsx("div",{className:"gm-commit-diff",children:b?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading diff..."]}):v?t.jsxs(t.Fragment,{children:[(x.body||x.message)&&t.jsx("div",{className:"gm-commit-message-full",children:x.body||x.message}),v.stat&&t.jsx("pre",{className:"gm-diff-stat",children:v.stat}),t.jsx("pre",{className:"gm-diff-patch",children:v.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},x.hash))})]})]},C.name))})]})}function kL({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:Ju(n.path)||n.path})]}),t.jsxs("div",{className:"gm-worktree-detail",children:[n.branch&&t.jsxs("span",{className:"gm-worktree-branch",children:[t.jsx(Os,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function jL({stashes:e,stashMessage:n,setStashMessage:s,onCreateStash:a,onApplyStash:r,onDropStash:o,onToggleStashDiff:l,stashLoading:c,expandedStashIndex:d,stashDiff:u,loadingStashDiff:m,stashDiffError:h}){return t.jsxs("div",{className:"gm-panel","data-testid":"stashes-panel",children:[t.jsx("div",{className:"gm-panel-header",children:t.jsx("h4",{children:"Stashes"})}),t.jsxs("form",{className:"gm-create-form",onSubmit:a,children:[t.jsx("input",{type:"text",placeholder:"Stash message (optional)",value:n,onChange:f=>s(f.target.value),disabled:c!==null}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:c!==null,children:[c==="create"?t.jsx(jt,{size:14,className:"spin"}):t.jsx(zo,{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(Os,{size:12}),f.branch]}),t.jsx("span",{children:Tr(f.date)})]})]}),t.jsxs("div",{className:"gm-stash-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>l(f.index),disabled:c!==null,children:d===f.index?"Hide":"View"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>r(f.index,!1),disabled:c!==null,title:"Apply stash (keep)",children:c===`apply-${f.index}`?t.jsx(jt,{size:14,className:"spin"}):"Apply"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>r(f.index,!0),disabled:c!==null,title:"Pop stash (apply and drop)",children:"Pop"}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>o(f.index),disabled:c!==null,title:"Drop stash",children:c===`drop-${f.index}`?t.jsx(jt,{size:14,className:"spin"}):t.jsx(Tn,{size:14})})]})]}),d===f.index&&t.jsx("div",{className:"gm-stash-diff",children:m?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:14,className:"spin"}),"Loading stash diff…"]}):h?t.jsx("div",{className:"gm-diff-error",children:h}):u?t.jsxs("div",{className:"gm-diff-viewer",children:[u.stat&&t.jsx("pre",{className:"gm-diff-stat",children:u.stat}),t.jsx("pre",{className:"gm-diff-patch",children:u.patch})]}):null})]},f.index))})]})}function NL({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:a,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:d}){const u=oe=>{try{return new URL(oe).hostname}catch{return oe.replace(/^git@/,"").split(":")[0]||oe}},[m,h]=i.useState([]),[f,p]=i.useState(!1),[g,w]=i.useState(null),[v,b]=i.useState(""),[y,S]=i.useState(""),[j,C]=i.useState(null),[x,N]=i.useState(""),[R,F]=i.useState(""),[E,_]=i.useState(!1),[K,U]=i.useState(!1),A=i.useRef(null),[T,H]=i.useState([]),[Q,se]=i.useState(!1),[O,M]=i.useState(null),[D,$]=i.useState([]),[k,X]=i.useState(!1),[le,ke]=i.useState(null),He=i.useRef(0),ye=m.find(oe=>oe.name===O);i.useEffect(()=>{(n!==null||f)&&U(!1)},[n,f]),i.useEffect(()=>{if(!K)return;const oe=ft=>{A.current?.contains(ft.target)||U(!1)},Ee=ft=>{ft.key==="Escape"&&U(!1)};return document.addEventListener("mousedown",oe),document.addEventListener("keydown",Ee),()=>{document.removeEventListener("mousedown",oe),document.removeEventListener("keydown",Ee)}},[K]);const[je,ne]=i.useState(null),[fe,Z]=i.useState(null),[re,q]=i.useState(!1),[L,xe]=i.useState(null),[he,B]=i.useState(null),[pe,ze]=i.useState(!1);i.useEffect(()=>{ae()},[]),i.useEffect(()=>{e&&e.ahead>0?Ve():e&&e.ahead===0&&H([])},[e?.ahead]),i.useEffect(()=>{m.length>0&&!O&&M(m[0].name)},[m]),i.useEffect(()=>{O?Te(O):($([]),ke(null))},[O]),i.useEffect(()=>{!O||!s||Te(O)},[O,s]),i.useEffect(()=>{O&&!m.find(oe=>oe.name===O)&&M(m.length>0?m[0].name:null)},[m,O]);const ae=async()=>{p(!0);try{const oe=await $N(c);h(oe)}catch(oe){l(Se(oe)||"Failed to load remotes","error")}finally{p(!1)}},Ve=async()=>{se(!0);try{const oe=await VN(c);H(oe)}catch{H([])}finally{se(!1)}},Te=async oe=>{const Ee=He.current+1;He.current=Ee,X(!0),ke(null);try{const ft=await WN(oe,void 0,10,c);if(He.current!==Ee)return;$(ft)}catch(ft){if(He.current!==Ee)return;ke(Se(ft)||"Failed to load remote commits"),$([])}finally{He.current===Ee&&X(!1)}},rt=li(),Be=async oe=>{if(oe.preventDefault(),!(!v.trim()||!y.trim())){w("add");try{await DN(v.trim(),y.trim(),c),l(`Remote '${v}' added successfully`,"success"),b(""),S(""),_(!1),await ae()}catch(Ee){l(Se(Ee)||"Failed to add remote","error")}finally{w(null)}}},ce=async oe=>{if(await rt.confirm({title:"Remove Remote",message:`Are you sure you want to remove remote '${oe}'?`,danger:!0})){w(`remove-${oe}`);try{await LN(oe,c),l(`Remote '${oe}' removed`,"success"),await ae()}catch(ft){l(Se(ft)||"Failed to remove remote","error")}finally{w(null)}}},Re=async oe=>{if(R.trim()){w(`rename-${oe}`);try{await ON(oe,R.trim(),c),l(`Remote renamed to '${R.trim()}'`,"success"),C(null),F(""),await ae()}catch(Ee){l(Se(Ee)||"Failed to rename remote","error")}finally{w(null)}}},Le=async oe=>{if(x.trim()){w(`url-${oe}`);try{await FN(oe,x.trim(),c),l("Remote URL updated","success"),C(null),N(""),await ae()}catch(Ee){l(Se(Ee)||"Failed to update remote URL","error")}finally{w(null)}}},ct=i.useCallback(async(oe,Ee)=>{if(Ee==="ahead"){if(je===oe){ne(null),Z(null);return}ne(oe),Z(null),q(!0);try{const ft=await Jl(oe);Z(ft)}catch{Z(null)}finally{q(!1)}}else{if(L===oe){xe(null),B(null);return}xe(oe),B(null),ze(!0);try{const ft=await Jl(oe);B(ft)}catch{B(null)}finally{ze(!1)}}},[je,L]),Ue=oe=>{C(`url-${oe.name}`),N(oe.pushUrl||oe.fetchUrl)},ue=oe=>{C(`name-${oe.name}`),F(oe.name)};return t.jsx("div",{className:"gm-panel gm-remotes-panel","data-testid":"remotes-panel",children:t.jsxs("div",{className:"gm-remotes-layout",children:[t.jsxs("div",{className:"gm-remote-selector","data-testid":"remote-selector",children:[t.jsxs("div",{className:"gm-remote-selector-header",children:[t.jsx("span",{className:"gm-remote-selector-title",children:"Remotes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>_(!E),disabled:g!==null,title:E?"Cancel":"Add Remote",children:E?t.jsx(mn,{size:14}):t.jsx($n,{size:14})})]}),E&&t.jsxs("form",{className:"gm-remote-form",onSubmit:Be,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:v,onChange:oe=>b(oe.target.value),disabled:g==="add",className:"input gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:y,onChange:oe=>S(oe.target.value),disabled:g==="add",className:"input gm-input gm-input-url"}),t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!v.trim()||!y.trim()||g==="add",children:[g==="add"?t.jsx(jt,{size:12,className:"spin"}):t.jsx($n,{size:12}),"Add"]})]}),f?t.jsxs("div",{className:"gm-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(oe=>t.jsxs("div",{className:`gm-remote-selector-item${O===oe.name?" selected":""}`,onClick:()=>M(oe.name),role:"button",tabIndex:0,onKeyDown:Ee=>{(Ee.key==="Enter"||Ee.key===" ")&&(Ee.preventDefault(),M(oe.name))},children:[t.jsxs("div",{className:"gm-remote-selector-info",children:[t.jsxs("span",{className:"gm-remote-selector-name",children:[t.jsx("span",{className:"gm-remote-selector-name-text",children:oe.name}),oe.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",title:oe.fetchUrl,children:u(oe.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm gm-remote-remove-btn",onClick:Ee=>{Ee.stopPropagation(),ce(oe.name)},disabled:g!==null,title:"Remove remote",children:t.jsx(Tn,{size:14})})]},oe.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[O&&ye?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"gm-remote-sync-card","data-testid":"remote-sync-card",children:[t.jsxs("div",{className:"gm-remote-sync-card-header",children:[t.jsx("span",{className:"gm-remote-sync-card-title",children:O}),e&&(e.ahead>0||e.behind>0)&&t.jsxs("div",{className:"gm-remote-status",children:[e.ahead>0&&t.jsxs("div",{className:"gm-remote-indicator ahead",children:[t.jsx("span",{className:"status-dot status-dot--online","aria-hidden":"true"}),t.jsx(La,{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(Bo,{size:14}),e.behind," to pull"]})]})]}),t.jsxs("div",{className:"gm-remote-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:a,disabled:n!==null||f,children:[n==="fetch"?t.jsx(jt,{size:14,className:"spin"}):t.jsx(ps,{size:14}),"Fetch"]}),t.jsxs("div",{className:"gm-pull-split",ref:A,children:[t.jsxs("button",{className:"btn btn-primary gm-pull-split-main",onClick:()=>{U(!1),r({rebase:!1})},disabled:n!==null||f,children:[n==="pull"?t.jsx(jt,{size:14,className:"spin"}):t.jsx(ii,{size:14}),"Pull"]}),t.jsx("button",{className:"btn btn-primary btn-icon gm-pull-split-toggle",onClick:()=>U(oe=>!oe),disabled:n!==null||f,"aria-label":"Pull options","aria-haspopup":"menu","aria-expanded":K,children:t.jsx(gn,{size:14})}),K?t.jsxs("div",{className:"gm-pull-menu",role:"menu","aria-label":"Pull options menu",children:[t.jsx("button",{className:"gm-pull-menu-item",role:"menuitem",onClick:()=>{U(!1),r({rebase:!1})},children:"Pull"}),t.jsx("button",{className:"gm-pull-menu-item",role:"menuitem",onClick:()=>{U(!1),r({rebase:!0})},children:"Pull --rebase"})]}):null]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||f,children:[n==="push"?t.jsx(jt,{size:14,className:"spin"}):t.jsx(La,{size:14}),"Push"]})]})]}),t.jsxs("div",{className:"gm-remote-detail-card","data-testid":"remote-detail-card",children:[t.jsxs("div",{className:"gm-remote-detail-urls",children:[t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Fetch:"}),j===`url-${O}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:x,onChange:oe=>N(oe.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Le(O),disabled:g===`url-${O}`,children:g===`url-${O}`?t.jsx(jt,{size:12,className:"spin"}):t.jsx(ks,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{C(null),N("")},title:"Cancel",children:t.jsx(mn,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:ye.fetchUrl,children:t.jsx("bdo",{dir:"ltr",children:ye.fetchUrl})}),t.jsxs("div",{className:"gm-remote-inline-actions",children:[t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(ye.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(ba,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>Ue(ye),disabled:g!==null,title:"Edit remote URL",children:t.jsx(Hs,{size:14})})]})]})]}),ye.pushUrl&&ye.pushUrl!==ye.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:ye.pushUrl,children:t.jsx("bdo",{dir:"ltr",children:ye.pushUrl})}),t.jsx("div",{className:"gm-remote-inline-actions",children:t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(ye.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(ba,{size:14})})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:j===`name-${O}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:R,onChange:oe=>F(oe.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Re(O),disabled:g===`rename-${O}`,children:g===`rename-${O}`?t.jsx(jt,{size:12,className:"spin"}):t.jsx(ks,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{C(null),F("")},title:"Cancel",children:t.jsx(mn,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>ue(ye),disabled:g!==null,title:"Edit remote name",children:t.jsx(Hs,{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(La,{size:14}),"Commits to Push (",e.ahead,")"]})}),Q?t.jsxs("div",{className:"gm-loading",children:[t.jsx(jt,{size:14,className:"spin"}),"Loading..."]}):T.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:T.map(oe=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>ct(oe.hash,"ahead"),role:"button",tabIndex:0,onKeyDown:Ee=>{(Ee.key==="Enter"||Ee.key===" ")&&(Ee.preventDefault(),ct(oe.hash,"ahead"))},title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:oe.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:oe.message,children:oe.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:oe.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Tr(oe.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:je===oe.hash?t.jsx(gn,{size:14}):t.jsx(qn,{size:14})})]}),je===oe.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:re?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading diff..."]}):fe?t.jsxs(t.Fragment,{children:[(oe.body||oe.message)&&t.jsx("div",{className:"gm-commit-message-full",children:oe.body||oe.message}),fe.stat&&t.jsx("pre",{className:"gm-diff-stat",children:fe.stat}),t.jsx("pre",{className:"gm-diff-patch",children:fe.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},oe.hash))}):t.jsx("div",{className:"gm-empty",children:"No ahead commits found (may need to fetch first)"})]}),t.jsxs("div",{className:"gm-remote-section","data-testid":"remote-commits-section",children:[t.jsx("div",{className:"gm-section-subheader",children:t.jsxs("h5",{children:[t.jsx(rb,{size:14}),"Recent commits on ",O]})}),k?t.jsxs("div",{className:"gm-loading",children:[t.jsx(jt,{size:14,className:"spin"}),"Loading commits..."]}):le?t.jsxs("div",{className:"gm-error",children:[t.jsx(Vs,{size:14}),le]}):D.length===0?t.jsxs("div",{className:"gm-empty",children:["No commits found on ",O,". Try fetching first."]}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:D.map(oe=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>ct(oe.hash,"remote"),role:"button",tabIndex:0,onKeyDown:Ee=>{(Ee.key==="Enter"||Ee.key===" ")&&(Ee.preventDefault(),ct(oe.hash,"remote"))},title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:oe.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:oe.message,children:oe.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:oe.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Tr(oe.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:L===oe.hash?t.jsx(gn,{size:14}):t.jsx(qn,{size:14})})]}),L===oe.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:pe?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading diff..."]}):he?t.jsxs(t.Fragment,{children:[(oe.body||oe.message)&&t.jsx("div",{className:"gm-commit-message-full",children:oe.body||oe.message}),he.stat&&t.jsx("pre",{className:"gm-diff-stat",children:he.stat}),t.jsx("pre",{className:"gm-diff-patch",children:he.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},oe.hash))})]})]}):t.jsx("div",{className:"gm-empty",children:"Select a remote to view details"}),s&&t.jsx("div",{className:"gm-remote-result",children:s.message})]})]})})}const pr={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function SL(e,n){return e&&n?`${e}/${n}`:""}function CL(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 rg(e){switch(e){case"file-text":return xa;case"check-circle":return Xn;case"shield":return Gk;case"zap":return ls;case"eye":return Fr;case"globe":return gc;case"layout-grid":return va;case"puzzle":return Rk;default:return Xn}}function og(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 EL({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,w]=i.useState("my-steps"),[v,b]=i.useState(null),[y,S]=i.useState(!1),[j,C]=i.useState(!1),[x,N]=i.useState(pr),[R,F]=i.useState(!1),[E,_]=i.useState(!1),[K,U]=i.useState(null),[A,T]=i.useState(null),[H,Q]=i.useState({}),[se,O]=i.useState([]),M=i.useRef(null);zi(M,e,"fusion:workflow-steps-modal-size");const D=i.useCallback(async()=>{try{h(!0);const L=await Ko(a);o(L)}catch(L){s(Se(L)||"Failed to load workflow steps","error")}finally{h(!1)}},[s,a]),$=i.useCallback(async()=>{try{const L=await $o(a);Q(L||{})}catch{}},[a]),k=i.useCallback(async()=>{try{const L=await Ws();O(L.models||[])}catch{}},[]),X=i.useCallback(async()=>{try{p(!0);const[L,xe]=await Promise.all([VS(),WS()]);c(L.templates);const he=Object.fromEntries(xe.templates.map(({pluginId:B,template:pe})=>[pe.id,B]));u(he)}catch(L){s(Se(L)||"Failed to load templates","error")}finally{p(!1)}},[s]);i.useEffect(()=>{e&&(D(),X(),$(),k())},[e,D,X,$,k]);const le=i.useCallback(()=>{C(!0),S(!1),b(null),N(pr)},[]),ke=i.useCallback(()=>{C(!1),S(!0),b(null),N(pr)},[]),He=i.useCallback(L=>{b(L.id),S(!1),N({name:L.name,description:L.description,mode:L.mode||"prompt",phase:L.phase||"pre-merge",prompt:L.prompt,scriptName:L.scriptName||"",enabled:L.enabled,defaultOn:L.defaultOn||!1,modelProvider:L.modelProvider||"",modelId:L.modelId||""})},[]),ye=i.useCallback(()=>{b(null),S(!1),C(!1),N(pr)},[]),je=i.useCallback(async()=>{if(!x.name.trim()||!x.description.trim()){s("Name and description are required","error");return}F(!0);try{const L=x.mode==="prompt"&&x.modelProvider&&x.modelId?{modelProvider:x.modelProvider,modelId:x.modelId}:x.mode==="prompt"?{modelProvider:void 0,modelId:void 0}:{};if(y){const xe={name:x.name.trim(),description:x.description.trim(),mode:x.mode,phase:x.phase,prompt:x.mode==="prompt"&&x.prompt.trim()||void 0,scriptName:x.mode==="script"?x.scriptName.trim():void 0,enabled:x.enabled,defaultOn:x.defaultOn||void 0,...L};await th(xe,a),s("Workflow step created","success")}else v&&(await US(v,{name:x.name.trim(),description:x.description.trim(),mode:x.mode,phase:x.phase,prompt:x.mode==="prompt"?x.prompt:"",scriptName:x.mode==="script"?x.scriptName.trim():void 0,enabled:x.enabled,defaultOn:x.defaultOn,...L},a),s("Workflow step updated","success"));S(!1),b(null),N(pr),await D()}catch(L){s(Se(L)||"Failed to save workflow step","error")}finally{F(!1)}},[x,y,v,s,D]),ne=i.useCallback(async L=>{try{await HS(L,a),s("Workflow step deleted","success"),U(null),v===L&&(b(null),N(pr)),await D()}catch(xe){s(Se(xe)||"Failed to delete workflow step","error")}},[v,s,D]),fe=i.useCallback(async()=>{if(!(!v&&!y)&&x.mode==="prompt"){if(y){if(!x.name.trim()||!x.description.trim()){s("Name and description are required before refining","error");return}F(!0);try{const L=x.modelProvider&&x.modelId?{modelProvider:x.modelProvider,modelId:x.modelId}:{},xe={name:x.name.trim(),description:x.description.trim(),mode:"prompt",prompt:x.prompt.trim()||void 0,enabled:x.enabled,defaultOn:x.defaultOn||void 0,...L},he=await th(xe,a);S(!1),b(he.id),_(!0);const B=await nh(he.id,a);N(pe=>({...pe,prompt:B.prompt})),s("Prompt refined with AI","success"),await D()}catch(L){s(Se(L)||"Failed to refine prompt","error")}finally{F(!1),_(!1)}return}if(v){_(!0);try{const L=await nh(v,a);N(xe=>({...xe,prompt:L.prompt})),s("Prompt refined with AI","success"),await D()}catch(L){s(Se(L)||"Failed to refine prompt","error")}finally{_(!1)}}}},[v,y,x,s,D]),Z=i.useCallback(async L=>{T(L.id);try{await GS(L.id,a),s(`Added ${L.name} workflow step`,"success"),await D(),w("my-steps"),C(!1)}catch(xe){const he=Se(xe);he?.includes("already exists")?s(`A workflow step named '${L.name}' already exists`,"error"):s(he||"Failed to add workflow step from template","error")}finally{T(null)}},[s,D]),re=sa(n);if(!e)return null;const q=y||v!==null;return t.jsx("div",{className:"modal-overlay open",...re,"data-testid":"workflow-step-manager",children:t.jsxs("div",{ref:M,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:[!q&&t.jsxs("div",{className:"wfm-tab-row",children:[t.jsxs("button",{className:`btn ${g==="my-steps"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>w("my-steps"),"data-testid":"tab-my-steps",children:[t.jsx(Dy,{size:14}),"My Workflow Steps (",r.length,")"]}),t.jsxs("button",{className:`btn ${g==="templates"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>w("templates"),"data-testid":"tab-templates",children:[t.jsx(va,{size:14}),"Templates (",l.length,")"]})]}),g==="my-steps"&&!q&&!j&&t.jsxs(t.Fragment,{children:[r.length===0&&t.jsx("div",{className:"wfm-empty","data-testid":"empty-state",children:"No workflow steps defined. Create one to get started, or add one from the Templates tab."}),r.length>0&&t.jsx("div",{className:"wfm-step-list",children:r.map(L=>t.jsx("div",{className:"wfm-step-card","data-testid":`workflow-step-${L.id}`,children:t.jsxs("div",{className:"wfm-step-card-top",children:[t.jsxs("div",{className:"wfm-step-card-info",children:[t.jsxs("div",{className:"wfm-step-card-title-row",children:[t.jsx("span",{className:"wfm-step-card-name",children:L.name}),t.jsx("span",{className:`wfm-badge ${L.enabled?"wfm-badge-enabled":"wfm-badge-disabled"}`,children:L.enabled?"Enabled":"Disabled"}),t.jsx("span",{className:`wfm-badge ${(L.mode||"prompt")==="script"?"wfm-badge-script":"wfm-badge-prompt"}`,children:(L.mode||"prompt")==="script"?"Script":"AI Prompt"}),t.jsx("span",{className:`wfm-badge ${(L.phase||"pre-merge")==="post-merge"?"wfm-badge-post-merge":"wfm-badge-pre-merge"}`,children:(L.phase||"pre-merge")==="post-merge"?"Post-merge":"Pre-merge"}),L.defaultOn&&t.jsx("span",{className:"wfm-badge wfm-badge-default-on",children:"Default on"})]}),t.jsx("div",{className:"wfm-step-card-desc",children:L.description})]}),t.jsxs("div",{className:"wfm-step-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>He(L),title:"Edit","aria-label":`Edit ${L.name}`,children:t.jsx(Hs,{size:14})}),K===L.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>ne(L.id),title:"Confirm delete","aria-label":`Confirm delete ${L.name}`,children:t.jsx(ks,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>U(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(mn,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>U(L.id),title:"Delete","aria-label":`Delete ${L.name}`,children:t.jsx(Tn,{size:14})})]})]})},L.id))})]}),g==="templates"&&!q&&!j&&t.jsx(t.Fragment,{children:f?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(jt,{size:24,className:"spin wfm-spinner"}),"Loading templates..."]}):l.length===0?t.jsx("div",{className:"wfm-empty","data-testid":"no-templates-state",children:"No templates available."}):t.jsx("div",{className:"wfm-template-list",children:l.map(L=>{const xe=rg(L.icon),he=og(L.category),B=A===L.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`template-${L.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(xe,{size:20})}),t.jsxs("div",{className:"wfm-template-content",children:[t.jsxs("div",{className:"wfm-template-title-row",children:[t.jsx("span",{className:"wfm-template-name",children:L.name}),t.jsx("span",{className:he,children:L.category}),d[L.id]&&t.jsx("span",{className:"wfm-badge-category wfm-badge-category-plugin",children:d[L.id]})]}),t.jsx("div",{className:"wfm-template-desc",children:L.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>Z(L),disabled:B,"data-testid":`add-template-${L.id}`,children:B?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx($n,{size:12}),"Add"]})})]})]})},L.id)})})}),j&&!q&&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:ke,"data-testid":"create-custom-step",children:[t.jsx($n,{size:14}),"Custom workflow step"]}),f?t.jsxs("div",{className:"wfm-loading","data-testid":"create-chooser-template-loading",children:[t.jsx(jt,{size:24,className:"spin wfm-spinner"}),"Loading built-in templates..."]}):l.length===0?t.jsx("div",{className:"wfm-empty","data-testid":"create-chooser-no-templates",children:"No built-in templates are available right now. You can still create a custom step."}):t.jsx("div",{className:"wfm-template-list","data-testid":"create-chooser-templates",children:l.map(L=>{const xe=rg(L.icon),he=og(L.category),B=A===L.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`chooser-template-${L.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(xe,{size:20})}),t.jsxs("div",{className:"wfm-template-content",children:[t.jsxs("div",{className:"wfm-template-title-row",children:[t.jsx("span",{className:"wfm-template-name",children:L.name}),t.jsx("span",{className:he,children:L.category}),d[L.id]&&t.jsx("span",{className:"wfm-badge-category wfm-badge-category-plugin",children:d[L.id]})]}),t.jsx("div",{className:"wfm-template-desc",children:L.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>Z(L),disabled:B,"data-testid":`chooser-add-template-${L.id}`,children:B?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx($n,{size:12}),"Add template"]})})]})]})},L.id)})})]}),q&&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:x.name,onChange:L=>N(xe=>({...xe,name:L.target.value})),placeholder:"e.g. Documentation Review","data-testid":"workflow-step-name"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{value:x.description,onChange:L=>N(xe=>({...xe,description:L.target.value})),placeholder:"Brief description of what this step does",rows:2,"data-testid":"workflow-step-description"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Mode"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-mode-selector",children:[t.jsxs("button",{className:`btn ${x.mode==="prompt"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>N(L=>({...L,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(Zi,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${x.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>N(L=>({...L,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(ea,{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 ${x.phase==="pre-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>N(L=>({...L,phase:"pre-merge"})),"data-testid":"phase-pre-merge",children:"Pre-merge"}),t.jsx("button",{className:`btn ${x.phase==="post-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>N(L=>({...L,phase:"post-merge"})),"data-testid":"phase-post-merge",children:"Post-merge"})]}),t.jsx("div",{className:"wfm-field-hint",children:x.phase==="pre-merge"?"Runs before merge — can block merge on failure":"Runs after merge success — failures are logged but do not block"})]}),x.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:fe,disabled:!x.description.trim()||E,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[E?t.jsx(jt,{size:12,className:"spin"}):t.jsx(ms,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:x.prompt,onChange:L=>N(xe=>({...xe,prompt:L.target.value})),placeholder:"Leave empty to use AI refinement",rows:6,className:"wfm-prompt-textarea","data-testid":"workflow-step-prompt"})]}),x.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"}),x.modelProvider&&x.modelId&&t.jsxs("button",{type:"button",className:"btn-icon wfm-model-clear-btn",onClick:()=>N(L=>({...L,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(mn,{size:12}),t.jsx("span",{children:"Use default"})]})]}),t.jsx("span",{className:"wfm-model-hint",children:x.modelProvider&&x.modelId?`Using ${x.modelProvider}/${x.modelId}`:"Using global default model"}),t.jsx("div",{"data-testid":"workflow-step-model-select",children:t.jsx(_s,{models:se,value:SL(x.modelProvider,x.modelId),onChange:L=>{const xe=CL(L);N(he=>({...he,modelProvider:xe.provider,modelId:xe.modelId}))},placeholder:"Select a model override…",label:"Model override for this workflow step"})})]}),x.mode==="script"&&t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Script"}),Object.keys(H).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:x.scriptName,onChange:L=>N(xe=>({...xe,scriptName:L.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(H).map(([L,xe])=>t.jsxs("option",{value:L,children:[L," (",xe,")"]},L))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:x.enabled,onChange:L=>N(xe=>({...xe,enabled:L.target.checked})),"data-testid":"workflow-step-enabled"}),"Enabled (available for selection on new tasks)"]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:x.defaultOn,onChange:L=>N(xe=>({...xe,defaultOn:L.target.checked})),"data-testid":"workflow-step-default-on"}),"Default on for new tasks"]}),t.jsxs("div",{className:"wfm-form-actions",children:[t.jsx("button",{className:"btn btn-secondary",onClick:ye,disabled:R,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:je,disabled:R||!x.name.trim()||!x.description.trim()||x.mode==="script"&&!x.scriptName.trim(),"data-testid":"save-workflow-step",children:R?"Saving...":y?"Create":"Save"})]})]})]})]})}),!q&&!j&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:le,"data-testid":"add-workflow-step",children:[t.jsx($n,{size:14}),"Add Workflow Step"]})})]})})}const _L=36e5,ML=3e5,Gd=[{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 AL(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 RL(e){return typeof e!="number"||!Number.isFinite(e)?_L:Math.max(ML,Math.round(e))}function $8(e){if(Gd.some(s=>s.value===e))return[...Gd];const n={value:e,label:`${AL(e)} (custom)`};return[...Gd,n].sort((s,a)=>s.value-a.value)}const IL=4,TL=5*6e4;function PL(e){const n=RL(e?.heartbeatIntervalMs);return Math.max(n*IL,TL)}function lg(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 $L(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 DL(e){const s=e.metadata?.heartbeatTimerRepair;if(!s||typeof s!="object")return{};const a=s;return{repairedAt:typeof a.repairedAt=="string"?a.repairedAt:void 0,staleAtRepair:typeof a.staleAtRepair=="boolean"?a.staleAtRepair:void 0,staleRepairReason:typeof a.staleRepairReason=="string"?a.staleRepairReason:void 0}}function LL(e){const{state:n,lastHeartbeatAt:s,lastError:a,pauseReason:r,runtimeConfig:o}=e,l=$L(e),c=l||o?.enabled!==!1;if(n==="error")return{label:a??"Error",icon:t.jsx(Js,{size:14}),color:"var(--state-error-text)",stateDerived:!a};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(Ci,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(Js,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!c)return{label:"Heartbeat Disabled",icon:t.jsx(Ci,{size:14}),color:"var(--state-paused-text)",stateDerived:!1};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(Qn,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const d=DL(e);if(d.staleAtRepair&&d.repairedAt){const f=Date.parse(d.repairedAt),p=Date.parse(s);if(Number.isFinite(f)&&Number.isFinite(p)&&p<f)return{label:"Unresponsive",icon:t.jsx(Js,{size:14}),color:"var(--state-error-text)",stateDerived:!1,reason:d.staleRepairReason??"Heartbeat scheduler repaired a missing timer; waiting for recovery heartbeat"}}const u=new Date(s).getTime(),m=Date.now()-u,h=PL(o);if(m>h){const f=`No heartbeat for ${lg(m)} (threshold: ${lg(h)})`;return{label:"Unresponsive",icon:t.jsx(Js,{size:14}),color:"var(--state-error-text)",stateDerived:!1,reason:f}}return{label:"Healthy",icon:t.jsx(qw,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}function cc({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(Qn,{size:Math.max(14,Math.round(n*.55)),"aria-hidden":"true"})})}const OL="https://github.com/Runfusion/Fusion/issues/new";function FL(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`${OL}?${r.toString()}`}function zL({open:e,onClose:n,errorText:s,issueContext:a}){const[r,o]=i.useState(!1),l=i.useMemo(()=>FL(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(Vs,{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(ks,{size:14}):t.jsx(ba,{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(eb,{size:14}),"Report on GitHub"]})]})]})}):null}function BL({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(Vs,{size:14}),t.jsx("span",{className:"agent-error-indicator__label",children:s})]}),t.jsx(zL,{open:a,onClose:()=>r(!1),errorText:e,issueContext:n})]})}const $l=[{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 UL({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,w]=i.useState("all"),[v,b]=i.useState(()=>{if(typeof window>"u")return"list";const $=Gn("fn-agent-view",a);return $==="board"||$==="list"?$:"list"});i.useEffect(()=>{const $=Gn("fn-agent-view",a);if($==="board"||$==="list"){b($);return}b("list")},[a]),i.useEffect(()=>{fs("fn-agent-view",v,a)},[a,v]);const[y,S]=i.useState(null),j=i.useRef(null),[C,x]=i.useState(new Set),[N,R]=i.useState(new Map),{confirm:F}=li(),E=i.useMemo(()=>N.size===0?r:r.map($=>{const k=N.get($.id);return k?{...$,state:k}:$}),[r,N]),_=i.useMemo(()=>g!=="all"?E:[...E].sort(($,k)=>{const X=$.state==="paused"?1:0,le=k.state==="paused"?1:0;return X!==le?X-le:(k.updatedAt??"").localeCompare($.updatedAt??"")}),[E,g]),K=i.useCallback(async()=>{c(!0);try{const k=await Ur(g!=="all"?{state:g}:void 0,a);o(k)}catch($){s(`Failed to load agents: ${Se($)}`,"error")}finally{c(!1)}},[g,s,a]);i.useEffect(()=>{e&&K()},[e,K]),i.useEffect(()=>{if(!e)return;const $=setInterval(()=>{K()},3e4);return()=>{clearInterval($)}},[e,K]);const U=async()=>{if(m.trim())try{await n1({name:m.trim(),role:f},a),s(`Agent "${m}" created`,"success"),h(""),u(!1),K()}catch($){s(`Failed to create agent: ${Se($)}`,"error")}},A=async($,k)=>{if(!C.has($)){x(X=>new Set(X).add($)),R(X=>{const le=new Map(X);return le.set($,k),le});try{await i1($,k,a),s(`Agent state updated to ${k}`,"success"),await K(),R(X=>{const le=new Map(X);return le.delete($),le})}catch(X){R(le=>{const ke=new Map(le);return ke.delete($),ke}),s(`Failed to update state: ${Se(X)}`,"error")}finally{x(X=>{const le=new Set(X);return le.delete($),le})}}},T=async($,k)=>{if(await F({title:"Delete Agent",message:`Delete agent "${k}"? This cannot be undone.`,danger:!0}))try{await a1($,a),s(`Agent "${k}" deleted`,"success"),K()}catch(le){s(`Failed to delete agent: ${Se(le)}`,"error")}},H=async($,k)=>{const X=r.find(le=>le.id===$);if(X){if(X.role===k){S(null);return}try{await s1($,{role:k},a),s(`Agent role updated to ${$l.find(le=>le.value===k)?.label??k}`,"success"),S(null),K()}catch(le){s(`Failed to update role: ${Se(le)}`,"error")}}},Q=($,k)=>{$.key==="Escape"&&S(null)},se=$=>$l.find(k=>k.value===$)?.label??$,O=$=>LL($),M=$=>$.color==="var(--state-active-text)"?"active":$.color==="var(--state-paused-text)"?"paused":$.color==="var(--state-error-text)"?"error":"muted",D=($,k)=>$.state==="error"?{title:void 0,label:"Error"}:{title:k.reason??k.label,label:k.stateDerived?null:k.label};return e?t.jsx("div",{className:"modal-overlay open",onClick:$=>$.target===$.currentTarget&&n(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal--wide agent-list-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{className:"modal-title",children:[t.jsx(Qn,{size:20}),"Agents"]}),t.jsxs("div",{className:"modal-actions",children:[t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${v==="board"?" active":""}`,onClick:()=>b("board"),title:"Board view","aria-label":"Board view","aria-pressed":v==="board",children:t.jsx(va,{size:16})}),t.jsx("button",{className:`view-toggle-btn${v==="list"?" active":""}`,onClick:()=>b("list"),title:"List view","aria-label":"List view","aria-pressed":v==="list",children:t.jsx(au,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void K(),title:"Refresh",disabled:l,children:t.jsx(ps,{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(ql,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:g,onChange:$=>w($.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($n,{size:16}),d?"Cancel":"New Agent"]})]}),d&&t.jsxs("div",{className:"agent-create-form",children:[t.jsx("input",{type:"text",placeholder:"Agent name...",value:m,onChange:$=>h($.target.value),onKeyDown:$=>$.key==="Enter"&&U(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:f,onChange:$=>p($.target.value),children:$l.map($=>t.jsxs("option",{value:$.value,children:[$.icon," ",$.label]},$.value))}),t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:()=>void U(),children:"Create"})]}),t.jsx("div",{className:v==="board"?"agent-board":"agent-list",children:_.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(Qn,{size:48,opacity:.3}),t.jsx("p",{children:"No agents found"}),t.jsx("p",{className:"text-secondary",children:"Create an agent to get started"})]}):v==="board"?_.map($=>{const k=O($),X=D($,k),le=M(k);return t.jsxs("div",{className:"agent-board-card","data-state":$.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:t.jsx(cc,{agent:$,size:20})}),t.jsx("span",{className:"agent-board-badge","data-state":$.state,children:$.state}),t.jsx("span",{className:"agent-board-health","data-health":le,title:X.title,children:k.icon})]}),t.jsx("div",{className:"agent-board-name",title:$.name,children:$.name}),t.jsx("div",{className:"agent-board-id",children:$.id}),t.jsxs("div",{className:"agent-board-actions",children:[$.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A($.id,"active"),disabled:C.has($.id),title:"Activate",children:t.jsx(os,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void T($.id,$.name),title:"Delete",children:t.jsx(Tn,{size:14})})]}),$.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Pause",children:t.jsx(Ci,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Stop",children:t.jsx($i,{size:14})})]}),$.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A($.id,"active"),disabled:C.has($.id),title:"Resume",children:t.jsx(os,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void T($.id,$.name),title:"Delete",children:t.jsx(Tn,{size:14})})]}),$.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Pause",children:t.jsx(Ci,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Stop",children:t.jsx($i,{size:14})})]}),$.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A($.id,"active"),disabled:C.has($.id),title:"Retry",children:t.jsx(os,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Stop",children:t.jsx($i,{size:14})})]})]})]},$.id)}):_.map($=>{const k=O($),X=D($,k),le=M(k);return t.jsxs("div",{className:"agent-card","data-state":$.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[y===$.id?t.jsx("select",{ref:j,className:"select agent-role-select",value:$.role,onChange:ke=>void H($.id,ke.target.value),onKeyDown:ke=>Q(ke,$.id),onBlur:()=>S(null),autoFocus:!0,children:$l.map(ke=>t.jsxs("option",{value:ke.value,children:[ke.icon," ",ke.label]},ke.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>S($.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:ke=>{(ke.key==="Enter"||ke.key===" ")&&S($.id)},children:t.jsx(cc,{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":le,title:X.title,children:[k.icon,X.label?` ${X.label}`:""]}),t.jsx("span",{className:"badge text-secondary",children:se($.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[$.state==="error"&&$.lastError?t.jsx(BL,{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 A($.id,"active"),disabled:C.has($.id),title:"Activate",children:[t.jsx(os,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void T($.id,$.name),title:"Delete",children:[t.jsx(Tn,{size:14})," Delete"]})]}),$.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Pause",children:[t.jsx(Ci,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Stop",children:[t.jsx($i,{size:14})," Stop"]})]}),$.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A($.id,"active"),disabled:C.has($.id),title:"Resume",children:[t.jsx(os,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void T($.id,$.name),title:"Delete",children:[t.jsx(Tn,{size:14})," Delete"]})]}),$.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Pause",children:[t.jsx(Ci,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Stop",children:[t.jsx($i,{size:14})," Stop"]})]}),$.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A($.id,"active"),disabled:C.has($.id),title:"Retry",children:[t.jsx(os,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Stop",children:[t.jsx($i,{size:14})," Stop"]})]})]})]},$.id)})})]})]})}):null}function HL({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 uN();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 bN(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,w=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"claude"})," CLI. Uses your existing Claude subscription / quota instead of an API key."]}),v=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),g?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void f(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void f(!0),disabled:o!==null||!p,title:p?void 0:"`claude` binary not detected on PATH — install Claude CLI first.",children:o==="enabling"?"Enabling…":"Enable"})]});return s?t.jsxs("div",{className:`auth-provider-card auth-provider-card--cli${e?" auth-provider-card--authenticated":""}`,"data-testid":"claude-cli-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(zn,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(qL,{status:a,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:v})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:"Details"}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[w,t.jsx(cg,{status:a,authenticated:e}),c&&t.jsx(dg,{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(zn,{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"}),w,t.jsx(cg,{status:a,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(dg,{action:c})]})}function qL({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 cg({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(jt,{size:10,className:"animate-spin"})," Probing local CLI…"]});const{binary:s,enabled:a,extension:r,ready:o}=e;return s.available?a?r&&r.status!=="ok"?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--warning",children:["⚠ Extension load failed: ",r.reason??r.status]}):o||n?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--connected",children:["✓ Connected",s.version?` — ${s.version}`:""]}):t.jsx("small",{className:"settings-muted",children:"Enabled. Validating…"}):t.jsxs("small",{className:"settings-muted",children:[t.jsx("code",{children:"claude"})," ",s.version?`(${s.version})`:""," detected",s.binaryPath?` at ${s.binaryPath}`:"",". Click Enable to route AI calls through it."]}):t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--error",children:["✗ ",s.reason??"`claude` not found on PATH"]})}function dg({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 VL({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 fN();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 w=await vN(g);s?.(w.enabled),await d()}finally{c.current&&l(null)}},[s,d]),m=a?.enabled??e,h=a?.binary.available??!1,f=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{l("testing"),d().finally(()=>{c.current&&l(null)})},disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:12,className:"animate-spin"})," Testing…"]}):"Test"}),m?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void u(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void u(!0),disabled:o!==null||!h,children:o==="enabling"?"Enabling…":"Enable"})]}),p=a?a.binary.available?m?`Connected${a.binary.version?` — ${a.binary.version}`:""}`:"Detected. Click Enable to route calls through Cursor CLI.":a.binary.reason??"`cursor-agent` not found on PATH":"Probing local CLI…";return n?t.jsxs("div",{className:`cursor-cli-provider-card auth-provider-card auth-provider-card--cli${e?" auth-provider-card--authenticated":""}`,"data-testid":"cursor-cli-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(zn,{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(zn,{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 WL({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 w=await gN();return c.current&&r(w),w},[]);i.useEffect(()=>{d()},[d]);const u=i.useCallback(async w=>{l(w?"enabling":"disabling");try{const v=await yN(w);n?.(v.enabled),await d()}finally{c.current&&l(null)}},[n,d]),m=i.useCallback(async()=>{l("testing");try{await d()}finally{c.current&&l(null)}},[d]),h=a?.enabled??e,f=a?.server.available??!1,p=a?a.server.available?`Server reachable at ${a.server.url}`:`Server unavailable: ${a.server.reason??"not reachable"}`:"Probing llama.cpp server…",g=t.jsxs("div",{className:"auth-provider-cli-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void m(),disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),h?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void u(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void u(!0),disabled:o!==null||!f,children:o==="enabling"?"Enabling…":"Enable"})]});return s?t.jsxs("div",{className:`auth-provider-card auth-provider-card--cli llama-cpp-provider-card llama-cpp-provider-card--compact${h?" auth-provider-card--authenticated":""}`,"data-testid":"llama-cpp-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(zn,{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(zn,{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 GL(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 Kd({instructions:e,"data-testid":n}){const[s,a]=i.useState(!1),r=GL(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(ks,{size:12}):t.jsx(ba,{size:12})})]})]},u))}):e})}function KL({value:e,onChange:n,onSubmit:s,prompt:a,placeholder:r,helpText:o,disabled:l=!1,submitLabel:c="Submit code","data-testid":d}){const u=i.useRef(null),m=i.useRef(null),[h,f]=i.useState(!1),p=i.useCallback(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return!1;const v=window.matchMedia("(max-width: 768px)").matches,b=window.matchMedia("(pointer: coarse)").matches;return v||b},[]),g=i.useCallback(()=>typeof window>"u"||typeof window.matchMedia!="function"||window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth",[]),w=i.useCallback(()=>{if(!p())return;const v=m.current??u.current;if(!v||typeof v.scrollIntoView!="function")return;const b=g();requestAnimationFrame(()=>{v.scrollIntoView({block:"center",behavior:b,inline:"nearest"}),window.setTimeout(()=>{v.scrollIntoView({block:"center",behavior:b,inline:"nearest"})},120)})},[g,p]);return i.useEffect(()=>{if(!h||!p())return;w();const v=window.visualViewport;if(!v)return;const b=()=>{document.activeElement===m.current&&w()};return v.addEventListener("resize",b),v.addEventListener("scroll",b),()=>{v.removeEventListener("resize",b),v.removeEventListener("scroll",b)}},[h,w,p]),t.jsxs("div",{ref:u,className:"oauth-manual-code","data-testid":d,children:[t.jsx("p",{className:"oauth-manual-code__prompt",children:a}),t.jsx("textarea",{ref:m,className:"form-input oauth-manual-code__input",value:e,onChange:v=>n(v.target.value),onFocus:()=>{f(!0),w()},onBlur:()=>f(!1),placeholder:r,rows:3,spellCheck:!1,disabled:l}),t.jsx("div",{className:"oauth-manual-code__actions",children:t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,disabled:l,children:c})}),o&&t.jsx("p",{className:"oauth-manual-code__help",children:o})]})}const JL=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"]),YL=/^[a-z][a-z0-9-]*$/,ug=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function mg(){return{id:"",name:"",reasoning:!1}}function QL({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,w]=i.useState(e?.apiKey??""),[v,b]=i.useState(e?.models?.length?e.models:[mg()]),[y,S]=i.useState(null),j=v.length>1,C=i.useMemo(()=>y??r??null,[y,r]);function x(E,_){b(K=>K.map((U,A)=>A===E?{...U,..._}:U))}function N(E){b(_=>_.length<=1?_:_.filter((K,U)=>U!==E))}function R(){if(!l.trim())return"Provider ID is required.";if(!YL.test(l.trim()))return"Provider ID must be kebab-case.";if(!o&&JL.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 ug.includes(f)?v.length===0?"At least one model is required.":v.some(E=>!E.id?.trim())?"Each model must have a model ID.":null:"API type is required."}async function F(E){E.preventDefault();const _=R();S(_),!_&&await n({id:l.trim(),name:d.trim()||void 0,baseUrl:m.trim(),api:f,apiKey:g.trim()||void 0,models:v.map(K=>({id:K.id.trim(),name:K.name?.trim()||void 0,reasoning:!!K.reasoning,contextWindow:K.contextWindow,maxTokens:K.maxTokens}))})}return t.jsxs("form",{onSubmit:F,className:"custom-provider-form","aria-label":"custom-provider-form",children:[t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-id",children:"Provider ID"}),t.jsx("input",{id:"custom-provider-id",className:"input",value:l,onChange: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:ug.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=>w(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:v.map((E,_)=>t.jsxs("div",{className:"custom-provider-form__model-row",children:[t.jsx("input",{className:"input","aria-label":`Model ID ${_+1}`,placeholder:"Model ID",value:E.id,onChange:K=>x(_,{id:K.target.value}),disabled:a}),t.jsx("input",{className:"input","aria-label":`Model name ${_+1}`,placeholder:"Display name",value:E.name??"",onChange:K=>x(_,{name:K.target.value}),disabled:a}),t.jsxs("label",{className:"checkbox-label custom-provider-form__toggle",children:[t.jsx("input",{type:"checkbox",checked:!!E.reasoning,onChange:K=>x(_,{reasoning:K.target.checked}),disabled:a}),"Reasoning"]}),t.jsx("input",{className:"input","aria-label":`Context window ${_+1}`,placeholder:"Context window",type:"number",value:E.contextWindow??"",onChange:K=>x(_,{contextWindow:K.target.value?Number(K.target.value):void 0}),disabled:a}),t.jsx("input",{className:"input","aria-label":`Max tokens ${_+1}`,placeholder:"Max tokens",type:"number",value:E.maxTokens??"",onChange:K=>x(_,{maxTokens:K.target.value?Number(K.target.value):void 0}),disabled:a}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>N(_),disabled:a||!j,"aria-label":`Remove model ${_+1}`,children:"×"})]},`${_}-model`))}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>b(E=>[...E,mg()]),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 XL=new Set(["google-antigravity","antigravity","google-gemini-cli"]);function ZL(e){return!XL.has(e)}function hg(e){return e.filter(n=>ZL(n.id))}const Fv={host:"web",activeProfileId:null,profiles:[]},zv=i.createContext({shellApi:null,state:Fv,ready:!0,openConnectionManagerSignal:0});function eO({children:e}){const n=i.useMemo(()=>typeof window<"u"?window.fusionShell??null:null,[]),[s,a]=i.useState(Fv),[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(zv.Provider,{value:{shellApi:n,state:s,ready:r,openConnectionManagerSignal:l},children:e})}function tO(){return i.useContext(zv)}const nO={host:"web",activeProfileId:null,profiles:[]};function sO(e){if(!e)return nO;const n=Array.isArray(e.profiles)?e.profiles.filter(a=>!!(a&&a.id&&a.serverUrl)):[],s=e.activeProfileId&&n.some(a=>a.id===e.activeProfileId)?e.activeProfileId:null;return{...e,activeProfileId:s,profiles:n}}function Cm(e){return new Error(`${e} is only available in native shell mode`)}async function iO(e,n){if(!e)throw Cm("Saving connection profiles");return e.saveProfile(n)}async function aO(e,n){if(!e)throw Cm("Deleting connection profiles");await e.deleteProfile(n)}async function rO(e,n){if(!e)throw Cm("Switching connection profiles");return e.setActiveProfile(n)}function Bv(){const e=tO(),n=i.useMemo(()=>sO(e.state),[e.state]),s=i.useCallback(o=>iO(e.shellApi,o),[e.shellApi]),a=i.useCallback(o=>aO(e.shellApi,o),[e.shellApi]),r=i.useCallback(o=>rO(e.shellApi,o),[e.shellApi]);return{...e,state:n,saveProfile:s,removeProfile:a,setActiveProfile:r}}const Wa="fusion_model_onboarding_state",Pr=[],$r=[],dc=!1,uc=!1,Dr={},oO=void 0,ua=["ai-setup","github","project-setup","first-task"],lO={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function ri(){if(typeof window>"u")return null;try{const e=localStorage.getItem(Wa);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?cO(n):null}catch{return null}}function cO(e){const n=e.postOnboardingDismissedAt??oO;return{...e,completedSteps:e.completedSteps??Pr,skippedSteps:e.skippedSteps??$r,dismissed:e.dismissed??dc,completed:e.completed??uc,stepData:e.stepData??Dr,...n?{postOnboardingDismissedAt:n}:{}}}function Dl(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:Pr,skippedSteps:$r,dismissed:dc,completed:uc,stepData:Dr};try{localStorage.setItem(Wa,JSON.stringify(s))}catch{}return}try{const s=ri(),a=new Date().toISOString(),r=n.completed??uc;let o=n.dismissed??dc;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??Pr,c=n.skippedSteps??s?.skippedSteps??$r,d={...s?.stepData??Dr};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(Wa,JSON.stringify(u))}catch{}}}function dO(e){if(!(typeof window>"u"))try{const n=ri(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:Pr,skippedSteps:[e],dismissed:dc,completed:uc,stepData:Dr};localStorage.setItem(Wa,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(Wa,JSON.stringify(r))}catch{}}function pg(){if(!(typeof window>"u"))try{const e=ri(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:Pr,skippedSteps:$r,dismissed:!1,completed:!0,stepData:Dr};localStorage.setItem(Wa,JSON.stringify(s))}catch{}}function Lr(){const e=ri();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function uO(){if(!(typeof window>"u"))try{const e=ri(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:Pr,skippedSteps:$r,dismissed:!1,completed:!1,stepData:Dr,postOnboardingDismissedAt:n};localStorage.setItem(Wa,JSON.stringify(s))}catch{}}function Uv(){const e=ri();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function mO(){const e=ri();return!e||Lr()?!1:e.currentStep!=="complete"}function hO(){const e=ri();if(!e||Lr()||e.currentStep==="complete")return null;const n=e.currentStep,s=lO[n]??gO(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function pO(){const e=ri();return e?e.skippedSteps:$r}function fO(e){const n=ri();return!n||!n.stepData?null:n.stepData[e]??null}function gO(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const Hv="fusion_onboarding_events",fg="fusion_onboarding_session_id",bO=200,xO=50;function pi(e,n={}){if(!(typeof window>"u"))try{const s=yO(),a=jO(n.step),r={type:e,timestamp:new Date().toISOString(),...a?{step:a}:{},metadata:n,sessionId:vO()},o=kO([...s,r]);wO(o)}catch{}}function vO(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(fg);if(e)return e;const n=gg();return sessionStorage.setItem(fg,n),n}catch{return gg()}}function gg(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function yO(){try{const e=localStorage.getItem(Hv);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(NO):[]}catch{return[]}}function wO(e){try{localStorage.setItem(Hv,JSON.stringify(e))}catch{}}function kO(e){const n=[...e];for(;n.length>bO;)n.splice(0,xO);return n}function jO(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function NO(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 SO=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}))??[]}),CO={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"}}},qv={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:"..."}},EO={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},bg={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"},_O=e=>`After you sign in with ${e}, the browser will try to redirect to a localhost address that this dashboard can't reach. The redirect tab will look like it failed. Before that happens, copy the full URL from the browser address bar — you'll paste it back here to finish login. Continue?`;function Tu(e){if(bg[e])return bg[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 Jd=["anthropic","openai","google","gemini","ollama"],MO=["anthropic","claude-cli","droid-cli","cursor-cli","llama-cpp","openai-codex","gemini","minimax","kimi","zai"],AO={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"},RO={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function Pu(e){return AO[e]??e}function xg(e){const n=Pu(e),s=MO.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function vg(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=xg(e.id),a=xg(n.id);if(s!==a)return s-a;const r=Pu(e.id),o=Pu(n.id);if(r!==o)return r.localeCompare(o);const l=RO[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 IO(e,n){const s=n.trim();if(!s)return"API key is required";const a=qv[e]??EO;return a.pattern.test(s)?null:`${Tu(e)} keys should follow this format: ${a.hint} (e.g. ${a.example})`}const Vv={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"},TO={description:"AI provider — connect to start using AI models",apiKeyInfo:Vv};function $u(e){return CO[e]??TO}function PO(e){return $u(e.id).apiKeyInfo??Vv}function $O({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 DO({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=qv[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(fi,{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:w=>c(e.id,w.target.value),onKeyDown:w=>{w.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(fi,{summary:"Advanced setup details",children:g})]})}const LO=150;function OO({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:a,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const{confirm:d}=li(),u=ri(),m=u?.currentStep,h=m==="complete"?"ai-setup":ua.includes(m)?m:"ai-setup",f=u?.completedSteps??[],p=u?.skippedSteps??pO(),[g,w]=i.useState(!0),[v,b]=i.useState(h),[y,S]=i.useState(f),[j,C]=i.useState(p),[x,N]=i.useState(!1),[R,F]=i.useState(""),[E,_]=i.useState(!1),[K,U]=i.useState(null),[A,T]=i.useState(null),[H,Q]=i.useState([]),[se,O]=i.useState(void 0),[M,D]=i.useState(!0),[$,k]=i.useState(null),[X,le]=i.useState({}),[ke,He]=i.useState({}),[ye,je]=i.useState({}),[ne,fe]=i.useState(null),[Z,re]=i.useState([]),[q,L]=i.useState(""),[xe,he]=i.useState(!1),[B,pe]=i.useState({}),[ze,ae]=i.useState({}),[Ve,Te]=i.useState({}),[rt,Be]=i.useState([]),[ce,Re]=i.useState(!1),[Le,ct]=i.useState(!1),[Ue,ue]=i.useState(),[oe,Ee]=i.useState("Remote Server"),[ft,ht]=i.useState(""),[tt,xt]=i.useState(""),[Me,Ye]=i.useState(!1),[dt,wt]=i.useState(null),St=i.useRef({}),Fe=i.useRef(null),J=i.useRef(null),me=i.useRef(null),[Ze,be]=i.useState({}),[gt,$t]=i.useState(()=>ri()?.stepData?.github?.skipped===!0),Ie=i.useRef(0),ge=i.useRef(l),{shellApi:st,state:yt}=Bv(),pt=i.useRef(!1),vt=u?.currentStep,Ut=!!u&&u.currentStep!=="complete";zi(J,g,"fusion:model-onboarding-modal-size"),i.useEffect(()=>{const P=Fe.current;P&&(P.scrollTop=0)},[v]);const[Dt,nn]=i.useState(()=>ri()?.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"}],sn=on.findIndex(P=>P.key===v),ln=v==="complete"?on.length:sn;i.useEffect(()=>{v!=="complete"&&Dl(v,{completedSteps:y,skippedSteps:j})},[v,y,j]),i.useEffect(()=>{pt.current||(pt.current=!0,pi("onboarding:wizard-opened",{source:Ut?"resume":"initial",resumedFromStep:vt}))},[Ut,vt]),i.useEffect(()=>{const P=ge.current!=null,Ce=l!=null;!P&&Ce&&N(!0),Ce||N(!1),ge.current=l},[l]);const xn=i.useRef(h);i.useEffect(()=>{if(xn.current==="ai-setup"&&v!=="ai-setup"&&!H.some(Ce=>Ce.id!=="github"&&Ce.authenticated)){const Ce={};for(const qe of H)qe.id!=="github"&&!qe.authenticated&&!Dt[qe.id]&&(Ce[qe.id]=!0);if(Object.keys(Ce).length>0){const qe={...Dt,...Ce};nn(qe),Dl(v,{stepData:{"ai-setup":{skippedProviders:qe}}})}}xn.current=v},[v,H,Dt]);const qt=i.useCallback(async()=>{try{const{providers:P,ghCli:Ce}=await Po(),qe=hg(P);Q(qe),O(Ce),le(et=>{const mt={};for(const[Nt,Pt]of Object.entries(et)){const an=qe.find(Cn=>Cn.id===Nt);an&&!an.authenticated&&an.loginInProgress&&(mt[Nt]=Pt)}return Object.keys(mt).length===Object.keys(et).length?et:mt}),be(et=>{let mt=!1;const Nt={...et};for(const[Pt,an]of Object.entries(et)){if(an!=="pending")continue;qe.find(ie=>ie.id===Pt)?.loginInProgress||(delete Nt[Pt],mt=!0)}return mt?Nt:et}),nn(et=>{const mt={...et};for(const Nt of qe)Nt.authenticated&&mt[Nt.id]&&delete mt[Nt.id];return Object.keys(mt).length===Object.keys(et).length?et:mt})}catch{}},[]),Qt=i.useCallback(async()=>{try{const P=await wN();Be((P.providers??[]).map(SO))}catch{}},[]),hn=i.useCallback(async P=>{ct(!0),ue(void 0);try{await jN(P),await Qt(),await Ws().then(Ce=>re(Ce.models??[])),Re(!1)}catch(Ce){ue(Se(Ce)||"Failed to create custom provider")}finally{ct(!1)}},[Qt]),Zt=i.useRef(!1);i.useEffect(()=>{v==="ai-setup"&&Qt(),Zt.current&&qt(),Zt.current=v!=="ai-setup"},[v,qt,Qt]),i.useEffect(()=>{if(!H.some(qe=>qe.loginInProgress))return;const Ce=setInterval(()=>{qt()},2e3);return()=>clearInterval(Ce)},[H,qt]);const ve=H.find(P=>P.id==="github"),Pe=!!ve,Ke=ve?.authenticated??!1,at=ve?.loginInProgress??!1,We=se?.authenticated??!1,It=Ke||We,Lt=!Ke&&We,Bt=i.useCallback(P=>{if(P.authenticated)return"connected";const Ce=Ze?.[P.id];return Ce==="timeout"||Ce==="failed"?"retry":Dt[P.id]?"skipped":"not-connected"},[Ze,Dt]);function Gt({status:P}){const Ce={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:qe,className:et}=Ce[P];return t.jsx("span",{"data-testid":"provider-status-badge",className:et,"data-status":P,children:qe})}const bt=i.useCallback(()=>{if(It)return"connected";const P=Ze.github;return P==="pending"?"pending":P==="failed"||P==="timeout"?"failed":gt?"skipped":"not-connected"},[It,Ze,gt]);function Ot({status:P}){const Ce={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:qe,className:et}=Ce[P];return t.jsx("span",{"data-testid":"github-status-badge",className:et,"data-status":P,children:qe})}const en=i.useCallback(async()=>{try{const P=await Ws();re(P.models)}catch{}},[]),Kt=i.useCallback(async()=>{try{const P=await na();if(P.defaultProvider&&P.defaultModelId){const Ce=`${P.defaultProvider}/${P.defaultModelId}`;L(Ce)}}catch{}},[]);i.useEffect(()=>{Promise.all([qt(),en(),Kt()]).finally(()=>D(!1))},[qt,en,Kt]),i.useEffect(()=>{const P=fO("ai-setup");if(P?.loginOutcomes){const Ce=P.loginOutcomes,qe={};for(const[et,mt]of Object.entries(Ce))mt!=="pending"&&(qe[et]=mt);Object.keys(qe).length>0&&be(qe)}},[]);const Sn=i.useCallback((P,Ce)=>{Dl(v,{completedSteps:y,stepData:{"ai-setup":{loginOutcomes:{[P]:Ce}}}})},[v,y]);i.useEffect(()=>{const P=Object.entries(Ze).filter(([Ce,qe])=>qe!=="pending");for(const[Ce,qe]of P)Sn(Ce,qe)},[Ze,Sn]),i.useEffect(()=>()=>{me.current&&clearInterval(me.current),Object.values(St.current).forEach(clearTimeout),St.current={}},[]);const dn=i.useCallback(P=>{$t(P),Dl(v,{completedSteps:y,stepData:{github:{skipped:P}}})},[v,y]),Jt=i.useCallback(P=>P==="complete"?-1:ua.indexOf(P),[]),tn=i.useCallback(()=>{S(Ce=>[...new Set([...Ce,v])]),C(Ce=>Ce.filter(qe=>qe!==v)),pi("onboarding:step-completed",{step:v}),v==="github"&&!Ke&&dn(!1);const P=Jt(v);P>=0&&P<ua.length-1&&b(ua[P+1])},[v,Ke,dn,Jt]),Ne=i.useCallback(()=>{C(Ce=>[...new Set([...Ce,v])]),dO(v),pi("onboarding:step-skipped",{step:v}),v==="github"&&!Ke&&dn(!0);const P=Jt(v);P>=0&&P<ua.length-1&&b(ua[P+1])},[v,Ke,dn,Jt]),W=i.useCallback(()=>{const P=v;S(qe=>qe.filter(et=>et!==P)),C(qe=>qe.filter(et=>et!==P)),P==="github"&&!Ke&&dn(!1);const Ce=Jt(v);Ce>0&&b(ua[Ce-1])},[v,Ke,dn,Jt]),Y=i.useCallback(()=>{Ne()},[Ne]),_e=i.useCallback(async P=>{const Ce=H.find(et=>et.id===P);if(Ce?.requiresManualCode===!0&&!await d({title:"Heads up — manual paste-back required",message:_O(Ce.name),confirmLabel:"Continue to login",cancelLabel:"Cancel"}))return;be(et=>{const mt=et[P];if(mt&&mt!=="pending"){const{[P]:Nt,...Pt}=et;return Pt}return et});const qe=()=>{le(et=>{if(!(P in et))return et;const mt={...et};return delete mt[P],mt}),He(et=>{if(!(P in et))return et;const mt={...et};return delete mt[P],mt}),je(et=>{if(!(P in et))return et;const mt={...et};return delete mt[P],mt})};qe(),be(et=>({...et,[P]:"pending"})),k(P),Ie.current=0;try{const{url:et,instructions:mt,manualCode:Nt}=await NN(P);mt?.trim()&&le(Pt=>({...Pt,[P]:mt})),Nt&&He(Pt=>({...Pt,[P]:Nt})),window.open(Fi(et),"_blank"),me.current=setInterval(async()=>{if(Ie.current++,Ie.current>=LO){me.current&&(clearInterval(me.current),me.current=null),k(null),Q(Pt=>Pt.map(an=>an.id===P?{...an,loginInProgress:!1}:an)),be(Pt=>({...Pt,[P]:"timeout"})),qe(),n("Login timed out. Please try again.","warning");return}try{const{providers:Pt,ghCli:an}=await Po(),Cn=hg(Pt);Q(Cn),O(an);const ie=Cn.find($e=>$e.id===P);if(ie?.authenticated){me.current&&(clearInterval(me.current),me.current=null),k(null),be($e=>({...$e,[P]:"success"})),qe(),P==="github"&&dn(!1),n("Login successful","success");return}ie?.loginInProgress||(me.current&&(clearInterval(me.current),me.current=null),k(null),be($e=>({...$e,[P]:"failed"})),qe(),n("Login did not complete. Please try again.","error"))}catch{}},2e3)}catch(et){et instanceof Error&&et.message.includes("already in progress")||et&&typeof et=="object"&&"status"in et&&et.status===409?(n("Login already in progress. Cancel it to retry.","warning"),be(Nt=>({...Nt,[P]:"pending"})),qt()):(n(et instanceof Error?et.message:"Login failed","error"),be(Nt=>({...Nt,[P]:"failed"}))),k(null),qe()}},[n,H,d,qt,dn]),ut=i.useCallback(async P=>{const Ce=ye[P]?.trim();if(!Ce){n("Paste the full redirect URL or authorization code first.","warning");return}fe(P);try{(await SN(P,Ce)).submitted?(je(et=>{if(!(P in et))return et;const mt={...et};return delete mt[P],mt}),n("Authorization code received. Finishing login…","success")):n("That authorization code was already submitted. Waiting for login…","warning")}catch(qe){n(Se(qe)||"Failed to submit authorization code","error")}finally{fe(null)}},[n,ye]),At=i.useCallback(async P=>{me.current&&(clearInterval(me.current),me.current=null),k(P),Ie.current=0,Q(Ce=>Ce.map(qe=>qe.id===P?{...qe,loginInProgress:!1}:qe)),be(Ce=>({...Ce,[P]:"cancelled"}));try{await EN(P),await qt().catch(()=>{}),n("Login cancelled","success")}catch(Ce){n(Se(Ce)||"Failed to cancel login","error")}finally{k(null),le(Ce=>{if(!(P in Ce))return Ce;const qe={...Ce};return delete qe[P],qe}),He(Ce=>{if(!(P in Ce))return Ce;const qe={...Ce};return delete qe[P],qe}),je(Ce=>{if(!(P in Ce))return Ce;const qe={...Ce};return delete qe[P],qe}),fe(Ce=>Ce===P?null:Ce)}},[n,qt]),zt=i.useCallback((P,Ce)=>{pe(et=>({...et,[P]:Ce}));const qe=St.current[P];qe&&(clearTimeout(qe),delete St.current[P]),ae(et=>{if(!et[P])return et;const mt={...et};return delete mt[P],mt}),Te(et=>{if(!et[P])return et;const mt={...et};return delete mt[P],mt})},[]),yn=i.useCallback(()=>{const P=Fe.current;if(!P)return;const Ce=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof P.scrollTo=="function"){P.scrollTo({top:0,behavior:Ce?"auto":"smooth"});return}}catch{}P.scrollTop=0},[]),Zn=i.useCallback(async(P,Ce)=>{const qe=(Ce??B[P]??"").trim(),et=IO(P,qe);if(et){ae(Nt=>({...Nt,[P]:et}));return}const mt=St.current[P];mt&&(clearTimeout(mt),delete St.current[P]),k(P),ae(Nt=>{const Pt={...Nt};return delete Pt[P],Pt}),Te(Nt=>{if(!Nt[P])return Nt;const Pt={...Nt};return delete Pt[P],Pt});try{await _N(P,qe),await qt(),yn(),pe(Nt=>{const Pt={...Nt};return delete Pt[P],Pt}),ae(Nt=>{if(!Nt[P])return Nt;const Pt={...Nt};return delete Pt[P],Pt}),Te(Nt=>({...Nt,[P]:"✓ Key saved"})),St.current[P]=setTimeout(()=>{Te(Nt=>{if(!Nt[P])return Nt;const Pt={...Nt};return delete Pt[P],Pt}),delete St.current[P]},3e3),n("API key saved","success")}catch(Nt){const Pt=Nt instanceof TypeError&&Nt.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":Nt instanceof Error?Nt.message:"Failed to save API key";ae(an=>({...an,[P]:Pt})),Te(an=>{if(!an[P])return an;const Cn={...an};return delete Cn[P],Cn}),n(Pt,"error")}finally{k(null)}},[B,n,qt,yn]),vn=i.useCallback(async P=>{k(P);try{await MN(P),await qt(),n("API key removed","success")}catch(Ce){n(Ce instanceof Error?Ce.message:"Failed to clear API key","error")}finally{k(null)}},[n,qt]),Dn=i.useCallback(async P=>{k(P);try{await CN(P),await qt(),n("Logged out","success")}catch(Ce){n(Ce instanceof Error?Ce.message:"Logout failed","error")}finally{k(null)}},[n,qt]),de=i.useCallback(P=>{L(P)},[]),nt=i.useCallback(async()=>{try{const P={modelOnboardingComplete:!0};if(q){const Ce=q.indexOf("/"),qe=Ce!==-1?q.slice(0,Ce):void 0,et=Ce!==-1?q.slice(Ce+1):q,mt=Z.find(Nt=>Nt.id===et);mt?(P.defaultProvider=mt.provider,P.defaultModelId=mt.id):qe&&et&&(P.defaultProvider=qe,P.defaultModelId=et)}await Bn(P),pg()}catch{}},[q,Z,Bn,pg]),ot=i.useCallback(async()=>{const P=[...new Set([...y,"first-task"])];he(!0);try{await nt(),pi("onboarding:completed",{completedSteps:P,skippedSteps:j}),S(P),C(Ce=>Ce.filter(qe=>qe!=="first-task")),b("complete")}finally{he(!1)}},[nt,y,j]),_t=i.useCallback(async()=>{if(!s)return;const P=R.trim();if(!P){U("Please enter a task description.");return}U(null),_(!0);let Ce=!1;try{const qe=await db({description:P,source:{sourceType:"dashboard_ui"}},s);T(qe),N(!0),pi("onboarding:first-task-created",{taskId:qe?.id}),n("Task created","success"),Ce=!0}catch(qe){const et=qe instanceof Error?qe.message:"Something went wrong creating your task. Please try again.";U(et),n(et,"error")}finally{_(!1)}Ce&&nt()},[s,R,n,nt]),G=i.useCallback(async()=>{he(!0);try{await nt()}finally{he(!1)}pi("onboarding:open-new-task",{}),r?.()},[nt,r]),Oe=i.useCallback(async()=>{if(It){he(!0);try{await nt()}finally{he(!1)}w(!1),e(),pi("onboarding:open-github-import",{}),o?.()}},[nt,It,e,o]),Mt=i.useCallback(async()=>{pi("onboarding:dismissed",{currentStep:v,completedSteps:y,skippedSteps:j}),he(!0);try{await Bn({modelOnboardingComplete:!0})}catch{}w(!1),e()},[v,y,j,e]),Xt=i.useCallback(()=>{pi("onboarding:finished",{}),w(!1),e()},[e]),_n=i.useCallback(()=>{const P=l??A;P&&(nt(),c?.(P),e())},[l,A,nt,c,e]),Pn=i.useCallback(()=>{nt(),e()},[nt,e]),kn=bt(),Vn=H.filter(P=>P.id!=="github"),$s=yt.host!=="web"&&!yt.activeProfileId,vs=[...Vn].sort(vg),As=vs.some(P=>!P.type||P.type==="oauth"),bn=vs.some(P=>P.type==="api_key"),Ht=Vn.filter(P=>P.authenticated),On=Ht.length>0,Fn=!!s,as=v==="github"&&!On,Wn=i.useCallback(async()=>{if(st){wt(null),Ye(!0);try{const P=await st.saveProfile({name:oe,serverUrl:ft,authToken:tt.trim()?tt:null});try{await st.setActiveProfile(P.id)}catch(Ce){wt(Se(Ce)||"Saved profile but failed to activate it");return}ht(""),xt(""),n("Remote server profile saved","success")}catch(P){wt(Se(P)||"Failed to save shell connection")}finally{Ye(!1)}}},[st,oe,ft,tt,n]);if(!g)return null;const Rs=(()=>{if(!q)return"";const P=q.indexOf("/"),Ce=P===-1?void 0:q.slice(0,P),qe=P===-1?q:q.slice(P+1),et=Z.find(mt=>mt.id===qe&&(!Ce||mt.provider===Ce));return et?.name?et.name:Ce?`${Tu(Ce)} ${qe}`:q})(),In=[];if(Fn?In.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):In.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),On){const P=Tu(Ht[0]?.id??"");In.push({label:"AI Provider",status:"connected",detail:`${P} connected — AI agents can work on tasks`})}else Vn.length>0&&Vn.some(P=>Dt[P.id])?In.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):In.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});It?In.push({label:"GitHub",status:"connected",detail:Lt?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!Pe||gt?In.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):In.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),Rs&&In.push({label:"Default Model",status:"connected",detail:Rs});const rs=l??A,Ns=rs?.description?.split(`
|
|
692
|
+
`)[0]?.trim()||rs?.title||"",ys=new Set(Jd),cs=vs.filter(P=>ys.has(P.id)).sort((P,Ce)=>{const qe=Jd.indexOf(P.id),et=Jd.indexOf(Ce.id);return qe!==et?qe-et:vg(P,Ce)}),ss=vs.filter(P=>P.authenticated&&!ys.has(P.id)),te=vs.filter(P=>!P.authenticated&&!ys.has(P.id)),we=P=>{const Ce=Ze[P.id]==="timeout"||Ze[P.id]==="failed"||Ze[P.id]==="cancelled",qe=P.loginInProgress&&!Ce;if(P.id==="llama-cpp"&&P.type==="cli")return t.jsx(WL,{authenticated:P.authenticated,onToggled:()=>{qt()}},P.id);if(P.id==="claude-cli"&&P.type==="cli")return t.jsx(HL,{authenticated:P.authenticated,onToggled:()=>{qt()}},P.id);if(P.id==="cursor-cli"&&P.type==="cli")return t.jsx(VL,{authenticated:P.authenticated,onToggled:()=>{qt()}},P.id);if(P.type==="api_key"){const et=$u(P.id),mt=PO(P);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${P.id}`,className:`onboarding-provider-card${P.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${P.id}`,"aria-hidden":"true",children:t.jsx(zn,{provider:P.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(ib,{size:14,className:"onboarding-provider-key-icon"}),P.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:et.description}),t.jsx(Gt,{status:Bt(P)}),P.authenticated&&P.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",P.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(DO,{provider:P,apiKeyInfo:mt,inputValue:B[P.id]??"",isSaving:$===P.id,error:ze[P.id],success:Ve[P.id],isConnected:P.authenticated,onInputChange:zt,onSave:Zn,onClear:vn})})]},P.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${P.id}`,className:`onboarding-provider-card${P.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${P.id}`,"aria-hidden":"true",children:t.jsx(zn,{provider:P.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:P.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:$u(P.id).description}),t.jsx(Gt,{status:Bt(P)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:$===P.id?P.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 At(P.id),children:"Cancel"})]}):qe?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 At(P.id),children:"Cancel"})]}):P.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>Dn(P.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>_e(P.id),children:"Login"})}),($===P.id||qe)&&X[P.id]&&t.jsx(Kd,{instructions:X[P.id],"data-testid":`onboarding-login-instructions-${P.id}`}),($===P.id||qe)&&ke[P.id]&&t.jsx(KL,{value:ye[P.id]??"",onChange:et=>je(mt=>({...mt,[P.id]:et})),onSubmit:()=>void ut(P.id),prompt:ke[P.id].prompt,placeholder:ke[P.id].placeholder,helpText:ke[P.id].helpText,disabled:ne===P.id,submitLabel:ne===P.id?"Submitting…":"Submit code","data-testid":`onboarding-manual-code-${P.id}`}),Ze[P.id]==="timeout"&&$!==P.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),Ze[P.id]==="failed"&&$!==P.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},P.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:J,children:[t.jsxs("div",{className:"model-onboarding-header",children:[t.jsxs("h2",{id:"onboarding-title",className:"model-onboarding-title",children:[v==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(ls,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),v==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(ii,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),v==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Dm,{size:24})," Set Up Your Project"]}),v==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(Dm,{size:24})," Create Your First Task"]}),v==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(Xn,{size:24})," All Set!"]})]}),v!=="complete"&&t.jsx("button",{className:"modal-close",onClick:Mt,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(mn,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:on.map((P,Ce)=>{const qe=ln>Ce,et=y.includes(P.key)&&qe,mt=j.includes(P.key)&&!y.includes(P.key)&&qe,Nt=et||mt;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[Ce>0&&t.jsx("div",{className:`model-onboarding-step-connector ${Ce<=ln?"done":""}`}),Nt?t.jsxs("button",{className:`model-onboarding-step-indicator ${v===P.key?"active":""} ${et?"done":""} ${mt?"skipped":""}`,onClick:()=>b(P.key),"aria-label":`Go back to ${P.label}`,title:`Review ${P.label}`,children:[t.jsx("span",{className:"step-number",children:et?t.jsx(Xn,{size:14}):mt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Ce+1}),t.jsx("span",{className:"step-label",children:P.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${v===P.key?"active":""} ${et?"done":""} ${mt?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:et?t.jsx(Xn,{size:14}):mt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Ce+1}),t.jsx("span",{className:"step-label",children:P.label})]})]},P.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:Fe,children:[v==="ai-setup"&&t.jsxs("div",{className:"model-onboarding-ai-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Fusion uses AI models to plan, write, and review code for you. Connect an AI provider below to get started — you can use a hosted service or enter an API key."}),t.jsx("p",{className:"onboarding-helper-text model-onboarding-primary-helper",children:"You only need one provider to get started."}),t.jsx("p",{className:"onboarding-helper-text",children:"Research runs require provider credentials and an enabled Research View. After onboarding, verify these in Settings → Authentication and Settings → Experimental Features."}),$s&&t.jsxs("div",{className:"card",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Connect remote Fusion server"}),t.jsx("p",{className:"onboarding-helper-text",children:"Your native shell needs an active remote profile before dashboard handoff can complete."}),t.jsx("label",{htmlFor:"onboarding-shell-profile-name",className:"onboarding-apikey-field-label",children:"Profile name"}),t.jsx("input",{id:"onboarding-shell-profile-name",className:"input",value:oe,onChange:P=>Ee(P.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:ft,onChange:P=>ht(P.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:tt,onChange:P=>xt(P.target.value)}),dt&&t.jsx("small",{className:"field-error",children:dt}),t.jsxs("div",{className:"onboarding-apikey-input-row",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void st?.openConnectionManager(),children:"Open manager"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void Wn(),disabled:!ft.trim()||Me,children:Me?"Saving…":"Save remote server"})]})]}),!M&&H.length>0&&(()=>{const P=H.filter(Nt=>Nt.id!=="github"&&Nt.authenticated).length,Ce=H.filter(Nt=>Nt.id!=="github").length,qe=Object.keys(Dt).filter(Nt=>!H.find(Pt=>Pt.id===Nt)?.authenticated).length;if(Ce===0)return null;let et="onboarding-provider-summary",mt="";return P>0?(et+=" onboarding-provider-summary--connected",mt=`✓ ${P} of ${Ce} provider${Ce!==1?"s":""} connected`):qe>0?(et+=" onboarding-provider-summary--skipped",mt=`${qe} provider${qe!==1?"s":""} skipped`):(et+=" onboarding-provider-summary--none",mt="No providers connected yet"),t.jsx("div",{className:et,"data-testid":"provider-summary",children:mt})})(),t.jsx(pa,{slotId:"onboarding-recommendation-card",projectId:s}),t.jsx(fi,{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."})}),H.length>0&&!H.some(P=>P.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),M?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(jt,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):H.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(pa,{slotId:"onboarding-provider-card",projectId:s,renderPlaceholder:!1,actions:{refreshAuthProviders:()=>{qt()}}}),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"}),cs.length>0?t.jsx("div",{className:"model-onboarding-providers",children:cs.map(P=>we(P))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),ss.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:ss.map(P=>we(P))})]}),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(fi,{summary:"How do I choose a model?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Models vary in speed, capability, and cost. A good default is usually the latest model from your connected provider. You can always change this later in Settings."})}),Z.length===0?t.jsx("div",{className:"model-onboarding-empty",children:"No models available yet. Connect a provider above to see model options."}):t.jsx("div",{className:"onboarding-model-selector",children:t.jsx(_s,{models:Z,value:q,onChange:de,placeholder:"Select a default model…",label:"Default model"})}),q&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",Z.find(P=>P.id===q)?.name??q]})})]}),t.jsx(fi,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsxs("div",{"data-testid":"onboarding-advanced-provider-settings",children:[te.length>0?t.jsx("div",{className:"model-onboarding-providers",children:te.map(P=>we(P))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."}),rt.length>0?t.jsx("div",{className:"onboarding-custom-provider-list",children:rt.map(P=>t.jsxs("div",{className:"onboarding-custom-provider-item",children:[t.jsx(zn,{provider:P.id,size:"sm"}),t.jsx("span",{children:P.name||P.id})]},P.id))}):null,ce?t.jsx(QL,{onSave:hn,onCancel:()=>{Re(!1),ue(void 0)},saving:Le,error:Ue}):t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>Re(!0),children:"Add custom provider"})]})}),As&&t.jsx(fi,{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."})}),bn&&t.jsx(fi,{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(pa,{slotId:"onboarding-setup-help",projectId:s})]})]}),v==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[It?t.jsx("p",{className:"model-onboarding-description",children:Lt?"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"})]})}),as&&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(fi,{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."})}),Pe?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(ii,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(Ot,{status:kn})})]}),Ke&&($==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>Dn("github"),children:"Disconnect"}))]}),(kn==="not-connected"||kn==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[$==="github"||at?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 At("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>_e("github"),children:[t.jsx(ii,{size:16}),"Connect"]}),($==="github"||at)&&X.github&&t.jsx(Kd,{instructions:X.github,"data-testid":"onboarding-login-instructions-github"})]}),kn==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:Lt?"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."}),kn==="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:()=>_e("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Y,children:"Skip for now"})]})]}),kn==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),kn==="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:()=>_e("github"),children:"Connect anyway"})})]}),kn==="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(zn,{provider:"github",size:"lg"})}),Lt?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:()=>b("project-setup"),children:Lt?"Continue with gh CLI auth →":"Continue without GitHub →"}),Lt&&($==="github"||at?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(jt,{size:14,className:"onboarding-spinner"}),"Waiting for OAuth login…"]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>_e("github"),children:[t.jsx(zn,{provider:"github",size:"sm"}),"Connect OAuth (optional)"]}))]}),Lt&&($==="github"||at)&&X.github&&t.jsx(Kd,{instructions:X.github,"data-testid":"onboarding-login-instructions-github"})]})]}),v==="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."}),Fn?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(fi,{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."})})]}),v==="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."}),x&&rs?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(Xn,{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:rs.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:_n,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:Pn,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[Fn?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:R,onChange:P=>{F(P.target.value),U(null)},placeholder:"Example: Build a login page with email and password",rows:4}),t.jsx("div",{className:"onboarding-first-task-form__actions",children:t.jsx("button",{type:"button",className:"btn btn-primary",onClick:_t,disabled:E,"data-testid":"onboarding-first-task-submit",children:E?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),K&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:K}),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($O,{items:In}),Fn&&t.jsxs(t.Fragment,{children:[t.jsx(fi,{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:G,disabled:xe,children:[t.jsx("div",{className:"cta-icon",children:t.jsx($n,{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:Oe,disabled:xe||!It,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(ii,{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."]})]})]})]}),v==="complete"&&t.jsxs("div",{className:"model-onboarding-complete",children:[t.jsx(Xn,{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:[v==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Mt,disabled:xe,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Ne,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:tn,children:"Next →"})]}),v==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:W,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Ne,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:tn,children:"Next →"})]}),v==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:W,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:tn,disabled:!Fn,children:"Next →"})]}),v==="first-task"&&!x&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:W,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:ot,disabled:xe,children:xe?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),v==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:Xt,children:[t.jsx(Xn,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function Wv({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 FO=i.lazy(()=>En(()=>import("./SetupWizardModal-Agi3XNtZ.js"),__vite__mapDeps([13,1,14,15,16,17,5,6,18])).then(e=>({default:e.SetupWizardModal}))),zO=i.lazy(()=>En(()=>import("./SettingsModal-Cu93Jjho.js"),__vite__mapDeps([19,1,20,21,22,2,5,6,23])).then(e=>({default:e.SettingsModal})));function BO(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{En(()=>import("./SettingsModal-Cu93Jjho.js"),__vite__mapDeps([19,1,20,21,22,2,5,6,23]))},{timeout:1500})}function UO({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[w,v]=i.useState(null),b=c.detailTask?(()=>{const N=n.find(R=>R.id===c.detailTask?.id);return N?"prompt"in c.detailTask?{...c.detailTask,...N,prompt:c.detailTask.prompt,log:c.detailTask.log}:N:c.detailTask})():null,y=p??c.closeSettings,S=i.useCallback(()=>{c.openNewTask()},[c]),j=i.useCallback(()=>{c.openGitHubImport()},[c]),C=i.useCallback(N=>{v(null),c.closeModelOnboarding(),c.openDetailTask(N)},[c]),x=i.useCallback(async N=>{const R=await u.handleModalCreate(N);return c.modelOnboardingOpen&&v(R),R},[u.handleModalCreate,c.modelOnboardingOpen]);return i.useEffect(()=>{!c.modelOnboardingOpen&&w&&v(null)},[c.modelOnboardingOpen,w]),i.useEffect(()=>{BO()},[]),t.jsxs(t.Fragment,{children:[b&&t.jsx(Ia,{children:t.jsx(ZP,{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(Ia,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(zO,{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(p4,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:u.handleGitHubImport,tasks:n,projectId:e}),t.jsx(Ia,{children:t.jsx(y4,{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(Ia,{children:t.jsx(A4,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:u.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(X4,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(eD,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(jD,{initialWorkspace:c.fileBrowserWorkspace,initialFile:c.fileBrowserInitialFile,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),c.todosOpen&&t.jsx(SD,{isOpen:!0,onClose:c.closeTodos,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan}),t.jsx(PD,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e,anchorRect:c.usageAnchorRect}),t.jsx(dL,{isOpen:c.systemStatsOpen,onClose:c.closeSystemStats,projectId:e}),c.schedulesOpen&&t.jsx(eL,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(Ia,{children:t.jsx(iL,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:x,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(fL,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:a,onOpenTaskDetail:N=>{const R=n.find(F=>F.id===N);R&&c.openDetailTask(R)}}),t.jsx(Ia,{children:t.jsx(bL,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(Ia,{children:t.jsx(EL,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(UL,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(i.Suspense,{fallback:null,children:t.jsx(FO,{onProjectRegistered:d.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(OO,{onComplete:d.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:d.handleAddProject,onOpenNewTask:S,onOpenGitHubImport:j,firstCreatedTask:w,onViewTask:C}),t.jsx(Wv,{toasts:o,onRemove:l})]})}function HO({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 Du=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function qO(e,n){if(n==="ready")return"done";const s=Du.findIndex(r=>r.id===n),a=Du.findIndex(r=>r.id===e);return a<s?"done":a===s?"active":"pending"}function VO({stage:e}){const[n]=i.useState(()=>hj());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:Du.map(s=>{const a=qO(s.id,e);return t.jsxs("li",{className:`dashboard-loader__step dashboard-loader__step--${a}`,"data-testid":`dashboard-loader-step-${s.id}`,children:[t.jsx("span",{className:"dashboard-loader__step-icon","aria-hidden":"true",children:a==="done"?"✓":a==="active"?t.jsx(jt,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:s.label})]},s.id)})})]})})}const WO=5e3;function GO(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function KO(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++,ec(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 JO(e,n,s,a){const[r,o]=i.useState({globalPause:!1,enginePaused:!1,maxConcurrent:2}),[l,c]=i.useState(!0),[d,u]=i.useState(null),m=i.useRef(null),h=i.useRef(null),f=i.useCallback(async()=>{h.current&&h.current.abort(),h.current=new AbortController;try{c(!0),u(null);const v=await y1(n);o(v)}catch(v){if(v instanceof Error&&v.name==="AbortError")return;u(v instanceof Error?v.message:"Failed to fetch executor stats")}finally{c(!1)}},[n]);i.useEffect(()=>(f(),()=>{h.current&&h.current.abort()}),[f]),i.useEffect(()=>(m.current&&clearInterval(m.current),m.current=setInterval(()=>{f()},WO),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[f]);const p=KO(e,s,a),g=GO(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:g,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:d,refresh:f}}const YO={planning:Oi,subtask:Fa,mission_interview:Es,milestone_interview:Es,slice_interview:Es},QO={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function XO({sessions:e,generating:n,needsInput:s,onOpenSession:a,onDismissSession:r}){const{confirm:o}=li(),[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}=Wr(),g=i.useMemo(()=>Ja(),[]);if(i.useEffect(()=>{if(!l)return;const b=y=>{m.current&&!m.current.contains(y.target)&&c(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[l]),i.useEffect(()=>{const b=new Set,y=new Map;for(const S of e){const j=p.get(S.id),C=[S.status,S.updatedAt,j?.tabId??S.lockedByTab??"",j?.stale?"stale":"fresh"].join("|"),x=h.current.get(S.id);x&&x!==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 w=e.length,v=s>0;return t.jsxs("div",{ref:m,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${v?" background-tasks-indicator__pill--attention":""}`,onClick:()=>c(b=>!b),title:`${w} background AI task${w!==1?"s":""}${s>0?` (${s} need${s!==1?"":"s"} input)`:""}`,children:[n>0&&t.jsx(jt,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(tu,{size:12}),t.jsxs("span",{children:["AI ",w]})]}),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=YO[b.type],S=b.status==="generating",j=b.status==="awaiting_input",C=b.status==="error",x=p.get(b.id),N=x?.tabId??b.lockedByTab??null,R=!!(N&&N!==g&&!x?.stale),F=d.has(b.id);return t.jsxs("div",{className:`background-tasks-indicator__item${F?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:F?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:F?"translateY(-1px)":void 0},onClick:async()=>{R&&!await o({title:"Open Active Session",message:"This session is active in another tab. Open anyway?"})||(a(b),c(!1))},children:[C?t.jsx(Vs,{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":QO[b.type],S&&" — generating...",j&&!R&&" — needs input",j&&R&&" — active in another tab"]})]}),S&&t.jsx(jt,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),j&&!R&&t.jsx(tu,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),j&&R&&t.jsx(yc,{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(mn,{size:12})})]},b.id)})})]})]})}function ZO(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 eF(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:os};case"paused":return{label:"Paused",color:"var(--triage)",icon:Ci};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:ls}}}function tF({tasks:e,projectId:n,taskStuckTimeoutMs:s,staleHighFanoutBlockerAgeThresholdMs:a,backgroundSessions:r,backgroundGenerating:o,backgroundNeedsInput:l,onOpenBackgroundSession:c,onDismissBackgroundSession:d,lastFetchTimeMs:u,currentProjectPath:m,onOpenProjectDirectory:h,keyboardOpen:f}){if(f)return null;const{stats:p,loading:g,error:w}=JO(e,n,s,u),[v,b]=i.useState(!1),y=i.useMemo(()=>eF(p.executorState),[p.executorState]),S=i.useMemo(()=>ZO(p.lastActivityAt),[p.lastActivityAt]),j=i.useMemo(()=>{const x=tm(e,{staleHighFanoutAgeThresholdMs:a??Lb});return Array.from(x.values()).map(R=>R.escalation).filter(R=>!!R).sort((R,F)=>F.activeTodoCount!==R.activeTodoCount?F.activeTodoCount-R.activeTodoCount:F.totalActiveCount!==R.totalActiveCount?F.totalActiveCount-R.totalActiveCount:F.blockingAgeMs!==R.blockingAgeMs?F.blockingAgeMs-R.blockingAgeMs:R.blockerId.localeCompare(F.blockerId,"en",{numeric:!0,sensitivity:"base"}))[0]??null},[e,a]),C=y.icon;return w?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(zr,{size:14}),w]})}):g&&p.runningTaskCount===0?t.jsx("div",{className:"executor-status-bar executor-status-bar--loading",role:"status","aria-label":"Executor status",children:t.jsx("span",{className:"executor-status-bar__loading-text",children:"Loading..."})}):t.jsxs("div",{className:`executor-status-bar ${p.executorState==="running"?"executor-status-bar--running":""}`,role:"status","aria-label":"Executor status",children:[r&&r.length>0&&c&&d&&t.jsxs(t.Fragment,{children:[t.jsx(XO,{sessions:r,generating:o??0,needsInput:l??0,onOpenSession:c,onDismissSession:d}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--queued","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Queued"}),t.jsx("span",{className:"executor-status-bar__count",children:p.queuedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--running ${p.runningTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Running"}),t.jsx("span",{className:"executor-status-bar__count",children:p.runningTaskCount}),t.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),t.jsx("span",{className:"executor-status-bar__max",children:p.maxConcurrent})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),p.stuckTaskCount>0&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--stuck",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--stuck executor-status-bar__indicator--active","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Stuck"}),t.jsx("span",{className:"executor-status-bar__count executor-status-bar__count--error",children:p.stuckTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--blocked ${p.blockedTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Blocked"}),t.jsx("span",{className:`executor-status-bar__count ${p.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:p.blockedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--review","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"In Review"}),t.jsx("span",{className:"executor-status-bar__count",children:p.inReviewCount})]}),j&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--fanout",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--fanout executor-status-bar__indicator--active","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Escalated"}),t.jsxs("span",{className:"executor-status-bar__fanout-summary",title:`Escalated blocker ${j.blockerId}: ${j.activeTodoCount} todo waiting (threshold ${Xu}), ${j.totalActiveCount} active total`,children:[j.blockerId," · ",j.activeTodoCount," todo"]})]})]}),m&&h&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--project-directory",children:[t.jsx("button",{className:`executor-status-bar__folder-toggle${v?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>b(x=>!x),"aria-label":v?"Hide project directory":"Show project directory","aria-expanded":v,"data-testid":"executor-project-path-toggle",title:v?"Hide project directory":"Show project directory",children:t.jsx(js,{size:12,"aria-hidden":"true"})}),v&&t.jsx("button",{className:"executor-status-bar__project-path",onClick:h,title:m,"data-testid":"executor-project-path-link",children:m})]})]}),t.jsx("div",{className:"executor-status-bar__spacer"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[t.jsx(ta,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:S})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx(C,{size:12,style:{color:y.color},"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__state",style:{color:y.color},children:y.label})]})]})}const nF={planning:Oi,subtask:Fa,mission_interview:Es,milestone_interview:Es,slice_interview:Es},sF={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},Gv="fusion:session-banner-dismissed";function So(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function iF(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(Gv);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:So(r);s.set(a,o)}return s}catch{return new Map}}function aF(e){if(!(typeof window>"u"))try{const n={};for(const[s,a]of e)n[s]=a;window.localStorage.setItem(Gv,JSON.stringify(n))}catch{}}const Qi=iF();function rF({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:a}){const[r,o]=i.useState(0),l=()=>{aF(Qi),o(g=>g+1)};i.useEffect(()=>{if(Qi.size===0)return;const g=new Map(e.map(v=>[v.id,v]));let w=!1;for(const[v,b]of Qi){const y=g.get(v);if(!y)continue;if(!(y.status==="awaiting_input"||y.status==="error")){Qi.delete(v),w=!0;continue}So(y.updatedAt)>b&&(Qi.delete(v),w=!0)}w&&l()},[e]);const c=i.useMemo(()=>e.filter(g=>{if(g.status!=="awaiting_input"&&g.status!=="error")return!1;const w=Qi.get(g.id);return w===void 0?!0:So(g.updatedAt)>w}),[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=>{Qi.set(g.id,Math.max(So(g.updatedAt),Date.now())),l()},f=g=>{Qi.delete(g.id),l(),n(g)},p=()=>{const g=Date.now();for(const w of c)Qi.set(w.id,Math.max(So(w.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(Vs,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(mn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Dismiss all"})]})]}),t.jsx("div",{className:"session-notification-banner__list",children:c.map(g=>{const w=nF[g.type],v=g.status==="error";return t.jsxs("article",{className:`session-notification-banner__item${v?" session-notification-banner__item--error":""}`,"data-session-type":g.type,"data-session-status":g.status,children:[t.jsxs("div",{className:"session-notification-banner__item-main",children:[v?t.jsx(Vs,{size:16,className:"session-notification-banner__type-icon session-notification-banner__type-icon--error","aria-hidden":"true"}):t.jsx(w,{size:16,className:"session-notification-banner__type-icon","aria-hidden":"true"}),t.jsxs("div",{className:"session-notification-banner__text",children:[t.jsx("p",{className:"session-notification-banner__title",title:g.title,children:g.title}),t.jsx("p",{className:"session-notification-banner__meta",children:v?"Failed":sF[g.type]})]})]}),t.jsxs("div",{className:"session-notification-banner__actions",children:[t.jsx("button",{className:"session-notification-banner__resume",onClick:()=>f(g),children:v?"Retry":"Resume"}),t.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{h(g),s(g.id)},"aria-label":`Dismiss ${g.title}`,children:t.jsx(mn,{size:14,"aria-hidden":"true"})})]})]},g.id)})})]})}const Kv="fusion:cli-binary-banner-dismissed";function oF(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Kv)==="1"}catch{return!1}}function lF(){if(!(typeof window>"u"))try{window.localStorage.setItem(Kv,"1")}catch{}}function cF({onOpenSettings:e}){const[n,s]=i.useState(null),[a,r]=i.useState(()=>oF()),[o,l]=i.useState(!1),[c,d]=i.useState(null);i.useEffect(()=>{if(a)return;let y=!1;return mN().then(S=>{y||s(S)}).catch(()=>{}),()=>{y=!0}},[a]);const u=i.useCallback(async()=>{l(!0),d(null);try{const y=await hN();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(()=>{lF(),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",w=h?t.jsxs(t.Fragment,{children:["Your installed ",t.jsx("code",{children:"fn"}),"/",t.jsx("code",{children:"fusion"})," CLI is"," ",t.jsxs("strong",{children:["v",f??"unknown"]})," but this dashboard expects"," ",t.jsxs("strong",{children:["v",p]}),". Update to stay in sync."]}):t.jsxs(t.Fragment,{children:["Get the ",t.jsx("code",{children:"fn"})," and ",t.jsx("code",{children:"fusion"})," commands on your terminal so you can drive Fusion from anywhere. One click below or copy the command into your shell."]}),v=h?"Update with npm":"Install with npm",b=h?"Updating…":"Installing…";return t.jsxs("div",{className:"cli-binary-banner",role:"status",children:[t.jsxs("div",{className:"cli-binary-banner__body",children:[t.jsx("div",{className:"cli-binary-banner__title",children:g}),t.jsx("div",{className:"cli-binary-banner__text",children:w}),t.jsxs("div",{className:"cli-binary-banner__actions",children:[t.jsx("button",{type:"button",className:"cli-binary-banner__primary",onClick:()=>void u(),disabled:o,children:o?b:v}),t.jsx("button",{type:"button",className:"cli-binary-banner__secondary",onClick:e,children:"Open Settings"})]}),c&&t.jsx("div",{className:"cli-binary-banner__error",children:c})]}),t.jsx("button",{type:"button",className:"cli-binary-banner__dismiss","aria-label":"Dismiss",onClick:m,children:t.jsx(mn,{size:16})})]})}const dF={duplicate_active_id:"Duplicate active task ID",id_in_active_and_archived:"Task ID present in active and archived storage",next_sequence_at_or_below_used:"Allocator next sequence overlaps an existing task ID",committed_reservation_for_existing_id:"Committed reservation still points at an existing task ID",task_row_outside_known_prefix:"Task row uses a prefix outside allocator state"};function uF(e){return e.length<=5?e.join(", "):`${e.slice(0,5).join(", ")} +${e.length-5} more`}function mF({report:e,recommendedAction:n,onRefresh:s}){const[a,r]=i.useState(!1),[o,l]=i.useState(null);if(e.status!=="anomaly")return null;const c=async()=>{r(!0),l(null);try{const d=await Lj();s?.(d.taskIdIntegrity,d.taskIdIntegrity.recommendedAction)}catch(d){l(d instanceof Error?d.message:"Failed to refresh integrity status.")}finally{r(!1)}};return t.jsxs("section",{className:"task-id-integrity-banner",role:"alert","aria-live":"assertive",children:[t.jsxs("div",{className:"task-id-integrity-banner__header",children:[t.jsxs("div",{className:"task-id-integrity-banner__headline-wrap",children:[t.jsx("span",{className:"status-dot status-dot--error","aria-hidden":"true"}),t.jsx(zr,{"aria-hidden":"true"}),t.jsx("h2",{className:"task-id-integrity-banner__headline",children:"Task ID integrity anomaly detected"})]}),t.jsxs("button",{type:"button",className:"btn btn-sm task-id-integrity-banner__refresh",onClick:()=>{c()},disabled:a,children:[t.jsx(ps,{className:a?"task-id-integrity-banner__refresh-icon task-id-integrity-banner__refresh-icon--spinning":"task-id-integrity-banner__refresh-icon","aria-hidden":"true"}),a?"Re-checking…":"Re-check"]})]}),t.jsx("p",{className:"task-id-integrity-banner__body",children:"Fusion found allocator state that can cause task IDs to be reused or overwrite live task records."}),t.jsx("ul",{className:"task-id-integrity-banner__list",children:e.anomalies.map(d=>t.jsxs("li",{className:"task-id-integrity-banner__item",children:[t.jsx("strong",{className:"task-id-integrity-banner__item-title",children:dF[d.kind]}),t.jsx("span",{className:"task-id-integrity-banner__item-detail",children:d.details}),t.jsx("code",{className:"task-id-integrity-banner__ids",children:uF(d.affectedIds)})]},`${d.kind}:${d.prefix}:${d.affectedIds.join(",")}`))}),t.jsx("p",{className:"task-id-integrity-banner__footer",children:n}),o?t.jsx("p",{className:"task-id-integrity-banner__error",children:o}):null]})}function hF({latestVersion:e,currentVersion:n,onDismiss:s}){return t.jsxs("div",{className:"update-available-banner",role:"status","aria-live":"polite",children:[t.jsxs("p",{className:"update-available-banner__text",children:["Update available: v",e," (current: v",n,"). Run ",t.jsx("code",{children:"fn update"})," for an installed CLI, or pull this source checkout."," ",t.jsx("a",{className:"update-available-banner__link",href:"https://github.com/Runfusion/Fusion/blob/main/CHANGELOG.md",target:"_blank",rel:"noreferrer",children:"Release notes"})," ","·"," ",t.jsx("a",{className:"update-available-banner__link",href:"https://runfusion.ai",target:"_blank",rel:"noreferrer",children:"Learn more"})]}),t.jsx("button",{type:"button",className:"update-available-banner__dismiss touch-target","aria-label":"Dismiss update notice",onClick:s,children:t.jsx(mn,{size:16,"aria-hidden":"true"})})]})}function pF({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(zr,{"aria-hidden":"true"}),t.jsxs("span",{children:[e," approval ",a," need your attention"]})]}),t.jsxs("div",{className:"approval-notification-banner__actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:n,children:[t.jsx(ma,{"aria-hidden":"true"}),t.jsx("span",{children:"Open Mailbox"})]}),t.jsx("button",{type:"button",className:"btn-icon approval-notification-banner__dismiss",onClick:s,"aria-label":"Dismiss approval notification banner",children:t.jsx(mn,{"aria-hidden":"true"})})]})]})})}function fF({onResume:e}){const n=hO();if(!n)return null;const s=n.completedSteps.length,a=ua.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(ms,{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:()=>{pi("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(os,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function gF({onOpenSettings:e,onOpenModelOnboarding:n}){const s=Lr(),a=Uv(),[r,o]=i.useState(!0),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[m,h]=i.useState({needsAiProvider:!1,needsDefaultModel:!1,needsGitHub:!1});i.useEffect(()=>{if(!s||a){o(!1);return}let b=!1;return(async()=>{try{o(!0),c(!1);const[S,j]=await Promise.all([Po(),na()]);if(b)return;const C=S.providers??[],x=C.find(_=>_.id==="github"),R=!C.some(_=>_.id!=="github"&&_.authenticated),F=!j.defaultProvider&&!j.defaultModelId,E=x?!x.authenticated:!1;h({needsAiProvider:R,needsDefaultModel:F,needsGitHub:E})}catch{b||c(!0)}finally{b||o(!1)}})(),()=>{b=!0}},[s,a]);const f=i.useCallback(()=>{uO(),u(!0)},[]),p=i.useCallback(()=>{n()},[n]),g=i.useCallback(()=>{e("global-models")},[e]),w=i.useCallback(()=>{e("authentication")},[e]),v=i.useMemo(()=>{const b=[];return m.needsAiProvider&&b.push({id:"ai-provider",title:"Connect AI Provider",description:"Connect an AI provider to enable AI agents for task planning and code generation",actionLabel:"Set Up AI",onAction:p,icon:ls}),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:ib}),m.needsGitHub&&b.push({id:"github",title:"Connect GitHub",description:"Connect GitHub to import issues and track pull requests",actionLabel:"Connect GitHub",onAction:w,icon:ii}),b},[m.needsAiProvider,m.needsDefaultModel,m.needsGitHub,w,g,p]);return!s||a||d||r||l||v.length===0?null:t.jsxs("section",{className:"post-onboarding-recommendations",role:"region","aria-label":"Setup recommendations",children:[t.jsxs("div",{className:"post-onboarding-recommendations__main",children:[t.jsx("div",{className:"post-onboarding-recommendations__icon","aria-hidden":"true",children:t.jsx(Oi,{size:18,"aria-hidden":!0})}),t.jsxs("div",{className:"post-onboarding-recommendations__content",children:[t.jsx("h2",{className:"post-onboarding-recommendations__title",children:"Recommended Next Steps"}),t.jsx("p",{className:"post-onboarding-recommendations__description",children:"Complete these setup items to get the most out of Fusion."}),t.jsx("ul",{className:"post-onboarding-recommendations__list",children:v.map(b=>{const 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(pa,{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(mn,{size:16,"aria-hidden":!0})})]})}function bF({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 po(e){return e>99?"99+":String(e)}function xF({view:e,onChangeView:n,footerVisible:s,modalOpen:a=!1,keyboardOpen:r=!1,onOpenSettings:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:d,mailboxUnreadCount:u=0,mailboxPendingApprovalCount:m=0,chatHasUnreadResponse:h=!1,stashOrphanCount:f=0,onOpenGitManager:p,onOpenWorkflowSteps:g,onOpenSchedules:w,onOpenScripts:v,onToggleTerminal:b,onOpenFiles:y,onOpenTodos:S,todosOpen:j=!1,onOpenGitHubImport:C,onOpenPlanning:x,onResumePlanning:N,activePlanningSessionCount:R=0,onOpenUsage:F,onRunScript:E,projectId:_,onViewAllProjects:K,showSkillsTab:U,experimentalFeatures:A,onOpenNodes:T,pluginDashboardViews:H=[],shellConnectionControl:Q}){const se=oi(),[O,M]=i.useState(!1),[D,$]=i.useState(!1),[k,X]=i.useState({}),[le,ke]=i.useState(!1),He=i.useMemo(()=>Object.entries(k).sort(([ae],[Ve])=>ae.localeCompare(Ve)),[k]);i.useEffect(()=>{if(!D)return;let ae=!1;return ke(!0),$o(_).then(Ve=>{ae||X(Ve)}).catch(()=>{ae||X({})}).finally(()=>{ae||ke(!1)}),()=>{ae=!0}},[D,_]);const ye=i.useCallback(()=>M(!1),[]),je=i.useCallback(ae=>{ye(),ae?.()},[ye]);if(i.useEffect(()=>{if(!O)return;const ae=Ve=>{Ve.key==="Escape"&&M(!1)};return document.addEventListener("keydown",ae),()=>document.removeEventListener("keydown",ae)},[O]),se!=="mobile"||a||r)return null;const ne=R>0&&N?N:x,fe=!!U,Z=!!A?.todoView,re=fe,q=fe&&!re,he=H.filter(ae=>ae.view.placement==="primary").sort((ae,Ve)=>(ae.view.order??Number.MAX_SAFE_INTEGER)-(Ve.view.order??Number.MAX_SAFE_INTEGER)).slice(0,1),B=new Set(he.map(ae=>`${ae.pluginId}:${ae.view.viewId}`)),pe=H.filter(ae=>!B.has(`${ae.pluginId}:${ae.view.viewId}`)).sort((ae,Ve)=>(ae.view.order??Number.MAX_SAFE_INTEGER)-(Ve.view.order??Number.MAX_SAFE_INTEGER)),ze=e==="documents"||!!A?.evalsView&&e==="evals"||e==="research"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||j&&Z||e==="skills"&&!re||e==="graph"||e==="stash-recovery"||wr(e)&&!he.some(ae=>Eo(ae.pluginId,ae.view.viewId)===e);return t.jsxs(t.Fragment,{children:[t.jsxs("nav",{className:`mobile-nav-bar${s?" mobile-nav-bar--with-footer":""}`,role:"tablist","aria-label":"Primary navigation",children:[t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="board"||e==="list"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-tasks",role:"tab","aria-selected":e==="board"||e==="list",onClick:()=>{n(e==="board"||e==="list"?e:"board")},children:[t.jsx(va,{}),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(Qn,{}),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(Es,{}),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(Zi,{}),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(za,{}),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:po(u)})]}),re&&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(ls,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),he.map(ae=>{const Ve=Eo(ae.pluginId,ae.view.viewId),Te=Ql(ae.view.icon);return t.jsxs("button",{type:"button",className:`mobile-nav-tab${e===Ve||e==="graph"&&ae.pluginId==="fusion-plugin-dependency-graph"&&ae.view.viewId==="graph"?" mobile-nav-tab--active":""}`,"data-testid":`mobile-nav-tab-plugin-${ae.pluginId}-${ae.view.viewId}`,role:"tab","aria-selected":e===Ve||e==="graph"&&ae.pluginId==="fusion-plugin-dependency-graph"&&ae.view.viewId==="graph",onClick:()=>n(ae.pluginId==="fusion-plugin-dependency-graph"&&ae.view.viewId==="graph"?"graph":Ve),children:[t.jsx(Te,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:ae.view.label})]},`${ae.pluginId}:${ae.view.viewId}`)}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${ze?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>M(ae=>!ae),children:[t.jsx(nu,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),O&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:ye}),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:()=>je(d),children:[t.jsx(za,{}),t.jsx("span",{children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:po(u)}),m>0&&t.jsx("span",{className:"mobile-more-item-badge",children:po(m)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>je(l),children:[t.jsx(Js,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>je(c),children:[t.jsx(Cr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>je(p),children:[t.jsx(Os,{}),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:()=>je(b),children:[t.jsx(ea,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>$(ae=>!ae),"aria-expanded":D,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(qn,{size:14,className:`mobile-more-chevron${D?" mobile-more-chevron--open":""}`})})]}),D&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:le?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(jt,{className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):He.length>0?t.jsxs(t.Fragment,{children:[He.map(([ae,Ve])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${ae}`,onClick:()=>{E&&E(ae,Ve),ye(),$(!1)},children:[t.jsx(os,{}),t.jsx("span",{children:ae})]},ae)),v&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{ye(),$(!1),v()},children:[t.jsx(Si,{}),t.jsx("span",{children:"Manage Scripts…"})]})]}):v&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":"mobile-more-scripts-manage",onClick:()=>{ye(),$(!1),v()},children:[t.jsx(Si,{}),t.jsx("span",{children:"No scripts — add one…"})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>je(y),children:[t.jsx(js,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>je(ne),children:[t.jsx(Oi,{}),t.jsx("span",{children:"Planning"}),R>0&&t.jsx("span",{className:"mobile-more-item-badge",children:po(R)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>je(g),children:[t.jsx(Wl,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>je(w),children:[t.jsx(ta,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>je(C),children:[t.jsx(bF,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>je(F),children:[t.jsx(Js,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>je(K),children:[t.jsx(bc,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>je(()=>n("documents")),children:[t.jsx(xa,{}),t.jsx("span",{children:"Documents"})]}),A?.evalsView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-evals",onClick:()=>je(()=>n("evals")),children:[t.jsx(Es,{}),t.jsx("span",{children:"Evals"})]}),q&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>je(()=>n("skills")),children:[t.jsx(ls,{}),t.jsx("span",{children:"Skills"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-stash-recovery",onClick:()=>je(()=>n("stash-recovery")),children:[t.jsx(Oa,{}),t.jsx("span",{children:"Stash Recovery"}),f>0?t.jsx("span",{className:"mobile-more-item-badge",children:po(f)}):null]}),A?.researchView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-research",onClick:()=>je(()=>n("research")),children:[t.jsx(Xi,{}),t.jsx("span",{children:"Research"})]}),A?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>je(()=>n("insights")),children:[t.jsx(ms,{}),t.jsx("span",{children:"Insights"})]}),A?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>je(()=>n("memory")),children:[t.jsx(Io,{}),t.jsx("span",{children:"Memory"})]}),A?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{je(()=>n("dev-server"))},children:[t.jsx(Cr,{}),t.jsx("span",{children:"Dev Server"})]}),A?.nodesView&&T&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-nodes",onClick:()=>je(T),children:[t.jsx(jk,{}),t.jsx("span",{children:"Nodes"})]}),Z&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>je(()=>S?.()),children:[t.jsx(Bu,{}),t.jsx("span",{children:"Todos"})]}),pe.map(ae=>{const Ve=Eo(ae.pluginId,ae.view.viewId),Te=Ql(ae.view.icon);return t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":`mobile-more-item-plugin-${ae.pluginId}-${ae.view.viewId}`,onClick:()=>je(()=>n(ae.pluginId==="fusion-plugin-dependency-graph"&&ae.view.viewId==="graph"?"graph":Ve)),children:[t.jsx(Te,{}),t.jsx("span",{children:ae.view.label})]},`${ae.pluginId}:${ae.view.viewId}`)}),t.jsx("div",{className:"mobile-more-separator"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-settings",onClick:()=>je(o),children:[t.jsx(Co,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function yg(e){return e.trim().toLowerCase().replace(/[\s-]+/g,"_").replace(/_+/g,"_")}function Jv(e,n){const s=n.trim();if(!s)return!0;const a=yg(s);return yg(e).includes(a)||e.toLowerCase().includes(s.toLowerCase())}function vF({agents:e,filter:n,highlightedIndex:s,visible:a,onSelect:r,position:o="below",roomMemberIds:l,roomName:c}){const d=i.useMemo(()=>e.filter(g=>Jv(g.name,n)),[e,n]),u=!!l,m=u&&n.trim().length>0,h=i.useMemo(()=>u?d.filter(g=>l?.has(g.id)):d,[d,l,u]),f=i.useMemo(()=>u?d.filter(g=>!l?.has(g.id)):[],[d,l,u]),p=m?[...h,...f]:h;return a?t.jsx("div",{className:`agent-mention-popup agent-mention-popup--${o}`,"data-testid":"agent-mention-popup",role:"listbox","aria-label":"Agent mention suggestions",children:p.length===0?t.jsx("div",{className:"agent-mention-empty",children:"No agents found"}):t.jsxs(t.Fragment,{children:[u&&t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-members-header",children:c?`Members of #${c}`:"Room members"}),h.map((g,w)=>t.jsxs("button",{type:"button",className:`agent-mention-item${w===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${g.id}`,onMouseDown:v=>v.preventDefault(),onClick:()=>r(g),role:"option","aria-selected":w===s,children:[t.jsx(cc,{agent:g,size:20}),u&&t.jsx("span",{className:"status-dot agent-mention-member-dot","aria-label":"Room member"}),t.jsx("span",{className:"agent-mention-name",children:g.name}),t.jsx("span",{className:"agent-mention-role",children:g.role})]},g.id)),u&&!m&&f.length>0&&t.jsx("div",{className:"agent-mention-hint","data-testid":"agent-mention-other-hint",children:"Type to search other agents"}),u&&m&&f.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-others-header",children:"Other agents"}),f.map((g,w)=>{const v=h.length+w;return t.jsxs("button",{type:"button",className:`agent-mention-item${v===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${g.id}`,onMouseDown:b=>b.preventDefault(),onClick:()=>r(g),role:"option","aria-selected":v===s,children:[t.jsx(cc,{agent:g,size:20}),t.jsx("span",{className:"agent-mention-name",children:g.name}),t.jsx("span",{className:"agent-mention-role",children:g.role})]},g.id)})]})]})}):null}function wg(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,w=null,v=null;const b=()=>{w=null,a(h)},y=()=>{v=null,r(f)},S=()=>{w!==null&&(cancelAnimationFrame(w),w=null),v!==null&&(cancelAnimationFrame(v),v=null)};return l.current=S,{handlers:{onThinking:C=>{f+=C,v===null&&(v=requestAnimationFrame(y))},onText:C=>{h+=C,w===null&&(w=requestAnimationFrame(b))},onToolStart:C=>{p=[...p,{toolName:C.toolName,args:C.args,isError:!1,status:"running"}],o(p)},onToolEnd:C=>{const x=[...p];for(let N=x.length-1;N>=0;N--){const R=x[N];if(R?.toolName===C.toolName&&R.status==="running"){x[N]={...R,status:"completed",isError:C.isError,result:C.result},p=x,o(x);return}}p=[...x,{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 yF=["load failed","failed to fetch","networkerror when attempting to fetch resource.","connection aborted","connection closed unexpectedly","network error"];function wF(e){const n=e.trim().toLowerCase();return n?yF.some(s=>n.includes(s)):!1}function kF(){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 yr="__fn_agent__";function Yv(e,n){const s=typeof e=="string"?e.trim():"",a=typeof n=="string"?n.trim():"";return!s||!a?{}:{modelProvider:s,modelId:a}}function Ll(e,n,s){const a=typeof e=="string"?e.trim():"",r=Yv(n,s),o=a||(r.modelProvider&&r.modelId?yr:"");return o?{agentId:o,...r}:null}function Ol(e,n,s){const a=Yv(n,s),r=a.modelProvider??"",o=a.modelId??"";return`${e}::${r}/${o}`}function kg(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 jF(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 NF(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 fr(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:jF(e.metadata),fallbackInfo:NF(e.metadata),createdAt:e.createdAt}}function SF(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,w]=i.useState(""),[v,b]=i.useState(""),[y,S]=i.useState([]),[j,C]=i.useState(""),x=i.useRef(null),N=i.useRef(!1),R=i.useRef(null),F=i.useRef(""),E=i.useRef(f);E.current=f;const _=i.useRef(null),K=i.useRef(""),U=i.useRef(null),A=i.useRef(s);A.current=s;const T=i.useRef(0),H=3,Q=i.useRef(!1);i.useEffect(()=>{F.current=j},[j]);const se=i.useCallback(async()=>{c(!0);try{const q=await uh(e);o(q.sessions)}catch(q){console.error("[useQuickChat] Failed to refresh sessions:",q)}finally{c(!1)}},[e]),O=i.useCallback(async q=>{const L={agentId:q.agentId};return q.modelProvider&&q.modelId&&(L.modelProvider=q.modelProvider,L.modelId=q.modelId),(await V0(L,e)).session},[e]),M=i.useCallback((q,L)=>{if(x.current||!q)return!0;N.current=!1,L&&(w(L.streamingText),b(L.streamingThinking),S(L.toolCalls)),p(!0);const{handlers:xe}=wg({sessionId:q,tempUserMessageId:"",setStreamingText:w,setStreamingThinking:b,setStreamingToolCalls:S,cancelStreamingFlushesRef:R,addToast:n,onFallbackSession:(he,B)=>{const pe=kg(he.fallbackModel);o(ze=>ze.map(ae=>ae.id===B?{...ae,...pe}:ae)),a(ze=>ze&&ze.id===B?{...ze,...pe}:ze)},onDone:()=>{w(""),b(""),S([]),p(!1),E.current=!1,x.current=null,Zr(q,{limit:50},e).then(he=>{u(he.messages.map(fr))}).catch(()=>{})},onError:he=>{w(""),b(""),S([]),p(!1),E.current=!1,x.current=null;const B=typeof he=="string"&&he.trim()?he:"Failed to get response";n?.(B,"error"),Zr(q,{limit:50},e).then(pe=>{u(pe.messages.map(fr))}).catch(()=>{})}});return x.current=Y0(q,xe,e,{...typeof L?.replayFromEventId=="number"?{lastEventId:L.replayFromEventId}:{}}),!0},[n,e]),D=i.useCallback(async(q,L,xe)=>{const he=Ll(q,L,xe);if(!he)return;const B=Ol(he.agentId,he.modelProvider,he.modelId);c(!0);try{const{session:pe}=await q0({agentId:he.agentId,modelProvider:he.modelProvider,modelId:he.modelId},e);if(pe)a(pe),K.current=B,pe.isGenerating&&M(pe.id,pe.inFlightGeneration);else{const ze=await O(he);a(ze),K.current=B}T.current=0}catch(pe){console.error("[useQuickChat] Failed to initialize session:",pe),T.current+=1,T.current<=H&&n?.("Failed to initialize chat","error")}finally{c(!1)}},[M,e,n,O]),$=i.useCallback(async()=>{if(s){h(!0);try{const q=await Zr(s.id,{limit:50},e);u(q.messages.map(fr))}catch(q){console.error("[useQuickChat] Failed to load messages:",q)}finally{h(!1)}}},[s,e]);i.useEffect(()=>{s?$():u([])},[s,$]),i.useEffect(()=>{if(!s?.isGenerating||(x.current||M(s.id,s.inFlightGeneration),!E.current||x.current||!s))return;const q=setInterval(async()=>{if(!E.current||x.current||!s){clearInterval(q);return}try{if(!(await W0(s.id,e)).session.isGenerating){clearInterval(q);const xe=await Zr(s.id,{limit:50},e);u(xe.messages.map(fr)),w(""),b(""),S([]),p(!1)}}catch{}},3e3);return()=>clearInterval(q)},[s,M,e]);const k=i.useCallback(async()=>{if(s){h(!0);try{const q=await Zr(s.id,{limit:50},e);u(q.messages.map(fr))}catch(q){console.error("[useQuickChat] Failed to reload messages:",q)}finally{h(!1)}}},[s,e]),X=i.useCallback(()=>{R.current?.(),R.current=null,F.current="",C(""),w(""),b(""),S([]),p(!1)},[]),le=i.useCallback(async(q,L,xe)=>{const he=Ll(q,L,xe);if(!he)return;const B=Ol(he.agentId,he.modelProvider,he.modelId);U.current=he;const pe=B===K.current&&A.current;if(pe||(x.current&&(x.current.close(),x.current=null),X()),pe){await k();return}a(null),u([]),K.current=B,await D(he.agentId,he.modelProvider,he.modelId)},[D,k,X]),ke=i.useCallback(async q=>{const L=Ll(q.agentId,q.modelProvider??void 0,q.modelId??void 0);L&&(U.current=L,K.current=Ol(L.agentId,L.modelProvider,L.modelId),x.current&&(x.current.close(),x.current=null),X(),a(q),q.isGenerating&&M(q.id,q.inFlightGeneration))},[M,X]),He=i.useCallback(async(q,L)=>{await le(yr,q,L)},[le]),ye=i.useCallback(async(q,L,xe)=>{const B=Ll(q??"",L,xe)??U.current;if(!B)return;U.current=B;const pe=Ol(B.agentId,B.modelProvider,B.modelId);Q.current=!0,T.current=0,x.current&&(x.current.close(),x.current=null),X(),u([]),a(null),c(!0);try{const ze=await O(B);a(ze),K.current=pe;const ae=await uh(e);o(ae.sessions)}catch(ze){console.error("[useQuickChat] Failed to start a fresh session:",ze),n?.("Failed to start a new chat","error")}finally{Q.current=!1,c(!1)}},[n,O,e,X]),je=i.useCallback(()=>{s&&(N.current=!0,R.current?.(),R.current=null,x.current?.close(),x.current=null,G0(s.id,e).catch(()=>{}),p(!1),w(""),b(""),S([]))},[s,e]),ne=i.useCallback(()=>{F.current="",C("")},[]),fe=i.useRef(()=>Promise.resolve()),Z=kF(),re=i.useCallback((q,L)=>{if(!s||!q.trim()&&(!L||L.length===0))return Promise.resolve();if(E.current)return L&&L.length>0?Promise.reject(new Error("Cannot send attachments while a response is streaming")):(F.current=q,C(q),Promise.resolve());const xe=new Promise((he,B)=>{_.current={resolve:he,reject:B},N.current=!1,x.current&&(x.current.close(),x.current=null);const pe=`temp-${Date.now()}`,ze={id:pe,sessionId:s.id,role:"user",content:q,createdAt:new Date().toISOString()};u(Ve=>[...Ve,ze]),w(""),b(""),S([]),p(!0);const{handlers:ae}=wg({sessionId:s.id,tempUserMessageId:pe,setStreamingText:w,setStreamingThinking:b,setStreamingToolCalls:S,cancelStreamingFlushesRef:R,addToast:n,onFallbackSession:(Ve,Te)=>{const rt=kg(Ve.fallbackModel);o(Be=>Be.map(ce=>ce.id===Te?{...ce,...rt}:ce)),a(Be=>Be&&Be.id===Te?{...Be,...rt}:Be)},onDone:({messageId:Ve,message:Te,accumulated:rt})=>{const Be=Te?fr(Te):{id:Ve||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:rt.text,thinkingOutput:rt.thinking||void 0,toolCalls:rt.toolCalls.length>0?rt.toolCalls:void 0,fallbackInfo:rt.fallbackInfo,createdAt:new Date().toISOString()};u(Re=>[...Re,Be]),w(""),b(""),S([]),p(!1),E.current=!1,x.current=null,_.current?.resolve(),_.current=null;const ce=F.current.trim();ce&&(F.current="",C(""),fe.current(ce))},onError:Ve=>{w(""),b(""),S([]),p(!1),E.current=!1,x.current=null,console.error("[useQuickChat] Stream error:",Ve);const Te=typeof Ve=="string"&&Ve.trim()?Ve:"Failed to get response";if(typeof Ve=="string"&&wF(Ve)&&(Z.isHiddenNow()||Z.wasRecentlyHidden(5e3))?(console.info("[useQuickChat] Suppressed tab-suspension stream error:",Ve),_.current?.resolve()):(n?.(Te,"error"),_.current?.reject(new Error(Te))),_.current=null,!N.current){const Be=F.current.trim();Be&&(F.current="",C(""),fe.current(Be))}k()}});x.current=J0(s.id,q,ae,L,e)});return xe.catch(()=>{}),xe},[s,e,n,k,Z]);return fe.current=re,i.useEffect(()=>()=>{x.current&&(x.current.close(),x.current=null)},[]),i.useMemo(()=>({activeSession:s,sessions:r,sessionsLoading:l,messages:d,messagesLoading:m,isStreaming:f,streamingText:g,streamingThinking:v,streamingToolCalls:y,pendingMessage:j,sendMessage:re,stopStreaming:je,clearPendingMessage:ne,switchSession:le,selectSession:ke,startModelChat:He,startFreshSession:ye,refreshSessions:se,loadMessages:$,reloadMessages:k,skipNextSessionInitRef:Q}),[s,r,l,d,m,f,g,v,y,j,re,je,ne,le,ke,He,ye,se,$,k])}function CF(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,w=g&&g!=="all"?{state:g}:void 0,v=n?.showSystemAgents??!1,b=await Ur({...w,...p,includeEphemeral:p?.includeEphemeral??v},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 r1(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 yi(`/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||!HC(p));return{agents:s,activeAgents:f,stats:r,isLoading:l,loadAgents:d,loadStats:u,refreshAgents:m}}function EF({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=NC(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(nb,{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 _F=200;function MF(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),w=i.useRef(null),v=i.useRef(null);i.useEffect(()=>()=>{w.current&&clearTimeout(w.current),v.current?.abort()},[]);const b=i.useCallback((x,N)=>{if(N<0||N>x.length){r(!1);return}const R=F=>/[a-zA-Z0-9/_.-]/.test(F);for(let F=N-1;F>=0;F--){if(x[F]==="#")if(F===0){const E=x.slice(F+1,N);d(F),l(E),g(0),r(!0);return}else{const E=x[F-1];if(/[\s,.;:!?'"()[\]{}]/.test(E)){const _=x.slice(F+1,N);d(F),l(_),g(0),r(!0);return}r(!1);return}if(!R(x[F])){r(!1);return}}r(!1)},[]),y=i.useCallback(()=>{r(!1),l(""),d(-1),m([]),g(0),f(!1)},[]),S=i.useCallback(async x=>{if(!x.trim()){m([]),f(!1);return}v.current?.abort(),v.current=new AbortController;try{f(!0);const N=await uS(x,s,n);m(N.files),g(0)}catch(N){N.name!=="AbortError"&&m([])}finally{f(!1)}},[s,n]);i.useEffect(()=>{if(a)return w.current&&clearTimeout(w.current),w.current=setTimeout(()=>{S(o)},_F),()=>{w.current&&clearTimeout(w.current)}},[o,a,S]);const j=i.useCallback((x,N)=>{if(!a||c<0)return N;const R=N.slice(0,c),F=N.slice(c+1),E=F.match(/[\s]|$/),_=E?E.index:F.length,K=F.slice(_);return`${R}#${x.path}${K}`},[a,c]),C=i.useCallback((x,N)=>{if(!a||u.length===0)return!1;switch(x.key){case"ArrowDown":return x.preventDefault(),g(R=>Math.min(R+1,u.length-1)),!0;case"ArrowUp":return x.preventDefault(),g(R=>Math.max(R-1,0)),!0;case"Enter":case"Tab":return u[p]?(x.preventDefault(),!0):!1;case"Escape":return x.preventDefault(),y(),!0;default:return!1}},[a,u,p,y]);return{mentionActive:a,files:u,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:g,detectMention:b,selectFile:j,dismissMention:y,handleKeyDown:C}}function AF(e){return`${e.name?.trim()||e.id} (${e.role})`}function fo(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 RF(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 Hl(e,n){return e.length<=n?e:`${e.slice(0,n)}…`}function IF(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}=${Hl(r,50)}`}).join(", ")}function TF(e){if(e===void 0)return null;if(typeof e=="string")return Hl(e,200);try{return Hl(JSON.stringify(e),200)}catch{return Hl(String(e),200)}}function Qv(e,n=!1){if(!e||e.length===0)return null;const s=(f,p)=>{const g=f.status==="running",w=f.status==="completed"&&f.isError,v=IF(f.args),b=TF(f.result),y=g?v:b?`result: ${b}`:v?`args: ${v}`:null,S=n?null:y,j=g?"running":w?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${g?" chat-tool-call--running":""}${w?" chat-tool-call--error":""}`,open:g,children:[t.jsxs("summary",{children:[t.jsx("span",{className:"chat-tool-call-status-dot","aria-hidden":"true"}),t.jsx("span",{className:"chat-tool-call-name",title:f.toolName,children:f.toolName}),S&&t.jsx("span",{className:"chat-tool-call-preview",title:S,children:S}),t.jsx("span",{className:"chat-tool-call-status-text",children:j})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[v&&t.jsxs("div",{className:"chat-tool-call-row",children:[t.jsx("span",{className:"chat-tool-call-label",children:"args"}),t.jsx("span",{className:"chat-tool-call-value",children:v})]}),b&&t.jsxs("div",{className:`chat-tool-call-row${w?" 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(Om,{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(Om,{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 Xv={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 jg(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 PF(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 Fl={width:320,height:400},$F=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"]),DF=[".png",".jpg",".jpeg",".gif",".webp",".txt",".json",".yaml",".yml",".log",".csv",".xml",".md"];function LF(e){return e.type.startsWith("image/")}function OF(e){if($F.has(e.type))return!0;const n=e.name.toLowerCase();return DF.some(s=>n.endsWith(s))}const gr={width:280,height:260},Ls=768,br=8;function FF(e,n){const s=i.useCallback(()=>{if(typeof window>"u")return 0;const j=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return j&&parseFloat(j)||0},[]),a=i.useCallback(()=>typeof window<"u"&&window.innerWidth<=768?{x:4,y:4+s()}:{x:24,y:24+s()},[s]),[r,o]=i.useState(()=>{if(typeof window>"u")return a();const j=`fusion-quick-chat-position-${e||"default"}`;try{const C=localStorage.getItem(j);if(C){const x=JSON.parse(C);if(typeof x.x=="number"&&typeof x.y=="number"&&!isNaN(x.x)&&!isNaN(x.y))return x}}catch{}return a()}),[l,c]=i.useState(!1),d=i.useRef(null),u=i.useRef(r),m=i.useRef(null),h=i.useRef(null),f=n??i.useRef(!1);i.useEffect(()=>{u.current=r},[r]);const p=i.useCallback(j=>{if(typeof window>"u")return j;const C=48,x=window.innerWidth<=768?4:8,N=window.innerWidth<=768?44:0,R=window.innerWidth>768?s():0,F=window.innerWidth-C-x,E=window.innerHeight-C-x-N-R;return{x:Math.max(x,Math.min(F,j.x)),y:Math.max(x,Math.min(E,j.y))}},[s]),g=i.useCallback(j=>{if(typeof window>"u")return;const C=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(C,JSON.stringify(j))}catch{}},[e]),w=i.useCallback(()=>{if(!d.current)return;const j=h.current,C=m.current;j&&C!==null&&typeof j.releasePointerCapture=="function"&&j.releasePointerCapture(C),d.current=null,m.current=null,h.current=null,c(!1),document.body.style.userSelect="",f.current&&g(u.current),document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b),document.removeEventListener("pointercancel",y)},[g]),v=i.useCallback(j=>{if(!d.current||m.current!==null&&j.pointerId!==m.current)return;const C=j.clientX-d.current.pointerX,x=j.clientY-d.current.pointerY;if((Math.abs(C)>=5||Math.abs(x)>=5)&&(f.current=!0),!f.current)return;const N=d.current.x-C,R=d.current.y-x,F=p({x:N,y:R});u.current=F,o(F)},[p]),b=i.useCallback(j=>{m.current!==null&&j.pointerId!==m.current||w()},[w]),y=i.useCallback(j=>{m.current!==null&&j.pointerId!==m.current||w()},[w]),S=i.useCallback(j=>{if(j.button!==0&&j.pointerType==="mouse")return;const C=j.currentTarget;j.preventDefault(),typeof C.setPointerCapture=="function"&&C.setPointerCapture(j.pointerId);const x=u.current;d.current={x:x.x,y:x.y,pointerX:j.clientX,pointerY:j.clientY},m.current=j.pointerId,h.current=C,f.current=!1,c(!0),document.body.style.userSelect="none",document.addEventListener("pointermove",v,{passive:!0}),document.addEventListener("pointerup",b),document.addEventListener("pointercancel",y)},[y,v,b]);return i.useEffect(()=>()=>{document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b),document.removeEventListener("pointercancel",y),document.body.style.userSelect=""},[y,v,b]),{position:r,isDragging:l,handlePointerDown:S}}function zF(e,n,s){const a=`fusion:quick-chat-size-${e||"default"}`,r=i.useCallback(()=>typeof window<"u"&&window.innerWidth>Ls,[]),o=i.useCallback((f,p,g)=>{if(typeof window>"u")return f;const w=Math.max(gr.width,window.innerWidth-p-br),v=Math.max(gr.height,window.innerHeight-g-br);return{width:Math.max(gr.width,Math.min(w,f.width)),height:Math.max(gr.height,Math.min(v,f.height))}},[]),l=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=Ls)return Fl;try{const f=localStorage.getItem(a);if(!f)return Fl;const p=JSON.parse(f);return typeof p.width!="number"||typeof p.height!="number"?Fl:{width:p.width,height:p.height}}catch{return Fl}},[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 w={pointerX:f.clientX,pointerY:f.clientY,width:c.width,height:c.height,anchorRight:u.right,anchorBottom:u.bottom};document.body.style.userSelect="none";const v=y=>{const S=y.clientX-w.pointerX,j=y.clientY-w.pointerY;let C=w.width,x=w.height,N=w.anchorRight,R=w.anchorBottom;if(p.includes("w")&&(C=w.width-S),p.includes("e")){const A=S;C=w.width+A,N=w.anchorRight-A}if(p.includes("n")&&(x=w.height-j),p.includes("s")){const A=j;x=w.height+A,R=w.anchorBottom-A}const F=n+N,E=s+R,_=o({width:C,height:x},F,E),K=Math.max(br-n,Math.min(window.innerWidth-n-gr.width-br,N)),U=Math.max(br-s,Math.min(window.innerHeight-s-gr.height-br,R));d(_),m({right:K,bottom:U})},b=y=>{typeof g.releasePointerCapture=="function"&&g.releasePointerCapture(y.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b);try{localStorage.setItem(a,JSON.stringify({width:c.width,height:c.height}))}catch{}};document.addEventListener("pointermove",v),document.addEventListener("pointerup",b)},[u.bottom,u.right,o,s,n,r,c.height,c.width,a]);return{panelSize:c,anchorOffset:u,handleResizeStart:h}}const Ng=i.memo(function({message:n,forcePlain:s,mentionAgentsByName:a,roomContext:r,onToggleRender:o}){const l=n.role==="user",c=i.useMemo(()=>{if(!l)return null;const u=n.content,m=/@([\w-]+)/g,h=[];let f=0,p=m.exec(u);for(;p;){const[g,w=""]=p,v=p.index;v>f&&h.push(u.slice(f,v));const b=w.replace(/_/g," ").toLowerCase(),y=a.get(b);if(y){const S=!!(r&&!r.memberIds.has(y.id)),j=S?`Not a member of ${r?.roomName}`:void 0;h.push(t.jsxs("span",{className:`chat-mention-chip${S?" chat-mention-chip--non-member":""}`,title:j,"aria-label":j,children:["@",y.name.replace(/\s+/g,"_")]},`${y.id}-${v}`))}else h.push(g);f=v+g.length,p=m.exec(u)}return f<u.length&&h.push(u.slice(f)),h.length===0?u:h},[l,n.content,a,r]),d=i.useMemo(()=>l?null:s?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:n.content}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(xi,{remarkPlugins:[vi],components:Xv,children:n.content})}),[l,s,n.content]);return t.jsxs("div",{className:`quick-chat-panel-message ${l?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${n.id}`,children:[l?t.jsx("p",{children:c}):t.jsxs(t.Fragment,{children:[d,t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${s?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":s?"Show rendered markdown":"Show plain text",onClick:()=>o(n.id),children:s?t.jsx(zu,{size:14}):t.jsx(Fr,{size:14})})]}),Qv(n.toolCalls,!0)]})});function BF({projectId:e,addToast:n,showFAB:s=!0,open:a,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:d,roomContext:u=null}){const{agents:m}=CF(e),[h,f]=i.useState(!1),p=a!==void 0,g=p?a:h,w=p?ie=>{r?.(typeof ie=="function"?ie(g):ie)}:f,{keyboardOpen:v}=aa({enabled:g}),b=oi(),y=b==="mobile",[S,j]=i.useState("agent"),[C,x]=i.useState(""),[N,R]=i.useState(!1),[F,E]=i.useState("model"),[_,K]=i.useState(""),[U,A]=i.useState(""),[T,H]=i.useState([]),[Q,se]=i.useState(!1),[O,M]=i.useState(""),[D,$]=i.useState(""),[k,X]=i.useState(""),[le,ke]=i.useState([]),[He,ye]=i.useState(!1),[je,ne]=i.useState(!1),[fe,Z]=i.useState(""),[re,q]=i.useState(0),[L,xe]=i.useState(""),[he,B]=i.useState(!1),[pe,ze]=i.useState(0),[ae,Ve]=i.useState(-1),[Te,rt]=i.useState(()=>new Set),[Be,ce]=i.useState(!1),[Re,Le]=i.useState([]),[ct,Ue]=i.useState(!1),[ue,oe]=i.useState(!1),[,Ee]=i.useState(!1),[ft,ht]=i.useState({top:0,left:0}),tt=MF({projectId:e}),xt=i.useCallback(ie=>{if(!ie||!tt.mentionActive)return;const $e=ie.getBoundingClientRect();ht({top:$e.top-260,left:$e.left+8})},[tt.mentionActive]),Me=i.useRef(!1),Ye=i.useRef(!1),dt=i.useRef(!1),wt=i.useRef(""),St=i.useRef(!1),Fe=i.useRef(C),J=i.useRef(O),me=i.useRef(0),Ze=i.useRef(null),be=i.useRef(null),gt=i.useRef(0),{position:$t,isDragging:Ie,handlePointerDown:ge}=FF(e,Me),st=$t.y+60,{panelSize:yt,anchorOffset:pt,handleResizeStart:vt}=zF(e,$t.x,st),Ut=typeof window<"u"&&window.innerWidth>Ls,{activeSession:Dt,messages:nn,isStreaming:on,streamingText:sn,streamingThinking:ln,streamingToolCalls:xn,sessions:qt,sessionsLoading:Qt,messagesLoading:hn,sendMessage:Zt,stopStreaming:ve,pendingMessage:Pe,clearPendingMessage:Ke,switchSession:at,selectSession:We,startModelChat:It,startFreshSession:Lt,refreshSessions:Bt,skipNextSessionInitRef:Gt}=SF(e,n),bt=i.useRef(null),Ot=i.useRef(null),en=i.useRef(null),Kt=i.useRef(null),Sn=i.useRef(null),dn=i.useRef([]),Jt=i.useRef(!1),tn=i.useRef(!1),Ne=i.useRef(!1),W=i.useRef(null),Y=i.useRef(!1),_e=i.useRef(!1),ut=i.useRef({isOpen:!1,sessionId:null});i.useEffect(()=>{if(!g||typeof window>"u"||typeof document>"u"||window.innerWidth>Ls)return;const ie=window.scrollY,$e=document.documentElement,Qe=document.body,Ft={htmlOverflow:$e.style.overflow,bodyOverflow:Qe.style.overflow};return window.scrollTo(0,0),$e.style.overflow="hidden",Qe.style.overflow="hidden",()=>{$e.style.overflow=Ft.htmlOverflow,Qe.style.overflow=Ft.bodyOverflow,window.scrollTo(0,ie)}},[g]),i.useLayoutEffect(()=>{if(!g||typeof window>"u"||!window.visualViewport)return;const ie=bt.current;if(!ie)return;const $e=window.visualViewport,Qe=()=>{Y.current||(ie.style.setProperty("--vv-height",`${$e.height}px`),ie.style.setProperty("--vv-offset-top",`${$e.offsetTop||0}px`))};return Qe(),$e.addEventListener("resize",Qe),$e.addEventListener("scroll",Qe),()=>{$e.removeEventListener("resize",Qe),$e.removeEventListener("scroll",Qe)}},[g]);const At=O||D,zt=i.useMemo(()=>fo(At),[At]),yn=i.useMemo(()=>S==="model"&&Dt?.modelProvider&&Dt?.modelId?`${Dt.modelProvider}/${Dt.modelId}`:At,[Dt?.modelId,Dt?.modelProvider,S,At]),Zn=i.useMemo(()=>fo(yn),[yn]),vn=i.useMemo(()=>T.find(ie=>`${ie.provider}/${ie.id}`===yn)??null,[yn,T]),Dn=i.useMemo(()=>RF(vn,Zn),[vn,Zn]),de=i.useMemo(()=>S==="model"?zt?`${yr}::${zt.modelProvider}/${zt.modelId}`:"":C?`${C}::`:"",[S,C,zt]),ot=!(S==="agent"?!!C:!!zt)||!Dt,_t=i.useMemo(()=>!!C&&qt.some(ie=>!ie.modelProvider&&!ie.modelId&&ie.agentId===C),[C,qt]);i.useEffect(()=>{Fe.current=C},[C]),i.useEffect(()=>{J.current=O},[O]),i.useEffect(()=>{if(m.length===0){x(""),j("model");return}if(St.current&&_t)return;m.some($e=>$e.id===C)||x(m[0]?.id??"")},[m,_t,C]),i.useEffect(()=>{!g||Ye.current||(Ye.current=!0,dt.current=!1,se(!0),Ws().then(ie=>{const $e=ie.models??[];if(H($e),J.current||$e.length===0)return;const Qe=ie.defaultProvider,Ft=ie.defaultModelId;if(Qe&&Ft){const pn=`${Qe}/${Ft}`;if($e.some(Un=>`${Un.provider}/${Un.id}`===pn)){$(pn),J.current||M(pn),St.current||j("model");return}}$("");const cn=$e[0];cn&&!J.current&&M(`${cn.provider}/${cn.id}`)}).catch(ie=>{console.error("[QuickChatFAB] Failed to load models:",ie),H([]),$("")}).finally(()=>{dt.current=!0,se(!1)}))},[g,m.length,O]),i.useEffect(()=>{!g||!e||(ye(!0),H0(e).then(ie=>{ke(ie)}).catch(()=>{ke([])}).finally(()=>{ye(!1)}))},[g,e]),i.useEffect(()=>{g&&Bt()},[g,Bt]),i.useEffect(()=>{if(!g||Qt||St.current||qt.length===0)return;const ie=qt[0];ie&&(ie.modelProvider&&ie.modelId?(j("model"),M(`${ie.modelProvider}/${ie.modelId}`)):(j("agent"),x(ie.agentId)),St.current=!0)},[g,qt,Qt]),i.useEffect(()=>{if(!g){wt.current="";return}if(!St.current&&qt.length===0&&Ye.current&&!dt.current)return;if(!de){wt.current="";return}if(Gt.current){wt.current=de;return}const $e=de===wt.current&&!Dt&&!Qt;if(!(de===wt.current&&!$e)){if(wt.current=de,S==="model"&&zt){It(zt.modelProvider,zt.modelId);return}S==="agent"&&C&&at(C)}},[g,S,zt,C,de,Dt,Qt,It,at,Gt]),i.useEffect(()=>{g||(B(!1),xe(""),Ve(-1),ne(!1),Z(""),q(0),dn.current.forEach(ie=>{ie.previewUrl&&URL.revokeObjectURL(ie.previewUrl)}),Le([]))},[g]),i.useEffect(()=>{dn.current=Re},[Re]),i.useEffect(()=>{if(!g){Jt.current=!1;return}typeof window>"u"||(Jt.current=window.innerWidth<=Ls)},[g]),i.useEffect(()=>{if(!g||ot||!Jt.current)return;const ie=Kt.current;if(!ie)return;const $e=document.activeElement,Qe=$e?bt.current?.contains($e):!1,Ft=$e===document.body,cn=$e===W.current;if(!Qe&&!Ft&&!cn){Jt.current=!1;return}if(cn){ie.focus({preventScroll:!0}),Jt.current=!1;return}const pn=requestAnimationFrame(()=>{ie.focus(),Jt.current=!1});return()=>cancelAnimationFrame(pn)},[g,ot]),i.useEffect(()=>()=>{dn.current.forEach(ie=>{ie.previewUrl&&URL.revokeObjectURL(ie.previewUrl)})},[]);const G=i.useCallback(()=>{R(!0),E("model"),K(m[0]?.id??""),A(O||D||"")},[m,D,O]),Oe=i.useMemo(()=>m.find(ie=>ie.id===C)??null,[m,C]),Mt=i.useMemo(()=>{const ie=fe.trim().toLowerCase();return(ie?le.filter(Qe=>Qe.name.toLowerCase().includes(ie)):le).slice(0,10)},[le,fe]),Xt=i.useMemo(()=>{const ie=m.filter(Ft=>Jv(Ft.name,L));if(!u)return ie;const $e=ie.filter(Ft=>u.memberIds.has(Ft.id));if(L.trim().length===0)return $e;const Qe=ie.filter(Ft=>!u.memberIds.has(Ft.id));return[...$e,...Qe]},[m,L,u]),_n=i.useMemo(()=>{const ie=new Map;for(const $e of m)ie.set($e.name.toLowerCase(),$e);return ie},[m]);i.useEffect(()=>{q(0)},[Mt]),i.useEffect(()=>{ze(0)},[L,he]),i.useEffect(()=>()=>{Ze.current!==null&&(window.clearTimeout(Ze.current),Ze.current=null),be.current!==null&&(window.clearTimeout(be.current),be.current=null)},[]),i.useEffect(()=>{if(!g)return;const ie=Qe=>{const Ft=Qe.target;bt.current?.contains(Ft)||Ot.current?.contains(Ft)||Ft.closest(".model-combobox-dropdown--portal")||w(!1)},$e=Qe=>{Qe.key==="Escape"&&w(!1)};return document.addEventListener("mousedown",ie),document.addEventListener("keydown",$e),()=>{document.removeEventListener("mousedown",ie),document.removeEventListener("keydown",$e)}},[g,w]);const Pn=i.useCallback(()=>{const ie=en.current;if(!ie)return;const Qe=ie.scrollTop+ie.clientHeight>=ie.scrollHeight-50;oe(!Qe),_e.current=!Qe},[]),kn=i.useCallback(ie=>{if(!ie.isConnected)return;let $e=0,Qe=0,Ft=-1;const cn=6,pn=()=>{if(ie.isConnected){if(ie.scrollTop=ie.scrollHeight,ie.scrollHeight===Ft?Qe+=1:(Qe=0,Ft=ie.scrollHeight),$e+=1,$e>=cn||Qe>=2){oe(!1),_e.current=!1;return}window.requestAnimationFrame(pn)}};pn()},[]),Vn=i.useCallback(()=>{const ie=en.current;ie&&kn(ie)},[kn]);i.useLayoutEffect(()=>{const ie=Dt?.id??null,$e=ut.current;if(ut.current={isOpen:g,sessionId:ie},!g||!ie)return;const Qe=!$e.isOpen&&g,Ft=$e.isOpen&&$e.sessionId!==ie;if(!Qe&&!Ft)return;const cn=en.current;cn&&kn(cn)},[g,Dt?.id,kn]),i.useEffect(()=>{if(!y||!g||!Dt)return;const ie=()=>{const Qe=en.current;Qe&&kn(Qe)},$e=()=>{document.visibilityState==="visible"&&ie()};return document.addEventListener("visibilitychange",$e),window.addEventListener("pageshow",ie),()=>{document.removeEventListener("visibilitychange",$e),window.removeEventListener("pageshow",ie)}},[y,g,Dt,kn]),i.useEffect(()=>{g&&(_e.current||Vn())},[nn,sn,ln,on,g,Vn]);const $s=i.useMemo(()=>{const ie=new Map(m.map(Qe=>[Qe.id,Qe.name?.trim()||Qe.id])),$e=new Map(T.map(Qe=>[`${Qe.provider}/${Qe.id}`,Qe.name?.trim()||""]));return qt.map((Qe,Ft)=>{const cn=Qe.title?.trim()||`Session ${Ft+1}`;let pn=null;if(Qe.agentId&&Qe.agentId!==yr)pn=ie.get(Qe.agentId)||Qe.agentId;else if(Qe.modelProvider&&Qe.modelId){const jn=`${Qe.modelProvider}/${Qe.modelId}`,Un=$e.get(jn);pn=Un?`${Un} [${jn}]`:jn}return{id:Qe.id,label:pn?`${cn} — ${pn}`:cn}})},[m,T,qt]),vs=i.useMemo(()=>S==="agent"?Oe?`Message ${Oe.name||Oe.id}`:"Select an agent to start chatting":Dn?`Message ${Dn}`:"Select a model to start chatting",[S,Oe,Dn]),As=i.useCallback(ie=>{const $e=qt.find(Qe=>Qe.id===ie);$e&&(St.current=!0,$e.modelProvider&&$e.modelId?(j("model"),M(`${$e.modelProvider}/${$e.modelId}`)):(j("agent"),x($e.agentId)),We($e))},[We,qt]),bn=i.useCallback(async()=>{if(!Qt){if(St.current=!0,F==="agent"){if(!_)return;j("agent"),x(_),await Lt(_)}else{const ie=fo(U||O||D);if(!ie)return;j("model"),M(`${ie.modelProvider}/${ie.modelId}`),await Lt(yr,ie.modelProvider,ie.modelId)}await Bt(),R(!1),E("model")}},[D,_,F,U,Bt,O,Qt,Lt]),Ht=Pe.length>50?`${Pe.slice(0,50)}…`:Pe,On=i.useCallback(ie=>{if(!ie||ie.length===0)return;const $e=[];for(let Qe=0;Qe<ie.length;Qe+=1){const Ft=ie[Qe];OF(Ft)&&$e.push({file:Ft,previewUrl:LF(Ft)?URL.createObjectURL(Ft):""})}$e.length>0&&Le(Qe=>[...Qe,...$e])},[]),Fn=i.useCallback(ie=>{Le($e=>{const Qe=$e[ie];return Qe?.previewUrl&&URL.revokeObjectURL(Qe.previewUrl),$e.filter((Ft,cn)=>cn!==ie)})},[]),as=i.useCallback(ie=>{On(ie.clipboardData?.files)},[On]),Wn=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth>Ls)return;const ie=Kt.current;!ie||ie.disabled||ie.focus({preventScroll:!0})},[]),Rs=i.useCallback(()=>{typeof window>"u"||window.innerWidth>Ls||(Ne.current=!0)},[]),In=i.useCallback(async()=>{const ie=k.trim(),$e=dn.current;if(!(!ie&&$e.length===0)&&!ot){if(X(""),B(!1),xe(""),Ve(-1),ie==="/help"){ce(!0),Wn(),Ne.current=!1;return}if(ie==="/clear"||ie==="/new"){ve(),Ke(),$e.forEach(Qe=>{Qe.previewUrl&&URL.revokeObjectURL(Qe.previewUrl)}),Le(Qe=>Qe.filter(Ft=>!$e.includes(Ft)));try{if(S==="model"){const Qe=fo(At);if(!Qe)return;await Lt(yr,Qe.modelProvider,Qe.modelId)}else C&&await Lt(C)}catch{n("Failed to clear conversation","error")}finally{Wn(),Ne.current=!1}return}try{ce(!1),await Zt(ie,$e.map(Qe=>Qe.file)),$e.forEach(Qe=>{Qe.previewUrl&&URL.revokeObjectURL(Qe.previewUrl)}),Le(Qe=>Qe.filter(Ft=>!$e.includes(Ft)))}catch{}finally{Wn(),Ne.current=!1}}},[n,S,Ke,Wn,ot,k,At,C,Zt,Lt,ve]),rs=i.useCallback(ie=>{ie.preventDefault(),gt.current+=1,Ue(!0)},[]),Ns=i.useCallback(ie=>{ie.preventDefault(),ie.dataTransfer.dropEffect="copy",Ue(!0)},[]),ys=i.useCallback(ie=>{ie.preventDefault(),gt.current=Math.max(0,gt.current-1),gt.current===0&&Ue(!1)},[]),cs=i.useCallback(ie=>{ie.preventDefault(),gt.current=0,Ue(!1),On(ie.dataTransfer?.files)},[On]),ss=i.useCallback((ie,$e)=>{const Qe=PF(ie,$e);if(Qe){B(!0),xe(Qe.filter),Ve(Qe.start);return}B(!1),xe(""),Ve(-1)},[]),te=i.useCallback(ie=>{X($e=>{const Qe=jg($e);if(!Qe)return $e;const Ft=`/skill:${ie.name} `,cn=$e.slice(0,Qe.start)+Ft+$e.slice(Qe.end);return window.requestAnimationFrame(()=>{Kt.current&&Kt.current.focus()}),cn}),ne(!1),Z(""),q(0)},[]),we=i.useCallback(ie=>{const $e=Kt.current;if(!$e||ae<0)return;const Qe=$e.selectionStart??me.current,Ft=$e.selectionEnd??Qe,cn=Math.max(Qe,Ft),pn=Math.min(ae,cn),Un=`${`@${ie.name.replace(/\s+/g,"_")}`} `,gs=k.slice(0,pn)+Un+k.slice(cn),bs=pn+Un.length;X(gs),B(!1),xe(""),ze(0),Ve(-1),window.requestAnimationFrame(()=>{Kt.current&&(Kt.current.focus(),Kt.current.setSelectionRange(bs,bs))})},[ae,k]),P=i.useCallback(ie=>{const $e=ie.target.value,Qe=ie.target.selectionStart??$e.length;me.current=Qe,X($e),Be&&$e.trim().length>0&&ce(!1),ss($e,Qe);const Ft=jg($e);Ft?(ne(!0),Z(Ft.filter)):(ne(!1),Z("")),tt.detectMention($e,Qe),Ee(tt.mentionActive),tt.mentionActive&&xt(ie.target)},[Be,ss,tt,xt]),Ce=i.useCallback(()=>{if(Ne.current){window.requestAnimationFrame(()=>{Wn()});return}typeof window<"u"&&window.innerWidth<=Ls&&bt.current&&(Y.current=!0,bt.current.style.removeProperty("--vv-height"),bt.current.style.removeProperty("--vv-offset-top"),window.setTimeout(()=>{Y.current=!1},450)),Ze.current!==null&&window.clearTimeout(Ze.current),Ze.current=window.setTimeout(()=>{B(!1),xe(""),Ve(-1),Ee(!1),tt.dismissMention(),Ze.current=null},120),be.current!==null&&window.clearTimeout(be.current),be.current=window.setTimeout(()=>{ne(!1),be.current=null},120)},[tt,Wn]),qe=i.useCallback(()=>{Y.current=!1,Ze.current!==null&&(window.clearTimeout(Ze.current),Ze.current=null),be.current!==null&&(window.clearTimeout(be.current),be.current=null)},[]),et=i.useCallback(ie=>{const $e=ie.currentTarget,Qe=$e.selectionStart??$e.value.length;me.current=Qe,ss($e.value,Qe),tt.detectMention($e.value,Qe),Ee(tt.mentionActive),tt.mentionActive&&xt($e)},[ss,tt,xt]),mt=i.useCallback(ie=>{ie.key!=="Escape"&&et(ie)},[et]),Nt=i.useCallback(ie=>{rt($e=>{const Qe=new Set($e);return Qe.has(ie)?Qe.delete(ie):Qe.add(ie),Qe})},[]),Pt=i.useCallback((ie,$e=!1)=>$e?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:ie}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(xi,{remarkPlugins:[vi],components:Xv,children:ie})}),[]),an=i.useCallback(ie=>{if(me.current=ie.currentTarget.selectionStart??me.current,tt.mentionActive&&tt.files.length>0){if(tt.handleKeyDown(ie,k),ie.key==="Enter"||ie.key==="Tab"){const $e=tt.files[tt.selectedIndex];if($e){const Qe=tt.selectFile($e,k);X(Qe),tt.dismissMention(),Ee(!1)}}return}if(he&&ie.key==="ArrowDown"){ie.preventDefault(),Xt.length>0&&ze($e=>($e+1)%Xt.length);return}if(he&&ie.key==="ArrowUp"){ie.preventDefault(),Xt.length>0&&ze($e=>$e===0?Xt.length-1:$e-1);return}if(he&&ie.key==="Enter"){ie.preventDefault();const $e=Xt[pe]??Xt[0];$e&&we($e);return}if(he&&ie.key==="Escape"){ie.preventDefault(),ie.stopPropagation(),B(!1),xe(""),Ve(-1);return}if(je&&Mt.length>0&&ie.key==="ArrowDown"){ie.preventDefault(),q($e=>($e+1)%Mt.length);return}if(je&&Mt.length>0&&ie.key==="ArrowUp"){ie.preventDefault(),q($e=>$e===0?Mt.length-1:$e-1);return}if(je&&(ie.key==="Enter"||ie.key==="Tab")){ie.preventDefault();const $e=Mt[re]??Mt[0];$e&&te($e);return}if(je&&ie.key==="Escape"){ie.preventDefault(),ne(!1),Z("");return}ie.key!=="Enter"||ie.shiftKey||(ie.preventDefault(),In())},[he,Xt,pe,we,In,tt,k,je,Mt,re,te]),Cn=i.useCallback(()=>{if(Me.current){Me.current=!1;return}if(g){w(!1);return}typeof window<"u"&&window.innerWidth<=Ls&&W.current?.focus({preventScroll:!0}),w(!0)},[g,w]);return t.jsxs(t.Fragment,{children:[t.jsx("input",{ref:W,type:"text",className:"quick-chat-stealth-input","aria-hidden":"true",tabIndex:-1}),s&&t.jsx("button",{ref:Ot,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":Ie?"true":"false",style:{right:$t.x,bottom:$t.y},onPointerDown:ge,onClick:Cn,children:t.jsx(Zi,{size:24})}),g&&t.jsxs("div",{className:`quick-chat-panel${y&&v?" quick-chat-panel--keyboard-open":""}`,ref:bt,"data-testid":"quick-chat-panel",style:{...Ut?{right:$t.x+pt.right,bottom:st+pt.bottom,width:yt.width,height:yt.height}:{}},children:[Ut&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:vt,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:vt,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:vt,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:vt,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:vt,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:vt,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:vt,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:vt,role:"separator","aria-label":"Resize panel from bottom-right corner"})]}),t.jsxs("div",{className:"quick-chat-panel-header",children:[t.jsxs("div",{className:"quick-chat-panel-title-wrap",children:[t.jsx("h3",{children:"Quick Chat"}),S==="model"&&Dn&&(()=>{const ie=vn?.provider??Zn?.modelProvider??"";return b==="mobile"&&Dn.length>12&&ie?t.jsx("span",{className:"quick-chat-model-tag quick-chat-model-tag--icon","data-testid":"quick-chat-model-tag",title:Dn,"aria-label":Dn,children:t.jsx(zn,{provider:ie,size:"sm"})}):t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:Dn,children:Dn})})()]}),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:G,disabled:Qt,children:t.jsx($n,{size:16})}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":"Close quick chat","data-testid":"quick-chat-close",onClick:()=>w(!1),children:t.jsx(mn,{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:Dt?.id??"",onChange:ie=>As(ie.target.value),"data-testid":"quick-chat-session-dropdown",children:[t.jsx("option",{value:"",disabled:!0,children:Qt?"Loading sessions…":"Select a session"}),$s.map(ie=>t.jsx("option",{value:ie.id,children:ie.label},ie.id))]})]}),N&&t.jsxs("div",{className:"quick-chat-new-session-chooser","data-testid":"quick-chat-new-session-chooser",children:[t.jsxs("div",{className:"quick-chat-inline-mode-toggle","data-testid":"quick-chat-inline-mode-toggle",children:[t.jsx("button",{type:"button",className:`quick-chat-mode-btn${F==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-model",onClick:()=>E("model"),children:"Model"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${F==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-agent",onClick:()=>E("agent"),children:"Agent"})]}),F==="agent"?t.jsxs("div",{className:"quick-chat-panel-agent-select",children:[t.jsx("label",{htmlFor:"quick-chat-new-agent-select",className:"visually-hidden",children:"Select agent for new chat"}),t.jsx("select",{id:"quick-chat-new-agent-select",value:_,onChange:ie=>K(ie.target.value),"data-testid":"quick-chat-new-agent-select",children:m.map(ie=>t.jsx("option",{value:ie.id,children:AF(ie)},ie.id))})]}):t.jsx("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-new-model-select",children:t.jsx(_s,{id:"quick-chat-new-model-select",models:T,value:U,onChange:A,label:"Select model override",placeholder:Q?"Loading models…":"Select a model",disabled:Q||T.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:()=>{R(!1),E("model")},children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary","data-testid":"quick-chat-new-session-submit",onClick:()=>void bn(),disabled:Qt||(F==="agent"?!_:!fo(U||O||D)),children:"Create"})]})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:en,"data-testid":"quick-chat-messages",onScroll:Pn,children:Qt?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):on?t.jsxs(t.Fragment,{children:[nn.map(ie=>t.jsx(Ng,{message:ie,forcePlain:ie.role!=="user"&&Te.has(ie.id),mentionAgentsByName:_n,roomContext:u,onToggleRender:Nt},ie.id)),Be&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:Pt("Available commands:\n- `/new` or `/clear` — Clear conversation and start fresh\n- `/skill:{name}` — Use a specific skill\n- `/help` — Show this help")}),t.jsxs("div",{className:"quick-chat-panel-message quick-chat-panel-message--received quick-chat-panel-message--streaming","data-testid":"quick-chat-streaming-message",children:[sn?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:Pt(sn,Te.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${Te.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":Te.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>Nt("__streaming__"),children:Te.has("__streaming__")?t.jsx(zu,{size:14}):t.jsx(Fr,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:ln?"Thinking…":"Connecting…"}),Qv(xn,!0),ln&&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:ln})]})]})]}):hn?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):nn.length===0&&!sn&&!ln&&!on&&!Be?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[nn.map(ie=>t.jsx(Ng,{message:ie,forcePlain:ie.role!=="user"&&Te.has(ie.id),mentionAgentsByName:_n,roomContext:u,onToggleRender:Nt},ie.id)),Be&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:Pt("Available commands:\n- `/new` or `/clear` — Clear conversation and start fresh\n- `/skill:{name}` — Use a specific skill\n- `/help` — Show this help")})]})}),ue&&t.jsxs("button",{type:"button",className:"btn btn-sm quick-chat-jump-to-latest","data-testid":"quick-chat-jump-to-latest",onClick:Vn,children:[t.jsx(gn,{size:14}),"Latest"]}),Re.length>0&&t.jsx("div",{className:"quick-chat-attachment-previews","data-testid":"quick-chat-attachment-previews",children:Re.map((ie,$e)=>t.jsxs("div",{className:"quick-chat-attachment-preview","data-testid":`quick-chat-attachment-preview-${$e}`,children:[ie.previewUrl?t.jsx("img",{src:ie.previewUrl,alt:ie.file.name}):t.jsx("span",{className:"quick-chat-attachment-preview-name",children:ie.file.name}),t.jsx("button",{type:"button",className:"quick-chat-attachment-remove","data-testid":`quick-chat-attachment-remove-${$e}`,"aria-label":`Remove ${ie.file.name}`,onClick:()=>Fn($e),children:"×"})]},`${ie.file.name}-${$e}`))}),t.jsx("div",{className:"quick-chat-panel-input",children:t.jsxs("div",{className:`quick-chat-input-wrapper${ct?" quick-chat-input-wrapper--dragover":""}`,onDragEnter:rs,onDragOver:Ns,onDragLeave:ys,onDrop:cs,children:[t.jsx("input",{ref:Sn,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:ie=>{On(ie.target.files),ie.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:()=>Sn.current?.click(),children:t.jsx(ab,{size:16})}),t.jsx("input",{ref:Kt,type:"text",value:k,onChange:P,onKeyDown:an,onKeyUp:mt,onClick:et,onBlur:Ce,onFocus:qe,onPaste:as,onTouchStart:ie=>{typeof window>"u"||window.innerWidth>Ls||document.activeElement!==ie.currentTarget&&(ie.preventDefault(),ie.currentTarget.focus({preventScroll:!0}))},placeholder:vs,disabled:ot,"data-testid":"quick-chat-input"}),on?t.jsx("button",{type:"button",className:"chat-input-stop quick-chat-send-btn",onPointerDown:ie=>{typeof window>"u"||window.innerWidth>Ls||(ie.preventDefault(),ie.pointerType&&ie.pointerType!=="mouse"&&(tn.current=!0,ve()))},onTouchStart:ie=>{typeof window>"u"||window.innerWidth>Ls||(ie.preventDefault(),tn.current=!0,ve())},onMouseDown:ie=>{typeof window>"u"||window.innerWidth>Ls||ie.preventDefault()},onClick:()=>{if(tn.current){tn.current=!1;return}ve()},"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx($i,{size:14})}):t.jsx("button",{type:"button",className:"quick-chat-send-btn",onPointerDown:ie=>{typeof window>"u"||window.innerWidth>Ls||(ie.preventDefault(),ie.pointerType&&ie.pointerType!=="mouse"&&(tn.current=!0,Rs(),Wn(),In()))},onTouchStart:ie=>{typeof window>"u"||window.innerWidth>Ls||(ie.preventDefault(),tn.current=!0,Rs(),Wn(),In())},onMouseDown:ie=>{typeof window>"u"||window.innerWidth>Ls||ie.preventDefault()},onClick:()=>{if(tn.current){tn.current=!1;return}In()},disabled:ot||k.trim().length===0&&Re.length===0,"data-testid":"quick-chat-send",children:t.jsx(Da,{size:16})})]}),t.jsx(vF,{agents:m,filter:L,highlightedIndex:pe,visible:he,onSelect:we,position:"above",roomMemberIds:u?.memberIds,roomName:u?.roomName}),t.jsx(EF,{visible:tt.mentionActive&&!he,position:ft,files:tt.files,selectedIndex:tt.selectedIndex,onSelect:ie=>{const $e=tt.selectFile(ie,k);X($e),tt.dismissMention(),Ee(!1),Kt.current?.focus()},loading:tt.loading}),je&&t.jsx("div",{className:"chat-skill-menu","data-testid":"quick-chat-skill-menu",role:"listbox","aria-label":"Skill suggestions",children:He?t.jsx("div",{className:"chat-skill-menu-empty",children:"Loading skills…"}):Mt.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:fe?"No skills found":"No skills available"}):Mt.map((ie,$e)=>t.jsxs("button",{type:"button",role:"option","aria-selected":$e===re,className:`chat-skill-menu-item${$e===re?" chat-skill-menu-item--highlighted":""}`,onMouseDown:Qe=>Qe.preventDefault(),onMouseEnter:()=>q($e),onClick:()=>te(ie),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:ie.name}),t.jsx("span",{className:"chat-skill-menu-item-description",title:ie.relativePath,children:ie.relativePath})]},ie.id))}),Pe&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${Ht}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:Ke,children:"×"})]})]})})]})]})}function go(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Sg(e){return e.status==="generating"||e.status==="awaiting_input"}function bo(e){return e==="complete"||e==="error"}function UF(e){const[n,s]=i.useState([]),a=i.useRef(new Map),r=i.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:d}=Wr(),u=i.useCallback(()=>{Wu(e).then(p=>{const g=p.filter(v=>{const b=go(v.updatedAt),y=r.current.get(v.id);return y===void 0?!0:b<=y?!1:(r.current.delete(v.id),!0)}),w=new Map;for(const v of g)w.set(v.id,go(v.updatedAt));a.current=w,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 w=new Map(p.map(v=>[v.id,v]));for(const v of o.values()){if(e&&v.projectId&&v.projectId!==e)continue;const b=v.lastEventTimestamp,y=a.current.get(v.sessionId)??0;if(b<y)continue;const S=r.current.get(v.sessionId);if(S!==void 0&&b<=S)continue;if(S!==void 0&&b>S&&!bo(v.status)&&r.current.delete(v.sessionId),bo(v.status)){w.delete(v.sessionId)&&(g=!0),a.current.set(v.sessionId,b);continue}const j=w.get(v.sessionId),C=v.type??j?.type,x=v.title??j?.title;if(!j&&(!C||!x))continue;const N={id:v.sessionId,type:C??"planning",status:v.status,title:x??"AI Session",projectId:v.projectId??j?.projectId??e??null,lockedByTab:v.owningTabId??j?.lockedByTab??null,updatedAt:v.updatedAt??j?.updatedAt??new Date(b).toISOString()},R=w.get(v.sessionId);(!R||R.status!==N.status||R.title!==N.title||R.type!==N.type||R.projectId!==N.projectId||R.lockedByTab!==N.lockedByTab||R.updatedAt!==N.updatedAt)&&(w.set(v.sessionId,N),a.current.set(v.sessionId,b),g=!0)}return g?[...w.values()].sort((v,b)=>go(b.updatedAt)-go(v.updatedAt)):p})},[e,o]),i.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",g=v=>{try{const b=JSON.parse(v.data),y=go(b.updatedAt)||Date.now();s(S=>{const j=a.current.get(b.id)??0;if(y<j)return S;const C=r.current.get(b.id);if(C!==void 0&&y<=C)return S;if(C!==void 0&&y>C&&!bo(b.status)&&r.current.delete(b.id),a.current.set(b.id,y),bo(b.status))return S.filter(N=>N.id!==b.id);const x=S.findIndex(N=>N.id===b.id);if(x>=0){const N=[...S];return N[x]=b,N}return Sg(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}),bo(b.status)&&c({sessionId:b.id,status:b.status,timestamp:y})}catch{}},w=v=>{try{const b=JSON.parse(v.data),y=Date.now();r.current.set(b,y),a.current.set(b,Math.max(a.current.get(b)??0,y)),c({sessionId:b,status:"complete",timestamp:y}),s(S=>S.filter(j=>j.id!==b))}catch{}};return yi(`/api/events${p}`,{events:{"ai_session:updated":g,"ai_session:deleted":w},onReconnect:()=>{u()}})},[c,l,e,u]);const m=i.useCallback(async p=>{const w=n.find(S=>S.id===p)?.type,v=Ja();let b=!1;if(w==="planning")try{await pb(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of planning session ${p} despite lock by another tab`)}else if(w==="subtask")try{await bb(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of subtask session ${p} despite lock by another tab`)}else if(w==="mission_interview")try{await kb(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of mission interview session ${p} despite lock by another tab`)}b&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${p}, attempting delete anyway`);const 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 jb(p)}catch{}s(S=>S.filter(j=>j.id!==p))},[c,e,n]),h=i.useMemo(()=>n.filter(p=>Sg(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 mc="fusion:hide-session-banners",Lu="fusion:session-banner-pref-changed";function HF(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(mc)==="1"}catch{return!1}}function qF(e){if(typeof window>"u")return()=>{};const n=a=>{a.key===mc&&e()},s=()=>e();return window.addEventListener("storage",n),window.addEventListener(Lu,s),()=>{window.removeEventListener("storage",n),window.removeEventListener(Lu,s)}}function D8(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(mc,"1"):window.localStorage.removeItem(mc),window.dispatchEvent(new Event(Lu))}catch{}}function VF(){return i.useSyncExternalStore(qF,HF,()=>!1)}function Ss(e){return{...e,column:Db(e.column),dependencies:Array.isArray(e.dependencies)?e.dependencies:[],steps:Array.isArray(e.steps)?e.steps:[],log:Array.isArray(e.log)?e.log:[]}}function Cg(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function WF(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 Yd(e,n){if(Cg(n.updatedAt,e.updatedAt)<0)return e;if(e.column===n.column)return WF(e,n);const a=Cg(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 GF(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),w=i.useRef(0),v=i.useRef(n);u.current=r,f.current=s,v.current!==n&&(v.current=n,w.current++);const b=1e3,y=i.useCallback(async se=>{const O=++m.current,M=n,D=se?.searchQueryOverride??f.current,$=se?.includeArchivedOverride??d.current;try{const k=await Oj(void 0,void 0,M,D,$);if(m.current!==O||n!==M)return;o(k.map(Ss)),g.current=Date.now()}catch{if(m.current!==O||n!==M)return;if(se?.clearOnError){o([]);return}o(k=>k)}},[n]);p.current=y;const S=i.useCallback(async()=>{d.current||(c(!0),d.current=!0,await p.current({includeArchivedOverride:!0}))},[]),j=i.useRef(s);i.useEffect(()=>{if(s===void 0&&j.current===void 0)return;j.current=s;const se=setTimeout(()=>{y({searchQueryOverride:s})},300);return()=>clearTimeout(se)},[s]),i.useEffect(()=>{y({clearOnError:!0});const se=()=>{if(document.visibilityState!=="visible")return;const O=Date.now();O-h.current<b||(h.current=O,y())};return document.addEventListener("visibilitychange",se),()=>{document.removeEventListener("visibilitychange",se)}},[y]),i.useEffect(()=>{if(a===!1)return;const se=w.current,O=n?`?projectId=${encodeURIComponent(n)}`:"",M=()=>w.current!==se;let D=!0;const $=ye=>{if(M())return;const je=Ss(JSON.parse(ye.data));if(f.current){p.current({searchQueryOverride:f.current});return}o(ne=>{const fe=ne.findIndex(L=>L.id===je.id);if(fe===-1)return[...ne,je];const Z=ne[fe],re=Yd(Z,je);if(re===Z)return ne;const q=[...ne];return q[fe]=re,q}),g.current=Date.now()},k=ye=>{if(M())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:je,to:ne}=JSON.parse(ye.data),fe=Ss(je),Z={...fe,column:Db(ne,fe.column)};o(re=>{const q=re.findIndex(xe=>xe.id===Z.id);if(q===-1)return[...re,Z];const L=[...re];return L[q]=Z,L}),g.current=Date.now()},X=ye=>{if(M())return;if(f.current){p.current({searchQueryOverride:f.current});return}const je=Ss(JSON.parse(ye.data));o(ne=>{const fe=ne.findIndex(L=>L.id===je.id);if(fe===-1)return[...ne,je];const Z=ne[fe],re=Yd(Z,je);if(re===Z)return ne;const q=[...ne];return q[fe]=re,q}),g.current=Date.now()},le=ye=>{if(M())return;if(f.current){p.current({searchQueryOverride:f.current});return}const je=Ss(JSON.parse(ye.data));o(ne=>ne.filter(fe=>fe.id!==je.id))},ke=ye=>{if(M())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:je}=JSON.parse(ye.data),fe={...Ss(je),column:"done"};o(Z=>{const re=Z.findIndex(L=>L.id===fe.id);if(re===-1)return[...Z,fe];const q=[...Z];return q[re]=fe,q})},He=yi(`/api/events${O}`,{events:{"task:created":$,"task:moved":k,"task:updated":X,"task:deleted":le,"task:merged":ke},onReconnect:()=>{D&&(M()||p.current())}});return()=>{D=!1,He()}},[n,a]);const C=i.useCallback(async se=>{const O=Ss(await db(se,n));return o(M=>M.some(D=>D.id===O.id)?M:[...M,O]),O},[n]),x=i.useCallback(async(se,O,M)=>Ss(await zj(se,O,n,M)),[n]),N=i.useCallback(async se=>Ss(await ub(se,n)),[n]),R=i.useCallback(async(se,O)=>Ss(await Bj(se,n,O)),[n]),F=i.useCallback(async se=>Uj(se,n),[n]),E=i.useCallback(async se=>Ss(await Hj(se,n)),[n]),_=i.useCallback(async se=>Ss(await qj(se,n)),[n]),K=i.useCallback(async se=>{const O=Ss(await Vj(se,n));return o(M=>M.some(D=>D.id===O.id)?M:[...M,O]),O},[n]),U=i.useCallback(async(se,O)=>{const M=u.current.find($=>$.id===se),D=M?{...M,...O,updatedAt:new Date().toISOString()}:void 0;D&&o($=>$.map(k=>k.id===se?D:k));try{const $=Ss(await Us(se,O,n));return o(k=>k.map(X=>X.id===se?$:X)),$}catch($){throw M&&o(k=>k.map(X=>X.id===se?M:X)),$}},[n]),A=i.useCallback(async se=>{const O=Ss(await Gj(se,n));return o(M=>M.map(D=>D.id===se?O:D)),O},[n]),T=i.useCallback(async se=>{const O=Ss(await Kj(se,n));return o(M=>M.map(D=>D.id===se?O:D)),O},[n]),H=i.useCallback(async()=>{const O=(await Jj(n)).map(Ss);return o(M=>M.map(D=>O.find(k=>k.id===D.id)||D)),O},[n]),Q=i.useCallback(se=>{if(se.length===0)return;if(f.current){p.current({searchQueryOverride:f.current});return}const O=se.map(Ss);o(M=>{let D=M;for(const $ of O){const k=D.findIndex(ke=>ke.id===$.id);if(k===-1){D===M&&(D=[...M]),D.push($);continue}const X=D[k],le=Yd(X,$);le!==X&&(D===M&&(D=[...M]),D[k]=le)}return D}),g.current=Date.now()},[]);return{tasks:r,createTask:C,moveTask:x,pauseTask:N,deleteTask:R,mergeTask:F,retryTask:E,resetTask:_,duplicateTask:K,updateTask:U,archiveTask:A,unarchiveTask:T,archiveAllDone:H,loadArchivedTasks:S,includeArchived:l,ingestCreatedTasks:Q,lastFetchTimeMs:g.current}}const KF=5e3,JF=1e3;function YF(e){const s=(d1(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 Eg(e){return e.map(n=>({...n,nodeMappings:YF(n)}))}function QF(){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 ih();n(Eg(f))}catch(f){o(f instanceof Error?f.message:"Failed to fetch projects")}},[]);i.useEffect(()=>{let f=!1;async function p(){a(!0);const w=performance.now();try{const v=await ih(),b=Eg(v),y=Math.round(performance.now()-w);console.log(`[useProjects] initial fetchProjectsAcrossNodes took ${y}ms (${b.length} projects)`),f||(n(b),o(null))}catch(v){const b=Math.round(performance.now()-w);console.warn(`[useProjects] initial fetch failed after ${b}ms: ${v instanceof Error?v.message:String(v)}`),f||o(v instanceof Error?v.message:"Failed to fetch projects")}finally{f||a(!1)}}p();const g=()=>{if(document.visibilityState!=="visible")return;const w=Date.now();w-c.current<JF||(c.current=w,d())};return document.addEventListener("visibilitychange",g),()=>{f=!0,document.removeEventListener("visibilitychange",g)}},[d]),i.useEffect(()=>{if(!s)return l.current=setInterval(()=>{d()},KF),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,d]);const u=i.useCallback(async f=>{const p=await x1(f);return n(g=>[...g,p]),p},[]),m=i.useCallback(async(f,p)=>{const g=await S1(f,p);return n(w=>w.map(v=>v.id===f?g:v)),g},[]),h=i.useCallback(async f=>{await vb(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 XF="kb-dashboard-current-project";function ZF(e){return e??"local"}function ez(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=ZF(s);i.useEffect(()=>{let p=!1;async function g(){try{const w=await na();if(p)return;u.current=w.dashboardCurrentProjectIdByNode??{};const v=u.current[m];if(v){const b=e.find(y=>y.id===v);b&&(r(b),c.current=!0)}if(!v)try{const b=localStorage.getItem(XF);if(b){const y=JSON.parse(b);y?.id&&e.some(j=>j.id===y.id)&&(r(y),c.current=!0,u.current={...u.current,[m]:y.id},await Bn({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(w=>w.id===a.id)&&e.length>0){const w=e.find(v=>v.status==="active");r(w||e[0]||null);return}const g={...u.current,[m]:a.id};u.current=g,Bn({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,Bn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}},[m]),f=i.useCallback(()=>{d.current=!0,r(null);const p={...u.current};delete p[m],u.current=p,Bn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:a,setCurrentProject:h,clearCurrentProject:f,loading:o}}const Zv=i.createContext(null);function tz({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()},[]),ga.createElement(Zv.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function nz(){const e=i.useContext(Zv);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const ey="kb-dashboard-theme-mode",ty="kb-dashboard-color-theme",ny="kb-dashboard-font-scale-pct",Ou=100,sz=85,iz=125,sy=[...BC],Fu="theme-data",xo="theme-data.css";function az(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.startsWith("http://")||e.startsWith("https://")?new URL(`/${xo}`,e).toString():e.startsWith("file://")?e.endsWith("/")?e.slice(0,-1)+`/${xo}`:e.replace(/\/[^/]+$/,`/${xo}`):`/${xo}`:`/${xo}`}const Qs=typeof window<"u",rz=Qs?i.useLayoutEffect:i.useEffect;function iy(e){return e==="dark"||e==="light"||e==="system"}function _g(){if(!Qs)return"dark";try{const e=localStorage.getItem(ey);if(iy(e))return e}catch{}return"dark"}function Mg(){if(!Qs)return"default";try{const e=localStorage.getItem(ty);if(e&&sy.includes(e))return e}catch{}return"default"}function Ag(e){if(Qs)try{localStorage.setItem(ey,e)}catch{}}function Rg(e){if(Qs)try{localStorage.setItem(ty,e)}catch{}}function Fo(e){return typeof e!="number"||!Number.isFinite(e)?Ou:Math.min(iz,Math.max(sz,Math.round(e)))}function Ig(){if(!Qs)return Ou;try{const e=Number(localStorage.getItem(ny));return Fo(e)}catch{return Ou}}function Tg(e){if(Qs)try{localStorage.setItem(ny,String(Fo(e)))}catch{}}function oz(e,n){return e==="system"?n?"dark":"light":e}function lz(e,n,s,a){if(!Qs)return;const r=oz(e,a);document.documentElement.setAttribute("data-theme",r),document.documentElement.setAttribute("data-color-theme",n),document.documentElement.style.fontSize=`${Fo(s)}%`}function Pg(){if(!Qs)return;const e=az(),n=document.getElementById(Fu);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=Fu,document.head.appendChild(s)}function $g(){if(!Qs)return;const e=document.getElementById(Fu);e&&e.remove()}function cz(){const[e,n]=i.useState(()=>_g()),[s,a]=i.useState(()=>Mg()),[r,o]=i.useState(()=>Ig()),[l,c]=i.useState(!0),[d,u]=i.useState(()=>Qs?window.matchMedia("(prefers-color-scheme: dark)").matches:!0),m=i.useRef(e),h=i.useRef(s),f=i.useRef(r),p=i.useRef(!1),g=i.useRef(!1),w=i.useRef(!1);i.useEffect(()=>{m.current=e},[e]),i.useEffect(()=>{h.current=s},[s]),i.useEffect(()=>{f.current=r},[r]),i.useEffect(()=>{if(!Qs||!l)return;let S=!1;return na().then(j=>{if(!S&&(iy(j.themeMode)&&!p.current&&(m.current!==j.themeMode&&(m.current=j.themeMode,n(j.themeMode)),_g()!==j.themeMode&&Ag(j.themeMode)),j.colorTheme&&sy.includes(j.colorTheme)&&!g.current&&(h.current!==j.colorTheme&&(h.current=j.colorTheme,a(j.colorTheme)),Mg()!==j.colorTheme&&Rg(j.colorTheme)),!w.current)){const C=Fo(j.dashboardFontScalePct);f.current!==C&&(f.current=C,o(C)),Ig()!==C&&Tg(C)}}).catch(j=>{console.warn("[useTheme] Failed to hydrate theme from global settings",j)}).finally(()=>{S||c(!1)}),()=>{S=!0}},[l]),i.useEffect(()=>{if(!Qs)return;const S=window.matchMedia("(prefers-color-scheme: dark)"),j=C=>{u(C.matches)};return S.addEventListener("change",j),()=>S.removeEventListener("change",j)},[]),rz(()=>{lz(e,s,r,d)},[e,s,r,d]),i.useEffect(()=>{!Qs||l||(s!=="default"?Pg():$g())},[s,l]);const v=i.useCallback(S=>{p.current=!0,m.current=S,n(S),Ag(S),Bn({themeMode:S}).catch(j=>{console.warn("[useTheme] Failed to persist themeMode to global settings",j)})},[]),b=i.useCallback(S=>{g.current=!0,h.current=S,a(S),Rg(S),S!=="default"?Pg():$g(),Bn({colorTheme:S}).catch(j=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",j)})},[]),y=i.useCallback(S=>{const j=Fo(S);w.current=!0,f.current=j,o(j),Tg(j),Bn({dashboardFontScalePct:j}).catch(C=>{console.warn("[useTheme] Failed to persist dashboardFontScalePct to global settings",C)})},[]);return{themeMode:e,colorTheme:s,dashboardFontScalePct:r,setThemeMode:v,setColorTheme:b,setDashboardFontScalePct:y,isSystemDark:d}}function dz(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,w]=i.useState(void 0),[v,b]=i.useState(null),[y,S]=i.useState("definition"),[j,C]=i.useState(null),[x,N]=i.useState(!1),[R,F]=i.useState(void 0),[E,_]=i.useState(!1),[K,U]=i.useState(!1),[A,T]=i.useState(!1),[H,Q]=i.useState(null),[se,O]=i.useState(!1),[M,D]=i.useState(!1),[$,k]=i.useState(void 0),[X,le]=i.useState(!1),[ke,He]=i.useState(!1),[ye,je]=i.useState("project"),[ne,fe]=i.useState(null),[Z,re]=i.useState(!1),[q,L]=i.useState(!1),[xe,he]=i.useState(!1),[B,pe]=i.useState(!1),[ze,ae]=i.useState(!1),[Ve,Te]=i.useState(!1),[rt,Be]=i.useState(!1),ce=!!(v||x||s||r||m||M||X||ke||Z||q||xe||ze||B||A||se||E||K||Ve||rt),Re=i.useCallback(()=>a(!0),[]),Le=i.useCallback(()=>a(!1),[]),ct=i.useCallback(()=>o(!0),[]),Ue=i.useCallback(bt=>{c(bt),o(!0)},[]),ue=i.useCallback(()=>{const bt=n[0];bt&&(u(bt.id),o(!0))},[n]),oe=i.useCallback(bt=>{u(bt),o(!0)},[]),Ee=i.useCallback(()=>{o(!1),c(null),u(void 0)},[]),ft=i.useCallback(bt=>{p(bt),h(!0)},[]),ht=i.useCallback(bt=>{w(bt),h(!0)},[]),tt=i.useCallback(()=>{h(!1),p(null),w(void 0)},[]),xt=i.useCallback((bt,Ot="definition",en)=>{b(bt),S(Ot),C(en?.origin??null)},[]),Me=i.useCallback(bt=>{b(bt),S("changes"),C(null)},[]),Ye=i.useCallback(bt=>{b(Ot=>Ot&&{...Ot,...bt})},[]),dt=i.useCallback(()=>{b(null),C(null)},[]),wt=i.useCallback(bt=>{F(bt),N(!0)},[]),St=i.useCallback(()=>{N(!1),F(void 0)},[]),Fe=i.useCallback(()=>_(!0),[]),J=i.useCallback(()=>_(!1),[]),me=i.useCallback(()=>U(!0),[]),Ze=i.useCallback(()=>U(!1),[]),be=i.useCallback(bt=>{Q(bt??null),T(!0)},[]),gt=i.useCallback(()=>{T(!1),Q(null)},[]),$t=i.useCallback(()=>O(!0),[]),Ie=i.useCallback(()=>O(!1),[]),ge=i.useCallback(()=>{D(bt=>!bt)},[]),st=i.useCallback(()=>{D(!1),k(void 0)},[]),yt=i.useCallback((bt,Ot)=>{bt&&je(bt),fe(Ot??null),le(!0)},[]),pt=i.useCallback(()=>{le(!1),fe(null)},[]),vt=i.useCallback(()=>He(!0),[]),Ut=i.useCallback(()=>He(!1),[]),Dt=i.useCallback(bt=>{je(bt)},[]),nn=i.useCallback(()=>re(!0),[]),on=i.useCallback(()=>re(!1),[]),sn=i.useCallback(()=>L(!0),[]),ln=i.useCallback(()=>L(!1),[]),xn=i.useCallback(()=>he(!0),[]),qt=i.useCallback(()=>he(!1),[]),Qt=i.useCallback(()=>pe(!0),[]),hn=i.useCallback(()=>pe(!1),[]),Zt=i.useCallback(()=>ae(!0),[]),ve=i.useCallback(()=>ae(!1),[]),Pe=i.useCallback(async(bt,Ot)=>{ae(!1),k(Ot),D(!0)},[]),Ke=i.useCallback(()=>Te(!0),[]),at=i.useCallback(()=>Te(!1),[]),We=i.useCallback(()=>Be(!0),[]),It=i.useCallback(()=>Be(!1),[]),Lt=i.useCallback((bt,Ot)=>{Ot(`Created ${bt.id} from planning mode`,"success"),o(!1),c(null)},[]),Bt=i.useCallback((bt,Ot)=>{const en=bt.map(Kt=>Kt.id).join(", ");Ot(`Created ${en} from planning mode`,"success"),o(!1),c(null)},[]),Gt=i.useCallback((bt,Ot)=>{const en=bt.map(Kt=>Kt.id).join(", ");Ot(`Created ${en} from subtask breakdown`,"success"),h(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:l,planningResumeSessionId:d,isSubtaskOpen:m,subtaskInitialDescription:f,subtaskResumeSessionId:g,detailTask:v,detailTaskInitialTab:y,detailTaskOrigin:j,settingsOpen:x,settingsInitialSection:R,schedulesOpen:E,githubImportOpen:K,usageOpen:A,usageAnchorRect:H,systemStatsOpen:se,terminalOpen:M,terminalInitialCommand:$,filesOpen:X,todosOpen:ke,fileBrowserWorkspace:ye,fileBrowserInitialFile:ne,activityLogOpen:Z,gitManagerOpen:q,workflowStepsOpen:xe,agentsOpen:B,scriptsOpen:ze,setupWizardOpen:Ve,modelOnboardingOpen:rt,anyModalOpen:ce,openNewTask:Re,closeNewTask:Le,openPlanning:ct,openPlanningWithInitialPlan:Ue,resumePlanning:ue,openPlanningWithSession:oe,closePlanning:Ee,openSubtaskBreakdown:ft,openSubtaskWithSession:ht,closeSubtask:tt,openDetailTask:xt,openDetailWithChangesTab:Me,updateDetailTask:Ye,closeDetailTask:dt,openSettings:wt,closeSettings:St,openSchedules:Fe,closeSchedules:J,openGitHubImport:me,closeGitHubImport:Ze,openUsage:be,closeUsage:gt,openSystemStats:$t,closeSystemStats:Ie,toggleTerminal:ge,closeTerminal:st,openFiles:yt,closeFiles:pt,openTodos:vt,closeTodos:Ut,setFileWorkspace:Dt,openActivityLog:nn,closeActivityLog:on,openGitManager:sn,closeGitManager:ln,openWorkflowSteps:xn,closeWorkflowSteps:qt,openAgents:Qt,closeAgents:hn,openScripts:Zt,closeScripts:ve,runScript:Pe,openSetupWizard:Ke,closeSetupWizard:at,openModelOnboarding:We,closeModelOnboarding:It,onPlanningTaskCreated:Lt,onPlanningTasksCreated:Bt,onSubtaskTasksCreated:Gt}}function uz(e){const[n,s]=i.useState(2),[a,r]=i.useState("."),[o,l]=i.useState(!0),[c,d]=i.useState(!1),[u,m]=i.useState(!1),[h,f]=i.useState(void 0),[p,g]=i.useState(7200*1e3),[w,v]=i.useState(!1),[b,y]=i.useState(!1),[S,j]=i.useState(!1),[C,x]=i.useState({}),[N,R]=i.useState(!1),[F,E]=i.useState(!1),[_,K]=i.useState(!1),[U,A]=i.useState(!1),[T,H]=i.useState(!0),Q=i.useCallback(async()=>{const[k,X]=await Promise.allSettled([Xj(e),kc(e)]);if(k.status==="fulfilled"&&(s(k.value.maxConcurrent),r(k.value.rootDir)),X.status==="fulfilled"){const le=X.value;l(!!le.autoMerge),d(!!le.globalPause),m(!!le.enginePaused),y(!!le.prAuthAvailable),f(le.taskStuckTimeoutMs),g(le.staleHighFanoutBlockerAgeThresholdMs??7200*1e3),v(le.showQuickChatFAB===!0),x(le.experimentalFeatures??{});const ke=le.experimentalFeatures??{};R(ke.insights===!0),E(ke.memoryView===!0),K(ke.devServerView===!0||ke.devServer===!0),A(ke.todoView===!0);const He=le.autoReloadOnVersionChange!==!1;H(He),zc(He)}j(!0)},[e]);i.useEffect(()=>{j(!1),x({}),R(!1),E(!1),K(!1),A(!1),Q()},[Q]);const se=i.useCallback(async()=>{const k=!o;l(k);try{await sl({autoMerge:k},e)}catch{l(!k)}},[o,e]),O=i.useCallback(async()=>{const k=!c;d(k);try{await sl({globalPause:k,globalPauseReason:k?"manual":void 0},e)}catch{d(!k)}},[c,e]),M=i.useCallback(async()=>{const k=!u;m(k);try{await sl({enginePaused:k},e)}catch{m(!k)}},[u,e]),D=i.useCallback(async()=>{const k=!w;v(k);try{await sl({showQuickChatFAB:k},e)}catch{v(!k)}},[w,e]),$=i.useCallback(async()=>{const k=!T;H(k),zc(k);try{await Bn({autoReloadOnVersionChange:k})}catch{H(!k),zc(!k)}},[T]);return{maxConcurrent:n,rootDir:a,autoMerge:o,globalPaused:c,enginePaused:u,taskStuckTimeoutMs:h,staleHighFanoutBlockerAgeThresholdMs:p,showQuickChatFAB:w,prAuthAvailable:b,settingsLoaded:S,experimentalFeatures:C,insightsEnabled:N,memoryEnabled:F,devServerEnabled:_,todosEnabled:U,autoReloadOnVersionChange:T,toggleAutoMerge:se,toggleGlobalPause:O,toggleEnginePause:M,toggleShowQuickChatFAB:D,toggleAutoReloadOnVersionChange:$,refresh:Q}}function mz(e){const{projectId:n,projects:s,projectsLoading:a,currentProject:r,setCurrentProject:o,addToast:l,openTaskDetail:c,closeTaskDetail:d}=e,u=i.useRef(!1),m=i.useRef(!1),h=i.useRef(null);return i.useEffect(()=>{if(!m.current){const b=window.location.pathname.match(/^\/tasks\/([A-Z]+-\d+)\/?$/);if(b){const y=b[1];if(/^[A-Z]+-\d+$/.test(y)){const S=new URLSearchParams(window.location.search);S.set("task",y);const j=S.toString(),C=window.history.state??{};window.history.replaceState(C,"",j?`/?${j}`:"/"),m.current=!0}}}const p=new URLSearchParams(window.location.search),g=p.get("project"),w=p.get("task");if(!w||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,Ba(w,g??n).then(b=>{c(b),h.current=w}).catch(()=>{l(`Task ${w} 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(),w=window.history.state??{};window.history.replaceState(w,"",g?`${window.location.pathname}?${g}`:window.location.pathname),h.current=null}d()},[d])}}function hz(){const[e,n]=i.useState([]),[s,a]=i.useState([]),[r,o]=i.useState([]),l=i.useRef(s),c=i.useRef(r);i.useEffect(()=>{Ws().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 Bn({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 Bn({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 pz({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;Po().then(({providers:d})=>{const u=d.some(h=>h.authenticated);if(d.length>0&&!u||d.length>0&&u)return na().then(h=>{const f=!!(h.defaultProvider&&h.defaultModelId);(h.modelOnboardingComplete===!1||h.modelOnboardingComplete===void 0)&&(!u||!f)&&!Lr()?l=!0:!u&&!Lr()&&(c=!0)})}).then(()=>{if(o.current){r.current=!1;return}l?(pi("onboarding:auto-triggered",{trigger:"first-run"}),s()):c&&(pi("onboarding:auto-triggered",{trigger:"missing-provider"}),a("authentication"))}).catch(()=>{})},[e,n,s,a])}const Dg="kb-update-banner-dismissed";function fz(){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(Dg)==="true";u(h);let f=!1;return Zj().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(Dg,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:d,dismiss:m}}const gz=["board","list","graph","agents","missions","chat","documents","research","evals","skills","mailbox","insights","memory","devserver","dev-server","stash-recovery"];function bz(e){return e!==null&&gz.includes(e)}function Qd(e){return e!==null&&(bz(e)||wr(e))}const xz=Xo("fusion-plugin-roadmap","roadmaps");function Lg(e){return e==="devserver"?"dev-server":e}function Og(e){return e!=="roadmaps"?"board":Rb("fusion-plugin-roadmap","roadmaps")?xz:"board"}function vz(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=Gn("kb-dashboard-task-view");return b==="roadmaps"?Og(b):Qd(b)?b:"board"}),g=i.useRef(!1);i.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),i.useEffect(()=>{const b=Gn("kb-dashboard-task-view",r?.id);if(b==="roadmaps")p(Og(b));else if(Qd(b)){const y=!g.current&&b==="devserver";p(y?"devserver":Lg(b))}else p("board");r?.id&&(g.current=!0)},[r?.id]),i.useEffect(()=>{fs("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&&Qd(b)&&p(Lg(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 w=i.useCallback(b=>{p(b)},[]),v=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:w,handleToggleTheme:v}}const Xd=new Map,yz=6e4;function wz(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";Xd.delete(h),d(f=>f+1)},[e]);return i.useEffect(()=>{const h=e??"default";let f=!1;async function p(){const g=Xd.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 w=await U0(e);if(f)return;Xd.set(h,{views:w,expiresAt:Date.now()+yz}),s(w)}catch(w){if(f)return;l(w instanceof Error?w.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 kz({taskView:e,context:n}){return t.jsx(_C,{viewId:e,context:n})}let Fg=!1;function Or(e,n){return function(){return i.createElement("span",null,`Bundled plugin view unavailable: ${e}#${n}`)}}async function jz(){const e="@fusion-plugin-examples/dependency-graph/dashboard-view",n="DependencyGraphDashboardView",a=(await En(()=>import("./dashboard-view-C7Snlgow.js"),__vite__mapDeps([24,1,25,5,6,26])))[n];return a?{default:a}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Or(e,n)})}async function Nz(){const e="@fusion-plugin-examples/roadmap/dashboard-view",n="RoadmapDashboardView",a=(await En(()=>import("./dashboard-view-BWGH_fAq.js"),__vite__mapDeps([27,1,25,28])))[n];return a?{default:a}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Or(e,n)})}async function Sz(){const e="@fusion-plugin-examples/cli-printing-press/dashboard-view",n="CliPrintingPressWizardView";try{const a=(await import(e))[n];return a?{default:a}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Or(e,n)})}catch{return{default:Or(e,n)}}}async function Cz(){const e="@fusion-plugin-examples/cli-printing-press/manage-view",n="CliPrintingPressManageView";try{const a=(await import(e))[n];return a?{default:a}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Or(e,n)})}catch{return{default:Or(e,n)}}}function ay(){Fg||(Fg=!0,ll("fusion-plugin-dependency-graph","graph",i.lazy(jz)),ll("fusion-plugin-roadmap","roadmaps",i.lazy(Nz)),ll("fusion-plugin-cli-printing-press","wizard",i.lazy(Sz)),ll("fusion-plugin-cli-printing-press","manage",i.lazy(Cz)))}function Ez(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(R=>{n(R),a("project")},[n,a]),g=i.useCallback(()=>{s(),a("overview")},[s,a]),w=i.useCallback(()=>{u()},[u]),v=i.useCallback(()=>{m()},[m]),b=i.useCallback(R=>{h(),n(R),a("project"),d(`Project ${R.name} registered successfully`,"success"),o()},[h,n,a,d,o]),y=i.useCallback(()=>{f()},[f]),S=i.useCallback(async R=>{try{await j1(R.id),d(`Project ${R.name} paused`,"success"),await o()}catch{d(`Failed to pause project ${R.name}`,"error")}},[d,o]),j=i.useCallback(async R=>{try{await N1(R.id),d(`Project ${R.name} resumed`,"success"),await o()}catch{d(`Failed to resume project ${R.name}`,"error")}},[d,o]),C=i.useCallback(async R=>{try{await vb(R.id),d(`Project ${R.name} removed`,"success"),r?.id===R.id&&(s(),a("overview")),await o()}catch{d(`Failed to remove project ${R.name}`,"error")}},[r,s,a,d,o]),x=i.useCallback(async R=>{try{await l(R)}catch{d("Failed to update favorites","error")}},[l,d]),N=i.useCallback(async R=>{try{await c(R)}catch{d("Failed to update model favorites","error")}},[c,d]);return{handleSelectProject:p,handleViewAllProjects:g,handleOpenSettings:w,handleAddProject:v,handleSetupComplete:b,handleModelOnboardingComplete:y,handlePauseProject:S,handleResumeProject:j,handleRemoveProject:C,handleToggleFavorite:x,handleToggleModelFavorite:N}}function _z(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 Mz(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),w=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=[Q0(e),X0(e)];s&&(y.push(Z0(e,s,a)),y.push(eC(e,s)));const S=await Promise.allSettled(y);if(b.signal.aborted)return;const j=S[0],C=S[1];if(j.status==="rejected"){p(`Failed to fetch node health: ${j.reason}`),h(!1);return}if(u(j.value),C.status==="rejected"){p(`Failed to fetch projects: ${C.reason}`),h(!1);return}if(o(C.value),s&&S[2]){const x=S[2];if(x.status==="rejected"){p(`Failed to fetch tasks: ${x.reason}`),h(!1);return}x.status==="fulfilled"&&c(x.value)}h(!1)}catch(y){b.signal.aborted||(p(y instanceof Error?y.message:"Unknown error"),h(!1))}},[e,s,a]);i.useEffect(()=>(w(),()=>{g.current?.abort()}),[w]);const v=i.useCallback(()=>{w()},[w]);return{projects:r,tasks:l,health:d,loading:m,error:f,refresh:v}}function Az(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 yi(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 Rz="fusion-dashboard-current-node",ry=i.createContext(null);function Iz({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 na();if(m)return;l.current=f.dashboardCurrentNodeId;const p=f.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const g=localStorage.getItem(Rz);if(g){const w=JSON.parse(g);w?.id&&w?.type==="remote"&&(l.current=w.id,await Bn({dashboardCurrentNodeId:w.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,Bn({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,Bn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,a]);const c=i.useCallback(m=>{s(m)},[]),d=i.useCallback(()=>{s(null),l.current=void 0,Bn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),u={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:d};return t.jsx(ry.Provider,{value:u,children:e})}function Tz(){const e=i.useContext(ry);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}const Pz=["shellKind","shellMode","profileId","serverBaseUrl","serverLabel","shellCanOpenConnectionManager","hostKind","mode","connectionId","serverUrl","canOpenConnectionManager"],$z=["__FUSION_SHELL_HOST_CONTEXT__","__fusionShellHostContext","__FUSION_SHELL_CONTEXT__"];let hc=null,zg=!1;function Dz(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 Lz(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 oy(e){if(e==="browser"||e==="desktop-shell"||e==="mobile-shell")return e;if(e==="desktop")return"desktop-shell";if(e==="mobile")return"mobile-shell"}function Oz(e){return e==="local"||e==="remote"?e:void 0}function ly(e){const n=Oz(e.mode),s=typeof e.connectionId=="string"&&e.connectionId.trim()?e.connectionId:void 0,a=Lz(e.serverUrl),r=Dz(e.canOpenConnectionManager);return{kind:e.kind,...n?{mode:n}:{},...s?{connectionId:s}:{},...a?{serverUrl:a}:{},...r!==void 0?{canOpenConnectionManager:r}:{}}}function Fz(e){for(const n of $z){const s=e[n];if(!s||typeof s!="object")continue;const a=s,r=oy(a.kind??a.shellKind??a.hostKind);if(r)return r==="browser"?{kind:r}:ly({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 zz(e){let n;try{n=new URL(e.location.href)}catch{return null}const s=n.searchParams,a=oy(s.get("hostKind")??s.get("kind")??s.get("shellKind"));return a?a==="browser"?{kind:a}:ly({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 Bz(e){try{const n=new URL(e.location.href);let s=!1;for(const r of Pz)n.searchParams.has(r)&&(n.searchParams.delete(r),s=!0);if(!s)return;const a=n.pathname+(n.search?n.search:"")+n.hash;e.history.replaceState(e.history.state,"",a)}catch{}}function Uz(e=window){const n=Fz(e);if(n)return n;const s=zz(e);return s||(typeof e.fusionAPI<"u"?{kind:"desktop-shell"}:{kind:"browser"})}function cy(e=window){return!zg&&typeof window<"u"&&(hc=Uz(e),Bz(e),zg=!0),hc??{kind:"browser"}}function Hz(){return hc||(typeof window>"u"?{kind:"browser"}:cy(window))}const qz={kind:"browser"},dy=i.createContext({host:qz,isNativeShell:!1,kind:"browser"});function Vz(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 Wz({children:e}){const n=i.useMemo(()=>Vz(Hz()),[]);return t.jsx(dy.Provider,{value:n,children:e})}function Gz(){return i.useContext(dy)}function Kz(e,n){const s=new URL(e);return n&&s.searchParams.set("rt",n),s.toString()}function Jz({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,w]=i.useState(!1),[v,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),w(!0);try{const j=await n.startQrScan();u(j.serverUrl),h(j.authToken??"")}catch(j){p(j.message)}finally{w(!1)}},disabled:g,children:g?"Scanning…":"Scan QR"}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-profile-name",children:"Profile name"}),t.jsx("input",{id:"native-shell-onboarding-profile-name",className:"input",value:l,onChange:j=>c(j.target.value)}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-server-url",children:"Server URL"}),t.jsx("input",{id:"native-shell-onboarding-server-url",className:"input",value:d,onChange:j=>u(j.target.value),placeholder:"https://your-fusion-host"}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-auth-token",children:"Auth token (optional)"}),t.jsx("input",{id:"native-shell-onboarding-auth-token",className:"input",type:"password",value:m,onChange:j=>h(j.target.value)})]}),f&&t.jsx("p",{className:"form-error",role:"alert",children:f})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{type:"button",className:"btn btn-primary",disabled:!S||v,onClick:async()=>{p(null),b(!0);try{if(y&&r==="local"){await n.setDesktopMode("local"),a();return}const j=await n.saveProfile({name:l.trim()||"Remote Server",serverUrl:d,authToken:m||null});if(y&&await n.setDesktopMode("remote"),await n.setActiveProfile(j.id),typeof window<"u"&&s.host!=="web"){window.location.href=Kz(j.serverUrl,j.authToken??null);return}a()}catch(j){p(j.message)}finally{b(!1)}},children:v?"Saving…":"Continue"})})]})}):null}function Yz({open:e,shellApi:n,shellState:s,onClose:a}){const r=i.useMemo(()=>s.profiles.find(x=>x.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(x=>x.id===o)??r,w=c.name??g?.name??"",v=c.serverUrl??g?.serverUrl??"",b=c.authToken??g?.authToken??"",y=()=>{l(null),d({}),f(null)},S=async()=>{f(null);try{const x=new URL(v.trim());if(!/^https?:$/.test(x.protocol))throw new Error("Server URL must use http or https");const N=await n.saveProfile({id:p?void 0:o??g?.id,name:w||"Remote Server",serverUrl:v,authToken:b||null});await n.setActiveProfile(N.id),l(N.id),d({})}catch(x){f(x.message)}},j=async()=>{f(null);try{const x=await n.startQrScan();l("__new__"),d({name:"",serverUrl:x.serverUrl,authToken:x.authToken??""})}catch(x){f(x.message)}},C=async()=>{u&&(await n.deleteProfile(u.id),m(null),y())};return t.jsx("div",{className:"modal-overlay open",children:t.jsxs("div",{className:"modal native-shell-connection-manager",role:"dialog","aria-label":"Connection Manager",children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h2",{children:"Connection Manager"}),t.jsx("button",{type:"button",className:"modal-close",onClick:a,"aria-label":"Close",children:"×"})]}),s.host==="desktop-shell"&&t.jsxs("div",{className:"native-shell-connection-manager__mode-row",children:[t.jsx("button",{type:"button",className:`btn ${s.desktopMode==="local"?"btn-primary":""}`,onClick:()=>void n.setDesktopMode("local"),children:"Local"}),t.jsx("button",{type:"button",className:`btn ${s.desktopMode!=="local"?"btn-primary":""}`,onClick:()=>void n.setDesktopMode("remote"),children:"Remote"})]}),t.jsx("div",{className:"native-shell-connection-manager__profiles",children:s.profiles.length===0?t.jsxs("div",{className:"card native-shell-connection-manager__empty-state",children:[t.jsx("p",{className:"settings-muted",children:"No remote servers saved yet."}),t.jsxs("div",{className:"native-shell-connection-manager__profile-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{l("__new__"),d({name:"",serverUrl:"",authToken:""}),f(null)},children:"Add server"}),s.host==="mobile-shell"&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void j(),children:"Scan QR"})]})]}):s.profiles.map(x=>t.jsxs("div",{className:"card native-shell-connection-manager__profile",children:[t.jsxs("div",{children:[t.jsx("strong",{children:x.name}),t.jsx("div",{className:"settings-muted",children:x.serverUrl}),x.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 ${x.name}`,onClick:()=>{l(x.id),d(x)},children:"Edit"}),t.jsx("button",{type:"button",className:"btn btn-sm","aria-label":`Use ${x.name}`,onClick:()=>void n.setActiveProfile(x.id),children:"Use"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-danger","aria-label":`Delete ${x.name}`,onClick:()=>m(x),children:"Delete"})]})]},x.id))}),t.jsxs("div",{className:"native-shell-connection-manager__mode-row",children:[t.jsx("button",{type:"button",className:"btn",onClick:()=>{l("__new__"),d({name:"",serverUrl:"",authToken:""}),f(null)},children:"Add connection"}),s.host==="mobile-shell"&&t.jsx("button",{type:"button",className:"btn",onClick:()=>void j(),children:"Scan QR"})]}),t.jsxs("div",{className:"form-group native-shell-connection-manager__editor",children:[t.jsx("label",{htmlFor:"native-shell-connection-manager-name",children:"Name"}),t.jsx("input",{id:"native-shell-connection-manager-name",className:"input",value:w,onChange:x=>d(N=>({...N,name:x.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:v,onChange:x=>d(N=>({...N,serverUrl:x.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:x=>d(N=>({...N,authToken:x.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:!v.trim(),children:"Save"})]})]})})}function Qz(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 Bg({status:e,onError:n}){if(e.hostKind==="browser"||!e.available)return null;const s=Qz(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 Xz(e){if(e)try{return new URL(e).origin}catch{return}}function Zz(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 e6(e){if(!e?.getState)return null;try{return await e.getState()}catch{return null}}async function t6(e,n=window){const s=n.fusionAPI,a=n.fusionShell,r=await e6(a),o=r?Zz(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=Xz(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 n6({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&&(Cj(l),window.location.reload())},[n]),o=i.useCallback(()=>{Ej(),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 s6=200,i6=i.lazy(()=>En(()=>import("./AgentsView-CxITZE-U.js"),__vite__mapDeps([29,1,3,4,30,15,5,6,31])).then(e=>({default:e.AgentsView}))),a6=i.lazy(()=>En(()=>import("./DocumentsView-1kr0dhsV.js"),__vite__mapDeps([32,1,5,6,33])).then(e=>({default:e.DocumentsView}))),r6=i.lazy(()=>En(()=>import("./InsightsView-D2AjxOnu.js"),__vite__mapDeps([34,1,22,5,6,35])).then(e=>({default:e.InsightsView}))),o6=i.lazy(()=>En(()=>import("./ResearchView-C9bjVB7-.js"),__vite__mapDeps([36,1,5,6,37])).then(e=>({default:e.ResearchView}))),l6=i.lazy(()=>En(()=>import("./EvalsView-cDfXYiK6.js"),__vite__mapDeps([38,1,5,6,39])).then(e=>({default:e.EvalsView}))),c6=i.lazy(()=>En(()=>import("./NodesView-Cpmkze7n.js"),__vite__mapDeps([40,1,17,30,5,6,41])).then(e=>({default:e.NodesView}))),d6=i.lazy(()=>En(()=>import("./ChatView-7WPHyB_7.js"),__vite__mapDeps([42,1,5,6,43])).then(e=>({default:e.ChatView}))),u6=i.lazy(()=>En(()=>import("./SkillsView-DmZfbGLs.js"),__vite__mapDeps([44,1,5,6,45])).then(e=>({default:e.SkillsView}))),m6=i.lazy(()=>En(()=>import("./MemoryView-Dq4yjIPI.js"),__vite__mapDeps([46,1,20,21,5,6,47])).then(e=>({default:e.MemoryView}))),h6=i.lazy(()=>En(()=>import("./DevServerView-Diw4hjw0.js"),__vite__mapDeps([48,1,5,6,49])).then(e=>({default:e.DevServerView})));i.lazy(()=>En(()=>import("./TodoView-uJRg4Cnl.js"),__vite__mapDeps([11,1,5,6,12])).then(e=>({default:e.TodoView})));const p6=i.lazy(()=>En(()=>import("./StashRecoveryView-BwKJQaUW.js"),__vite__mapDeps([50,1,5,6,51])).then(e=>({default:e.StashRecoveryView})));function f6(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{En(()=>import("./AgentsView-CxITZE-U.js"),__vite__mapDeps([29,1,3,4,30,15,5,6,31])),En(()=>import("./DocumentsView-1kr0dhsV.js"),__vite__mapDeps([32,1,5,6,33])),En(()=>import("./InsightsView-D2AjxOnu.js"),__vite__mapDeps([34,1,22,5,6,35])),En(()=>import("./ResearchView-C9bjVB7-.js"),__vite__mapDeps([36,1,5,6,37])),En(()=>import("./EvalsView-cDfXYiK6.js"),__vite__mapDeps([38,1,5,6,39])),En(()=>import("./NodesView-Cpmkze7n.js"),__vite__mapDeps([40,1,17,30,5,6,41])),En(()=>import("./ChatView-7WPHyB_7.js"),__vite__mapDeps([42,1,5,6,43])),En(()=>import("./SkillsView-DmZfbGLs.js"),__vite__mapDeps([44,1,5,6,45])),En(()=>import("./MemoryView-Dq4yjIPI.js"),__vite__mapDeps([46,1,20,21,5,6,47])),En(()=>import("./DevServerView-Diw4hjw0.js"),__vite__mapDeps([48,1,5,6,49])),En(()=>import("./TodoView-uJRg4Cnl.js"),__vite__mapDeps([11,1,5,6,12])),En(()=>import("./StashRecoveryView-BwKJQaUW.js"),__vite__mapDeps([50,1,5,6,51]))})}ay();const Zd="kb-setup-warning-dismissed",g6="kb-chat-active-session",Ug="kb-dashboard-working-branch-filter",Hg="kb-dashboard-base-branch-filter",qg="__fusion:no-branch__",uy="fusion:approval-banner-dismissed";function b6(e,n){return e==="awaiting-approval"&&n!=="awaiting-approval"}function Vg(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function x6(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(uy);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 Wg(e){if(!(typeof window>"u"))try{const n={};for(const[s,a]of e)n[s]=a;window.localStorage.setItem(uy,JSON.stringify(n))}catch{}}function v6(e,n){const s=new URL(e);return n&&s.searchParams.set("rt",n),s.toString()}function y6(e,n,s){return!n||s||e.host==="web"?!1:e.host==="mobile-shell"?!e.activeProfileId:e.desktopMode==="local"?!1:!e.activeProfileId}function w6(){const{toasts:e,addToast:n,removeToast:s}=nz(),{shellApi:a,state:r,ready:o,openConnectionManagerSignal:l}=Bv(),c=Gz();i.useEffect(()=>{f6()},[]);const{projects:d,loading:u,error:m,refresh:h}=QF(),{nodes:f}=Cc(),{currentNode:p,currentNodeId:g,isRemote:w,setCurrentNode:v,clearCurrentNode:b}=Tz(),{currentProject:y,setCurrentProject:S,clearCurrentProject:j,loading:C}=ez(d,{nodeId:g}),{hasAiProvider:x,hasGithub:N,loading:R,hasWarnings:F}=Lv(y?.id),{updateAvailable:E,latestVersion:_,currentVersion:K,dismissed:U,dismiss:A}=fz();i.useEffect(()=>{if(g&&!p&&f.length>0){const Je=f.find(Rt=>Rt.id===g);if(Je){v(Je);return}}g&&f.length>0&&(f.some(Rt=>Rt.id===g)||b())},[g,p,f,v,b]);const[T,H]=i.useState(""),[Q,se]=i.useState(""),[O,M]=i.useState("");i.useEffect(()=>{se(Gn(Ug,y?.id)??""),M(Gn(Hg,y?.id)??"")},[y?.id]);const D=i.useCallback(Je=>{se(Je),fs(Ug,Je,y?.id)},[y?.id]),$=i.useCallback(Je=>{M(Je),fs(Hg,Je,y?.id)},[y?.id]),k=Mz(g,{projectId:y?.id,searchQuery:T||void 0});Az(g);const X=w&&k.projects.length>0?k.projects:d,{themeMode:le,colorTheme:ke,dashboardFontScalePct:He,setThemeMode:ye,setColorTheme:je,setDashboardFontScalePct:ne}=cz(),{sessions:fe,generating:Z,needsInput:re,planningSessions:q,dismissSession:L}=UF(y?.id),xe=fe.filter(Je=>Je.status==="awaiting_input"||Je.status==="error"),he=VF(),B=dz({projectId:y?.id,planningSessions:q}),ze=oi()==="mobile",{pushNav:ae,replaceCurrent:Ve}=x$({enabled:!0}),{viewMode:Te,setViewMode:rt,taskView:Be,handleChangeTaskView:ce}=vz({projectsLoading:u,projectsError:m,currentProjectLoading:C,currentProject:y,projectsLength:d.length,setupWizardOpen:B.setupWizardOpen,openSetupWizard:B.openSetupWizard,themeMode:le,setThemeMode:ye}),{views:Re}=wz(y?.id),Le=i.useMemo(()=>{const Je=Re.find(Rt=>Rt.pluginId==="fusion-plugin-dependency-graph"&&Rt.view.viewId==="graph");return Je?`plugin:${Je.pluginId}:${Je.view.viewId}`:Rb("fusion-plugin-dependency-graph","graph")?"plugin:fusion-plugin-dependency-graph:graph":null},[Re]),ct=i.useCallback(Je=>{Je==="missions"&&(Sn(void 0),Jt(void 0),Ne(void 0));const Rt=Be;ce(Je),Rt!==Je&&ae({type:"view",revert:()=>ce(Rt)})},[ce,Be,ae]),Ue=Be==="board"||Be==="list",{tasks:ue,createTask:oe,moveTask:Ee,pauseTask:ft,deleteTask:ht,mergeTask:tt,retryTask:xt,resetTask:Me,updateTask:Ye,duplicateTask:dt,archiveTask:wt,unarchiveTask:St,archiveAllDone:Fe,loadArchivedTasks:J,ingestCreatedTasks:me,lastFetchTimeMs:Ze}=GF({...y?{projectId:y.id}:{},searchQuery:T||void 0,sseEnabled:Ue}),be=w&&k.tasks.length>0?k.tasks:ue,[gt,$t]=i.useState(!1),[Ie,ge]=i.useState(0),st=i.useRef(performance.now()),yt=i.useRef(!1),pt=i.useRef(!1),vt=i.useMemo(()=>u?"projects":C?"project":"tasks",[u,C]);i.useEffect(()=>{if(!u&&!yt.current){yt.current=!0;const Je=`projects loaded at ${Math.round(performance.now()-st.current)}ms from mount`;console.log(`[App] ${Je}`)}if(!C&&!pt.current){pt.current=!0;const Je=`current-project resolved at ${Math.round(performance.now()-st.current)}ms from mount`;console.log(`[App] ${Je}`)}},[u,C]),i.useEffect(()=>{if(gt||u||C)return;const Je=performance.now(),Rt=window.setTimeout(()=>{const rn=`dashboard ready at ${Math.round(performance.now()-st.current)}ms from mount (settle delay=${Math.round(performance.now()-Je)}ms)`;console.log(`[App] ${rn}`),$t(!0)},s6);return()=>{window.clearTimeout(Rt)}},[gt,u,C]);const{keyboardOpen:Ut}=aa({enabled:ze}),Dt=ze&&Ut&&!B.anyModalOpen;Mi(Dt);const[nn,on]=i.useState(0),[sn,ln]=i.useState(0),[xn,qt]=i.useState(!1),[Qt,hn]=i.useState(0),[Zt,ve]=i.useState(null),Pe=i.useRef(new Map),Ke=i.useRef(new Set),at=i.useRef(x6()),We=i.useCallback(()=>{Nb(y?.id).then(Je=>{on(Je.unreadCount),ln(Je.pendingApprovalCount??0)}).catch(Je=>{console.warn("[App] Failed to fetch mailbox unread count:",Je)})},[y?.id]);i.useEffect(()=>{const Je=new Map,Rt=new Set;for(const rn of ue)Je.set(rn.id,rn.status),rn.status==="awaiting-approval"&&Rt.add(`task:${rn.id}`);Pe.current=Je,Ke.current=Rt},[ue]),i.useEffect(()=>{We();const Je=new URLSearchParams;y?.id&&Je.set("projectId",y.id);const Rt=Je.size>0?`?${Je.toString()}`:"",rn=es=>{const Hn=at.current.get(es.dedupeKey);Hn!==void 0&&es.updatedAtMs<=Hn||ve(es)};return yi(`/api/events${Rt}`,{onReconnect:We,events:{"message:sent":We,"message:received":We,"message:read":We,"message:deleted":We,"approval:requested":es=>{We();try{const Hn=JSON.parse(es.data),Bs=Hn.id?`approval:${Hn.id}`:Hn.taskId?`task:${Hn.taskId}`:void 0;if(!Bs||Ke.current.has(Bs))return;Ke.current.add(Bs),rn({dedupeKey:Bs,updatedAtMs:Vg(Hn.updatedAt??Hn.createdAt)})}catch{}},"approval:updated":We,"approval:decided":We,"task:updated":es=>{try{const Hn=JSON.parse(es.data);if(!Hn?.id)return;const Bs=`task:${Hn.id}`,rr=Pe.current.get(Hn.id);if(Pe.current.set(Hn.id,Hn.status),Hn.status!=="awaiting-approval"){Ke.current.delete(Bs),at.current.delete(Bs),Wg(at.current);return}if(Ke.current.has(Bs))return;b6(Hn.status,rr)&&(Ke.current.add(Bs),rn({dedupeKey:Bs,updatedAtMs:Vg(Hn.updatedAt)}),We())}catch{}}}})},[y?.id,We]),i.useEffect(()=>{Be==="chat"&&qt(!1)},[Be]),i.useEffect(()=>{let Je=!1;const Rt=async()=>{try{const es=await I("/stash-recovery/orphans");Je||hn(es.count??0)}catch{Je||hn(0)}};Rt();const rn=window.setInterval(()=>void Rt(),3e4);return()=>{Je=!0,window.clearInterval(rn)}},[y?.id]),i.useEffect(()=>{const Je=new URLSearchParams;y?.id&&Je.set("projectId",y.id);const Rt=Je.size>0?`?${Je.toString()}`:"";return yi(`/api/events${Rt}`,{events:{"chat:message:added":rn=>{try{const es=JSON.parse(rn.data),Hn=Gn(g6,y?.id);if(!Hn||es.role!=="assistant"||Be==="chat"||es.sessionId!==Hn||es.projectId&&y?.id&&es.projectId!==y.id)return;qt(!0)}catch{}}}})},[y?.id,Be]);const It=i.useMemo(()=>Array.from(new Set(be.map(Je=>Je.branch?.trim()).filter(Je=>!!(Je&&Je.length>0)))).sort((Je,Rt)=>Je.localeCompare(Rt)),[be]),Lt=i.useMemo(()=>Array.from(new Set(be.map(Je=>Je.baseBranch?.trim()).filter(Je=>!!(Je&&Je.length>0)))).sort((Je,Rt)=>Je.localeCompare(Rt)),[be]),Bt=i.useMemo(()=>be.filter(Je=>{const Rt=Je.branch?.trim()??"",rn=Je.baseBranch?.trim()??"";if(Q===qg){if(Rt.length>0)return!1}else if(Q.length>0&&Rt!==Q)return!1;if(O===qg){if(rn.length>0)return!1}else if(O.length>0&&rn!==O)return!1;return!0}),[be,Q,O]),[Gt,bt]=i.useState(!1),[Ot,en]=i.useState(!1),[Kt,Sn]=i.useState(void 0),[dn,Jt]=i.useState(void 0),[tn,Ne]=i.useState(void 0),[W,Y]=i.useState(!1),[_e,ut]=i.useState(!1),[At,zt]=i.useState(null),[yn,Zn]=i.useState(()=>Gn(Zd,y?.id)==="true");i.useEffect(()=>{Zn(Gn(Zd,y?.id)==="true")},[y?.id]),i.useEffect(()=>{let Je=!1;return Dj().then(Rt=>{Je||zt(Rt)}).catch(()=>{Je||zt(null)}),()=>{Je=!0}},[]),i.useEffect(()=>{const Je=()=>{ut(!0)};return window.addEventListener(cu,Je),()=>{window.removeEventListener(cu,Je)}},[]);const vn=i.useCallback(()=>{fs(Zd,"true",y?.id),Zn(!0)},[y?.id]),{maxConcurrent:Dn,autoMerge:de,globalPaused:nt,enginePaused:ot,taskStuckTimeoutMs:_t,staleHighFanoutBlockerAgeThresholdMs:G,showQuickChatFAB:Oe,prAuthAvailable:Mt,settingsLoaded:Xt,experimentalFeatures:_n,insightsEnabled:Pn,memoryEnabled:kn,devServerEnabled:Vn,todosEnabled:$s,toggleAutoMerge:vs,toggleGlobalPause:As,toggleEnginePause:bn,refresh:Ht}=uz(y?.id),On=_n.skillsView===!0,Fn=_n.nodesView===!0,as=_n.researchView===!0,Wn=_n.evalsView===!0,Rs=_n.agentOnboarding===!0,In=!0,rs=i.useCallback(()=>{B.closeSettings(),ge(Je=>Je+1),Ht()},[B,Ht]);i.useEffect(()=>{if(Xt&&!wr(Be)){if(Be==="graph"&&!Le){ce("board");return}Be==="skills"&&!On&&ce("board"),Be==="insights"&&!Pn&&ce("board"),Be==="memory"&&!kn&&ce("board"),(Be==="devserver"||Be==="dev-server")&&!Vn&&ce("board"),Be==="research"&&!as&&ce("board"),Be==="evals"&&!Wn&&ce("board")}},[Be,Xt,On,Pn,ce,In,kn,Vn,as,Wn,Le]),i.useEffect(()=>{Gt&&!Fn&&bt(!1)},[Gt,Fn]);const{availableModels:Ns,favoriteProviders:ys,favoriteModels:cs,toggleFavoriteProvider:ss,toggleFavoriteModel:te}=hz();pz({projectId:y?.id,setupWizardOpen:B.setupWizardOpen,openModelOnboarding:B.openModelOnboarding,openSettings:B.openSettings});const{handleSelectProject:we,handleViewAllProjects:P,handleAddProject:Ce,handleSetupComplete:qe,handleModelOnboardingComplete:et,handlePauseProject:mt,handleResumeProject:Nt,handleRemoveProject:Pt,handleToggleFavorite:an,handleToggleModelFavorite:Cn}=Ez({setCurrentProject:S,clearCurrentProject:j,setViewMode:rt,currentProject:y,refreshProjects:h,toggleFavoriteProvider:ss,toggleFavoriteModel:te,addToast:n,openSettings:B.openSettings,openSetupWizard:B.openSetupWizard,closeSetupWizard:B.closeSetupWizard,closeModelOnboarding:B.closeModelOnboarding}),{handleDetailClose:ie}=mz({projectId:y?.id,projects:d,projectsLoading:u,currentProject:y,setCurrentProject:S,addToast:n,openTaskDetail:B.openDetailTask,closeTaskDetail:B.closeDetailTask}),$e=i.useCallback(async({insightId:Je,title:Rt,description:rn})=>{await oe({title:Rt,description:rn,column:"triage",source:{sourceType:"dashboard_ui",sourceMetadata:{origin:"insights",insightId:Je}}})},[oe]),{handleBoardQuickCreate:Qe,handleModalCreate:Ft,handlePlanningTaskCreated:cn,handlePlanningTasksCreated:pn,handleSubtaskTasksCreated:jn,handleGitHubImport:Un}=_z({createTask:oe,ingestCreatedTasks:me,onPlanningTaskCreated:B.onPlanningTaskCreated,onPlanningTasksCreated:B.onPlanningTasksCreated,onSubtaskTasksCreated:B.onSubtaskTasksCreated,addToast:n}),gs=i.useCallback((Je,Rt)=>{Rt==="changes"?B.openDetailWithChangesTab(Je):B.openDetailTask(Je,Rt),ae({type:"modal",close:B.closeDetailTask})},[B,ae]),bs=i.useCallback(async Je=>{try{const Rt=await Ba(Je,y?.id);B.openDetailTask(Rt,"logs"),ae({type:"modal",close:B.closeDetailTask})}catch(Rt){n(`Failed to open task logs: ${Rt.message}`,"error")}},[B,y?.id,n,ae]),[is,ds]=i.useState([]);i.useEffect(()=>{let Je=!1;return Ko(y?.id).then(Rt=>{Je||ds(Rt)}).catch(()=>{Je||ds([])}),()=>{Je=!0}},[y?.id]);const xs=i.useMemo(()=>new Map(is.map(Je=>[Je.id,Je.name])),[is]);i.useCallback(()=>{Fn&&bt(Je=>!Je)},[Fn]);const ra=i.useCallback(()=>{Fn&&(Gt?bt(!1):(bt(!0),ae({type:"view",revert:()=>bt(!1)})))},[Fn,Gt,ae]),Jn=i.useCallback((Je,Rt,rn)=>{B.openDetailTask(Je,Rt,rn),ae({type:"modal",close:B.closeDetailTask})},[B,ae]),Ui=i.useCallback(Je=>{B.openSettings(Je),ae({type:"modal",close:rs})},[B,ae,rs]),Hi=i.useCallback(()=>{B.openNewTask(),ae({type:"modal",close:B.closeNewTask})},[B,ae]),Zs=i.useCallback(()=>{B.openPlanning(),ae({type:"modal",close:B.closePlanning})},[B,ae]),ja=i.useCallback(Je=>{B.openPlanningWithInitialPlan(Je),ae({type:"modal",close:B.closePlanning})},[B,ae]),Na=i.useCallback(()=>{B.resumePlanning(),ae({type:"modal",close:B.closePlanning})},[B,ae]),Ya=i.useCallback(Je=>{B.openSubtaskBreakdown(Je),ae({type:"modal",close:B.closeSubtask})},[B,ae]),Qa=i.useCallback(()=>{B.openGitHubImport(),ae({type:"modal",close:B.closeGitHubImport})},[B,ae]),Mn=i.useCallback(()=>{B.terminalOpen?B.toggleTerminal():(B.toggleTerminal(),ae({type:"modal",close:B.closeTerminal}))},[B,ae]),ci=i.useCallback((Je,Rt)=>{B.openFiles(Je,Rt),ae({type:"modal",close:B.closeFiles})},[B,ae]),wi=i.useCallback((Je,Rt)=>{B.openFiles(Rt?.workspace,Je),ae({type:"modal",close:B.closeFiles})},[B,ae]),Ai=i.useCallback(()=>{B.openTodos(),ae({type:"modal",close:B.closeTodos})},[B,ae]),Sa=i.useCallback(()=>{B.openActivityLog(),ae({type:"modal",close:B.closeActivityLog})},[B,ae]),Xa=i.useCallback(()=>{B.openGitManager(),ae({type:"modal",close:B.closeGitManager})},[B,ae]),Za=i.useCallback(()=>{B.openSystemStats(),ae({type:"modal",close:B.closeSystemStats})},[B,ae]),Ca=i.useCallback(()=>{B.openSchedules(),ae({type:"modal",close:B.closeSchedules})},[B,ae]),Ea=i.useCallback(()=>{B.openScripts(),ae({type:"modal",close:B.closeScripts})},[B,ae]),_a=i.useCallback(()=>{B.openWorkflowSteps(),ae({type:"modal",close:B.closeWorkflowSteps})},[B,ae]),er=i.useCallback(Je=>{B.openUsage(Je),ae({type:"modal",close:B.closeUsage})},[B,ae]),Ma=i.useCallback(async(Je,Rt)=>{await B.runScript(Je,Rt),Ve({type:"modal",close:B.closeTerminal})},[B,Ve]),di=i.useCallback(()=>{B.closeSettings(),B.openModelOnboarding(),Ve({type:"modal",close:B.closeModelOnboarding})},[B,Ve]),ki=i.useCallback(()=>{B.setFileWorkspace("project"),B.openFiles()},[B]),Ds=i.useCallback(async()=>{en(!0);try{await h()}finally{en(!1)}},[h]),tr=i.useCallback(Je=>{Jt(Je),Sn(void 0),ce("missions")},[ce]),qi=i.useCallback(Je=>{Je.type==="planning"?B.openPlanningWithSession(Je.id):Je.type==="subtask"?B.openSubtaskWithSession(Je.id):Je.type==="mission_interview"?(Jt(void 0),Sn(Je.id),Ne(void 0),ce("missions")):(Je.type==="milestone_interview"||Je.type==="slice_interview")&&(Sn(void 0),Jt(void 0),Ne(Je.id),ce("missions"))},[ce,B]),nr=i.useCallback(()=>{},[]),ei=i.useCallback(()=>{},[]),[Gr,Kr]=i.useState(!1),[Jr,oa]=i.useState(!1),[Vi,sr]=i.useState(null),ir=y6(r,o,Gr);i.useEffect(()=>{!a||l===0||oa(!0)},[a,l]),i.useEffect(()=>{let Je=!1;return t6(c.host).then(Rt=>{Je||sr(Rt)}),()=>{Je=!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 Je=r.profiles.find(rn=>rn.id===r.activeProfileId);if(!Je||typeof window>"u")return;const Rt=v6(Je.serverUrl,Je.authToken??null);window.location.href!==Rt&&(window.location.href=Rt)},[r]);const Yr=!u&&!C&&d.length===0&&!y&&!!m,ar=()=>{if(Yr)return t.jsx(HO,{errorMessage:m??"Failed to fetch projects",isRetrying:Ot,onRetry:Ds,onManageConnection:a?()=>{a.openConnectionManager()}:void 0});if(Gt)return t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(c6,{addToast:n,onClose:()=>bt(!1)})})})});if(Te==="overview")return t.jsx(Is,{children:t.jsx(g$,{projects:d,loading:u,onSelectProject:we,onAddProject:Ce,onPauseProject:mt,onResumeProject:Nt,onRemoveProject:Pt,nodes:f})});const Je=Be==="graph"?Le:wr(Be)?Be:null;return Je?t.jsx(Is,{children:t.jsx(kz,{taskView:Je,context:{projectId:y?.id,tasks:w&&k.tasks.length>0?k.tasks:ue,workflowSteps:is,openTaskDetail:(Rt,rn)=>Jn(Rt,rn),renderTaskCard:Rt=>t.jsx(Do,{task:Rt,projectId:y?.id,onOpenDetail:rn=>Jn(rn),addToast:n,workflowStepNameLookup:xs,disableDrag:!0}),addToast:n}})}):Be==="skills"?!Xt||!On?null:t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(u6,{addToast:n,projectId:y?.id,onClose:()=>ce("board")})})}):Be==="chat"?t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(d6,{addToast:n,projectId:y?.id,experimentalFeatures:_n})})}):Be==="mailbox"?t.jsx(Is,{children:t.jsx(m4,{projectId:y?.id,addToast:n,onUnreadCountChange:on})}):Be==="missions"?t.jsx(Is,{children:t.jsx(o4,{isInline:!0,isOpen:!0,onClose:()=>{Jt(void 0),Sn(void 0),Ne(void 0),ce("board")},addToast:n,projectId:y?.id,onSelectTask:Rt=>{const rn=ue.find(es=>es.id===Rt);rn&&Jn(rn)},availableTasks:ue.map(Rt=>({id:Rt.id,title:Rt.title})),resumeSessionId:Kt,targetMissionId:dn,milestoneSliceResumeSessionId:tn,onMilestoneSliceResumeFetchError:()=>Ne(void 0)})}):Be==="agents"&&In?t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(i6,{addToast:n,projectId:y?.id,onOpenTaskLogs:bs,agentOnboardingEnabled:Rs})})}):Be==="documents"?t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(a6,{projectId:y?.id,addToast:n,onOpenDetail:Jn})})}):Be==="stash-recovery"?t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(p6,{})})}):Be==="insights"?!Xt||!Pn?null:t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(r6,{projectId:y?.id,addToast:n,onClose:()=>ce("board"),onCreateTask:$e})})}):Be==="research"?!Xt||!as?null:t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(o6,{projectId:y?.id,addToast:n,onOpenSettings:Rt=>B.openSettings(Rt),readinessVersion:Ie})})}):Be==="evals"?!Xt||!Wn?null:t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(l6,{projectId:y?.id,onOpenSettings:Rt=>B.openSettings(Rt),onOpenTaskDetail:Rt=>{Ba(Rt,y?.id).then(rn=>Jn(rn)).catch(rn=>n(rn instanceof Error?rn.message:"Failed to open task detail","error"))}})})}):Be==="memory"?!Xt||!kn?null:t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(m6,{addToast:n,projectId:y?.id})})}):Be==="devserver"||Be==="dev-server"?!Xt||!Vn?null:t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(h6,{addToast:n,projectId:y?.id})})}):Be==="board"?t.jsx(Is,{children:t.jsx(n_,{tasks:Bt,projectId:y?.id,maxConcurrent:Dn,onMoveTask:Ee,onPauseTask:ft,onOpenDetail:Jn,addToast:n,onQuickCreate:Qe,onNewTask:Hi,onPlanningMode:ja,onSubtaskBreakdown:Ya,autoMerge:de,onToggleAutoMerge:vs,globalPaused:nt,onUpdateTask:Ye,onRetryTask:xt,onArchiveTask:wt,onUnarchiveTask:St,onDeleteTask:ht,onArchiveAllDone:Fe,onLoadArchivedTasks:J,searchQuery:T,availableModels:Ns,onOpenDetailWithTab:gs,favoriteProviders:ys,favoriteModels:cs,onToggleFavorite:an,onToggleModelFavorite:Cn,taskStuckTimeoutMs:_t,staleHighFanoutBlockerAgeThresholdMs:G,onOpenMission:tr,lastFetchTimeMs:Ze})}):t.jsx(Is,{children:t.jsx(i$,{tasks:w&&k.tasks.length>0?k.tasks:ue,projectId:y?.id,onMoveTask:Ee,onRetryTask:xt,onDeleteTask:ht,onMergeTask:tt,onResetTask:Me,onDuplicateTask:dt,onOpenDetail:(Rt,rn)=>Jn(Rt,void 0,rn),addToast:n,globalPaused:nt,onNewTask:Hi,onQuickCreate:Qe,onPlanningMode:ja,onSubtaskBreakdown:Ya,availableModels:Ns,favoriteProviders:ys,favoriteModels:cs,onToggleFavorite:an,onToggleModelFavorite:Cn,taskStuckTimeoutMs:_t,searchQuery:T,lastFetchTimeMs:Ze,prAuthAvailable:Mt})})};if(!gt)return t.jsxs(t.Fragment,{children:[t.jsx(VO,{stage:vt}),t.jsx(Wv,{toasts:e,onRemove:s})]});const Aa=!B.modelOnboardingOpen&&mO(),Wi=!B.modelOnboardingOpen&&!Aa&&Lr()&&!Uv();return t.jsx(b$,{value:{pushNav:ae,replaceCurrent:Ve},children:t.jsxs(DT,{openFile:wi,children:[t.jsx(IC,{shellHost:c.host,onOpenSettings:Ui,onOpenGitHubImport:Qa,onOpenPlanning:Zs,onResumePlanning:Na,activePlanningSessionCount:q.length,onOpenUsage:er,onOpenActivityLog:Sa,onOpenSystemStats:Za,onOpenMailbox:()=>ct("mailbox"),mailboxUnreadCount:nn,mailboxPendingApprovalCount:sn,chatHasUnreadResponse:xn,stashOrphanCount:Qt,onOpenSchedules:Ca,onOpenGitManager:Xa,onOpenNodes:ra,showNodesButton:Fn,onOpenWorkflowSteps:_a,onOpenScripts:Ea,onRunScript:Ma,onToggleTerminal:Mn,onOpenFiles:ci,filesOpen:B.filesOpen,onOpenTodos:Ai,todosOpen:B.todosOpen,todosEnabled:$s,globalPaused:nt,enginePaused:ot,onToggleGlobalPause:As,onToggleEnginePause:bn,view:Be,onChangeView:Te==="project"&&y?ct:void 0,showSkillsTab:On,showAgentsTab:In,searchQuery:T,onSearchChange:H,branchFilter:Q,baseBranchFilter:O,branchOptions:It,baseBranchOptions:Lt,onBranchFilterChange:D,onBaseBranchFilterChange:$,projects:X,currentProject:y,onSelectProject:we,onViewAllProjects:P,projectId:y?.id,mobileNavEnabled:ze,availableNodes:f,currentNode:p,onSelectNode:Je=>{Je===null?b():v(Je)},isRemote:w,experimentalFeatures:{insights:Pn,memoryView:kn,devServer:Vn,devServerView:Vn,researchView:as,evalsView:Wn},pluginDashboardViews:Re,shellConnectionControl:!ze&&Vi?t.jsx(Bg,{status:Vi,onError:Je=>n(Je,"error")}):void 0}),Te==="project"&&y&&!Gt&&Be!=="missions"&&!B.isPlanningOpen&&!he&&t.jsx(rF,{sessions:xe,onResumeSession:qi,onDismissSession:nr,onDismissAll:ei}),Te==="project"&&y&&t.jsx(cF,{onOpenSettings:()=>B.openSettings("general")}),Te==="project"&&y&&Aa&&t.jsx(fF,{onResume:B.openModelOnboarding}),Te==="project"&&y&&Wi&&t.jsx(gF,{onOpenModelOnboarding:B.openModelOnboarding,onOpenSettings:Je=>B.openSettings(Je)}),Te==="project"&&y&&E&&_&&K&&!U&&t.jsx(hF,{latestVersion:_,currentVersion:K,onDismiss:A}),Te==="project"&&y&&At?.taskIdIntegrity?.status==="anomaly"&&At.taskIdIntegrity.recommendedAction&&t.jsx(mF,{report:At.taskIdIntegrity,recommendedAction:At.taskIdIntegrity.recommendedAction,onRefresh:(Je,Rt)=>{zt(rn=>rn?{...rn,status:Je.status==="anomaly"||!rn.database.healthy?"degraded":"ok",taskIdIntegrity:{...Je,recommendedAction:Rt}}:null)}}),Te==="project"&&y&&!R&&F&&!yn&&t.jsx(Ov,{hasAiProvider:x,hasGithub:N,onDismiss:vn}),Te==="project"&&y&&Zt&&t.jsx(pF,{pendingCount:Math.max(sn,1),onOpenMailbox:()=>ct("mailbox"),onDismiss:()=>{at.current.set(Zt.dedupeKey,Math.max(Date.now(),Zt.updatedAtMs)),Wg(at.current),ve(null)}}),t.jsx("div",{className:`project-content${Te==="project"&&y&&(!ze||!Dt)?" project-content--with-footer":""}${ze&&!Dt?" project-content--with-mobile-nav":""}`,children:ar()}),Te==="project"&&y&&!Gt&&t.jsx(tF,{tasks:w&&k.tasks.length>0?k.tasks:ue,projectId:y.id,taskStuckTimeoutMs:_t,staleHighFanoutBlockerAgeThresholdMs:G,backgroundSessions:fe,backgroundGenerating:Z,backgroundNeedsInput:re,onOpenBackgroundSession:qi,onDismissBackgroundSession:L,lastFetchTimeMs:Ze,currentProjectPath:y.path,onOpenProjectDirectory:ki,keyboardOpen:Dt}),t.jsx(xF,{view:Be,onChangeView:Te==="project"&&y?ct:()=>{},footerVisible:Te==="project"&&!!y,modalOpen:B.anyModalOpen,keyboardOpen:Dt,onOpenSettings:Ui,onOpenActivityLog:Sa,onOpenSystemStats:Za,onOpenMailbox:()=>ct("mailbox"),onOpenNodes:ra,mailboxUnreadCount:nn,mailboxPendingApprovalCount:sn,chatHasUnreadResponse:xn,stashOrphanCount:Qt,onOpenGitManager:Xa,onOpenWorkflowSteps:_a,onOpenSchedules:Ca,onOpenScripts:Ea,onToggleTerminal:Mn,onOpenFiles:ci,onOpenTodos:Ai,todosOpen:B.todosOpen,onOpenGitHubImport:Qa,onOpenPlanning:Zs,onResumePlanning:Na,activePlanningSessionCount:q.length,onOpenUsage:()=>er(null),onViewAllProjects:P,onRunScript:Ma,projectId:y?.id,showSkillsTab:On,experimentalFeatures:{insights:Pn,memoryView:kn,devServer:Vn,devServerView:Vn,todoView:$s,researchView:as,evalsView:Wn,nodesView:Fn},pluginDashboardViews:Re,shellConnectionControl:ze&&Vi?t.jsx(Bg,{status:Vi,onError:Je=>n(Je,"error")}):void 0}),Te==="project"&&y&&Be!=="chat"&&Be!=="mailbox"&&Be!=="insights"&&Be!=="evals"&&Be!=="devserver"&&Be!=="dev-server"&&Be!=="graph"&&!wr(Be)&&t.jsx(BF,{projectId:y.id,addToast:n,showFAB:Oe,open:W,onOpenChange:Y,favoriteProviders:ys,favoriteModels:cs,onToggleFavorite:an,onToggleModelFavorite:Cn}),t.jsx(UO,{projectId:y?.id,tasks:ue,projects:d,currentProject:y,addToast:n,toasts:e,removeToast:s,modalManager:B,projectActions:{handleAddProject:Ce,handleSetupComplete:qe,handleModelOnboardingComplete:et},taskHandlers:{handleModalCreate:Ft,handlePlanningTaskCreated:cn,handlePlanningTasksCreated:pn,handleSubtaskTasksCreated:jn,handleGitHubImport:Un},taskOperations:{moveTask:Ee,deleteTask:ht,mergeTask:tt,retryTask:xt,resetTask:Me,duplicateTask:dt},deepLink:{handleDetailClose:ie},settings:{prAuthAvailable:Mt,themeMode:le,colorTheme:ke,dashboardFontScalePct:He,setThemeMode:ye,setColorTheme:je,setDashboardFontScalePct:ne},onSettingsClose:rs,onReopenOnboarding:di}),t.jsx(n6,{open:_e}),a&&t.jsxs(t.Fragment,{children:[t.jsx(Jz,{open:ir,shellApi:a,shellState:r,onComplete:()=>Kr(!0)}),t.jsx(Yz,{open:Jr,shellApi:a,shellState:r,onClose:()=>oa(!1)})]})]})})}function k6(){return t.jsx(tz,{children:t.jsx(Wz,{children:t.jsx(eO,{children:t.jsx(Iz,{children:t.jsx(WC,{children:t.jsx(w6,{})})})})})})}function my(e){e.postMessage({type:"SKIP_WAITING"})}function Gg(e){e.addEventListener("statechange",()=>{e.state==="installed"&&navigator.serviceWorker.controller&&my(e)})}function j6(){if(!("serviceWorker"in navigator))return;const e=!!navigator.serviceWorker.controller;let n=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{n||!e||(n=!0,Hu("service worker activated new version"))}),navigator.serviceWorker.register("/sw.js").then(s=>{console.log("SW registered:",s.scope),s.waiting&&navigator.serviceWorker.controller&&my(s.waiting),s.installing&&Gg(s.installing),s.addEventListener("updatefound",()=>{const a=s.installing;a&&Gg(a)})}).catch(s=>{console.log("SW registration failed:",s)})}Pj();vj();cy();ay();vy.createRoot(document.getElementById("root")).render(t.jsx(i.StrictMode,{children:t.jsx(yj,{children:t.jsx(k6,{})})}));j6();export{s1 as $,Js as A,Qn as B,Xn as C,HC as D,Z3 as E,xa as F,gc as G,au as H,$n as I,ql as J,$8 as K,jt as L,qo as M,jk as N,BL as O,zn as P,Gd as Q,ps as R,Xi as S,zr as T,os as U,Ci as V,Tn as W,mn as X,LL as Y,ls as Z,En as _,gn as a,u5 as a$,ML as a0,AL as a1,i1 as a2,Y3 as a3,a1 as a4,c3 as a5,d3 as a6,cS as a7,zu as a8,Fr as a9,w8 as aA,y8 as aB,v8 as aC,b8 as aD,Oj as aE,Po as aF,h8 as aG,f8 as aH,p8 as aI,C8 as aJ,N8 as aK,S8 as aL,E8 as aM,p5 as aN,P8 as aO,To as aP,eu as aQ,Gk as aR,$i as aS,Ok as aT,lw as aU,Cs as aV,m$ as aW,Hs as aX,ob as aY,Dk as aZ,d5 as a_,Ga as aa,xi as ab,vi as ac,Li as ad,a8 as ae,d8 as af,c8 as ag,Kl as ah,u8 as ai,r8 as aj,m8 as ak,o8 as al,l8 as am,ms as an,zo as ao,Co as ap,Vs as aq,ij as ar,Oi as as,eb as at,ta as au,_y as av,g8 as aw,x8 as ax,j8 as ay,k8 as az,qn as b,P3 as b$,m5 as b0,h5 as b1,Cc as b2,QF as b3,uh as b4,Zr as b5,wg as b6,Y0 as b7,Ar as b8,V0 as b9,Om as bA,Zi as bB,J5 as bC,K5 as bD,Y5 as bE,H6 as bF,U6 as bG,B6 as bH,q6 as bI,Z6 as bJ,e3 as bK,Y6 as bL,G6 as bM,K6 as bN,J6 as bO,W6 as bP,V6 as bQ,z6 as bR,Q6 as bS,fD as bT,A3 as bU,M3 as bV,D3 as bW,_3 as bX,R3 as bY,I3 as bZ,T3 as b_,Q5 as ba,X5 as bb,G0 as bc,kF as bd,J0 as be,wF as bf,n8 as bg,s8 as bh,Z5 as bi,e8 as bj,t8 as bk,i8 as bl,wv as bm,MF as bn,aa as bo,Jv as bp,H0 as bq,ks as br,ba as bs,pc as bt,vF as bu,Da as bv,ab as bw,EF as bx,Ys as by,nb as bz,it as c,NN as c$,TS as c0,$3 as c1,Vu as c2,AS as c3,RS as c4,IS as c5,MS as c6,E3 as c7,wc as c8,Vk as c9,x3 as cA,p3 as cB,v3 as cC,f3 as cD,y3 as cE,g3 as cF,b3 as cG,Dy as cH,wN as cI,k3 as cJ,kN as cK,j3 as cL,fi as cM,zi as cN,VF as cO,tD as cP,t3 as cQ,g5 as cR,Dj as cS,_6 as cT,hg as cU,r5 as cV,M6 as cW,R6 as cX,F6 as cY,O6 as cZ,$N as c_,Cr as ca,v5 as cb,y5 as cc,w5 as cd,k5 as ce,j5 as cf,N5 as cg,S5 as ch,x5 as ci,db as cj,tk as ck,I as cl,ec as cm,Do as cn,Er as co,x1 as cp,Cj as cq,Ej as cr,mN as cs,hN as ct,z5 as cu,m3 as cv,u3 as cw,B5 as cx,h3 as cy,w3 as cz,a5 as d,e5 as d$,Fi as d0,SN as d1,EN as d2,CN as d3,_N as d4,MN as d5,i3 as d6,o5 as d7,l5 as d8,c5 as d9,Xp as dA,I8 as dB,T8 as dC,X6 as dD,C5 as dE,_5 as dF,R5 as dG,M5 as dH,E5 as dI,A5 as dJ,I5 as dK,uu as dL,qm as dM,G3 as dN,J3 as dO,O0 as dP,dw as dQ,za as dR,Os as dS,qw as dT,T5 as dU,X3 as dV,Ho as dW,YT as dX,ma as dY,K3 as dZ,t5 as d_,sa as da,M8 as db,A8 as dc,b5 as dd,I6 as de,tu as df,js as dg,hD as dh,HL as di,VL as dj,WL as dk,pa as dl,Kd as dm,KL as dn,P6 as dp,A6 as dq,$6 as dr,T6 as ds,D6 as dt,L6 as du,Ua as dv,D8 as dw,FC as dx,Nc as dy,R8 as dz,s5 as e,tb as e0,V3 as e1,q3 as e2,O3 as e3,F3 as e4,_L as e5,Ra as e6,Q3 as e7,U3 as e8,B3 as e9,s3 as eA,Rk as eB,o3 as eC,l3 as eD,r3 as eE,dS as ea,H3 as eb,W3 as ec,P5 as ed,P0 as ee,z3 as ef,L3 as eg,bi as eh,C3 as ei,N3 as ej,S3 as ek,$5 as el,U5 as em,ru as en,V5 as eo,W5 as ep,q5 as eq,O5 as er,L5 as es,F5 as et,D5 as eu,H5 as ev,f5 as ew,_8 as ex,a3 as ey,n3 as ez,Ba as f,i5 as g,Ws as h,Ur as i,Bn as j,cc as k,G5 as l,_s as m,n1 as n,n5 as o,oi as p,CF as q,RL as r,yi as s,Gn as t,Mi as u,li as v,fs as w,kc as x,sl as y,Se as z};
|