@runfusion/fusion 0.7.1 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +3737 -1373
- package/dist/client/assets/{AgentDetailView-DyzuiJas.js → AgentDetailView-CLzxf6Z7.js} +3 -3
- package/dist/client/assets/{AgentDetailView-C1_lTTET.css → AgentDetailView-DIBOY8V-.css} +1 -1
- package/dist/client/assets/{AgentsView-CgweOTe6.js → AgentsView-CXaYJX_G.js} +3 -3
- package/dist/client/assets/{ChatView-DrY8FMIt.js → ChatView-iXxGAaN1.js} +1 -1
- package/dist/client/assets/DevServerView-BeXfFkF4.js +1 -0
- package/dist/client/assets/{DirectoryPicker-D5KQ-im_.js → DirectoryPicker-BMn5fjn9.js} +1 -1
- package/dist/client/assets/{DocumentsView-D2wK7FYJ.js → DocumentsView-CjrtI3TX.js} +1 -1
- package/dist/client/assets/{InsightsView-DfY3sa1j.js → InsightsView-BkfQ-TV1.js} +1 -1
- package/dist/client/assets/MemoryView-1G0zWu1i.js +2 -0
- package/dist/client/assets/{NodesView-g26-j7rg.js → NodesView-Bn_1R73N.js} +1 -1
- package/dist/client/assets/{NodesView-BYVG2yY-.css → NodesView-DCoS6iYh.css} +1 -1
- package/dist/client/assets/{PiExtensionsManager-DfMr3Gls.js → PiExtensionsManager-CqGOtQnR.js} +3 -3
- package/dist/client/assets/{PluginManager-DiMOD-Kj.js → PluginManager-CM5QGvSG.js} +1 -1
- package/dist/client/assets/{RoadmapsView-DJC4F4CD.js → RoadmapsView-B4VnQP83.js} +1 -1
- package/dist/client/assets/SettingsModal-BiLA-BeG.js +31 -0
- package/dist/client/assets/{SettingsModal-Cx3iMWDs.js → SettingsModal-C3LckzfT.js} +1 -1
- package/dist/client/assets/SettingsModal-D5hLoLXp.css +1 -0
- package/dist/client/assets/SetupWizardModal-Bk_8HfLm.js +1 -0
- package/dist/client/assets/SetupWizardModal-DRF5fOoR.css +1 -0
- package/dist/client/assets/{SkillsView-DTB2cmXQ.js → SkillsView-CRvqF8P1.js} +1 -1
- package/dist/client/assets/{TodoView-CyxdHUdz.js → TodoView-Vzui5Eha.js} +2 -2
- package/dist/client/assets/{folder-open-C3zB1vmh.js → folder-open-CMF89prE.js} +1 -1
- package/dist/client/assets/index-B8kH5y4Q.js +656 -0
- package/dist/client/assets/index-D2fXOwWF.css +1 -0
- package/dist/client/assets/{list-checks-CK3_6p5e.js → list-checks-M95d1uAy.js} +1 -1
- package/dist/client/assets/{star-BQhDgM9V.js → star-DHhJD6ow.js} +1 -1
- package/dist/client/assets/{upload-DDdZveEJ.js → upload-CEq8jic8.js} +1 -1
- package/dist/client/assets/{users-DWWgd19M.js → users-CUA8Tv-d.js} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/client/version.json +1 -1
- package/dist/extension.js +2403 -471
- package/dist/pi-claude-cli/index.ts +27 -0
- package/dist/pi-claude-cli/package.json +4 -5
- package/dist/pi-claude-cli/src/__tests__/process-manager.test.ts +31 -9
- package/dist/pi-claude-cli/src/__tests__/provider.test.ts +122 -8
- package/dist/pi-claude-cli/src/process-manager.ts +25 -7
- package/dist/pi-claude-cli/src/provider.ts +31 -7
- package/dist/pi-claude-cli/src/types/cross-spawn.d.ts +7 -0
- package/package.json +2 -6
- package/skill/fusion/references/extension-tools.md +1 -0
- package/dist/client/assets/DevServerView-fvjo36sF.js +0 -6
- package/dist/client/assets/MemoryView-CyAQgXwO.js +0 -2
- package/dist/client/assets/SettingsModal-BnekMOV2.css +0 -1
- package/dist/client/assets/SettingsModal-DjVE27r5.js +0 -31
- package/dist/client/assets/SetupWizardModal-BMa6p24b.css +0 -1
- package/dist/client/assets/SetupWizardModal-Cow6woq6.js +0 -1
- package/dist/client/assets/index-Belw0PQt.css +0 -1
- package/dist/client/assets/index-DJDWSrju.js +0 -646
|
@@ -0,0 +1,656 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-xterm-DzcZoU0P.js","assets/vendor-react-K0fH_qHe.js","assets/vendor-xterm-LZoznX6r.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/SetupWizardModal-Bk_8HfLm.js","assets/DirectoryPicker-BMn5fjn9.js","assets/folder-open-CMF89prE.js","assets/DirectoryPicker-DzKVmxOf.css","assets/SetupWizardModal-DRF5fOoR.css","assets/SettingsModal-BiLA-BeG.js","assets/SettingsModal-C3LckzfT.js","assets/SettingsModal-D5hLoLXp.css","assets/users-CUA8Tv-d.js","assets/star-DHhJD6ow.js","assets/SettingsModal-YjpwLH2V.css","assets/AgentsView-CXaYJX_G.js","assets/upload-CEq8jic8.js","assets/AgentsView-C2f7esMv.css","assets/DocumentsView-CjrtI3TX.js","assets/DocumentsView-BrhyOdeE.css","assets/InsightsView-BkfQ-TV1.js","assets/InsightsView-Egu71gmh.css","assets/NodesView-Bn_1R73N.js","assets/NodesView-DCoS6iYh.css","assets/ChatView-iXxGAaN1.js","assets/RoadmapsView-B4VnQP83.js","assets/RoadmapsView-BOYnyMCh.css","assets/SkillsView-CRvqF8P1.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-1G0zWu1i.js","assets/MemoryView-DiajLXby.css","assets/DevServerView-BeXfFkF4.js","assets/DevServerView-DlZpuAnj.css","assets/TodoView-Vzui5Eha.js","assets/list-checks-M95d1uAy.js","assets/TodoView-C1g65hJo.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as a,j as t,R as lo,a as Xa,g as $h,c as hg}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"]'))i(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"&&i(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 i(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 Dh=(...e)=>e.filter((n,s,i)=>!!n&&n.trim()!==""&&i.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 pg=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 fg=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(n,s,i)=>i?i.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 Cd=e=>{const n=fg(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 il={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 gg=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},xg=a.createContext({}),bg=()=>a.useContext(xg),vg=a.forwardRef(({color:e,size:n,strokeWidth:s,absoluteStrokeWidth:i,className:r="",children:o,iconNode:l,...c},u)=>{const{size:d=24,strokeWidth:m=2,absoluteStrokeWidth:h=!1,color:g="currentColor",className:p=""}=bg()??{},f=i??h?Number(s??m)*24/Number(n??d):s??m;return a.createElement("svg",{ref:u,...il,width:n??d??il.width,height:n??d??il.height,stroke:e??g,strokeWidth:f,className:Dh("lucide",p,r),...!o&&!gg(c)&&{"aria-hidden":"true"},...c},[...l.map(([x,v])=>a.createElement(x,v)),...Array.isArray(o)?o:[o]])});/**
|
|
33
|
+
* @license lucide-react v1.7.0 - ISC
|
|
34
|
+
*
|
|
35
|
+
* This source code is licensed under the ISC license.
|
|
36
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
37
|
+
*/const Ue=(e,n)=>{const s=a.forwardRef(({className:i,...r},o)=>a.createElement(vg,{ref:o,iconNode:n,className:Dh(`lucide-${pg(Cd(e))}`,`lucide-${e}`,i),...r}));return s.displayName=Cd(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 yg=[["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"}]],Cs=Ue("activity",yg);/**
|
|
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 kg=[["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"}]],Mo=Ue("archive",kg);/**
|
|
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 jg=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],xr=Ue("arrow-down",jg);/**
|
|
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 wg=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],wa=Ue("arrow-left",wg);/**
|
|
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 Ng=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],br=Ue("arrow-right",Ng);/**
|
|
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 Sg=[["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"}]],Lh=Ue("arrow-up-down",Sg);/**
|
|
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 Cg=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Li=Ue("arrow-up",Cg);/**
|
|
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 Eg=[["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"}]],_g=Ue("book-open",Eg);/**
|
|
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 Mg=[["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"}]],gn=Ue("bot",Mg);/**
|
|
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 Ag=[["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"}]],uc=Ue("box",Ag);/**
|
|
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 Rg=[["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"}]],co=Ue("brain",Rg);/**
|
|
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 Tg=[["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"}]],zh=Ue("calendar",Tg);/**
|
|
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 Pg=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],Ig=Ue("check-check",Pg);/**
|
|
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 $g=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Mn=Ue("check",$g);/**
|
|
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 Dg=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],qt=Ue("chevron-down",Dg);/**
|
|
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 Lg=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],Ao=Ue("chevron-left",Lg);/**
|
|
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 zg=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],hn=Ue("chevron-right",zg);/**
|
|
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 Fg=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],li=Ue("chevron-up",Fg);/**
|
|
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 Og=[["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"}]],Xn=Ue("circle-alert",Og);/**
|
|
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 Ug=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],dn=Ue("circle-check-big",Ug);/**
|
|
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 Bg=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],Ro=Ue("circle-dot",Bg);/**
|
|
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 Hg=[["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"}]],mc=Ue("circle-question-mark",Hg);/**
|
|
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 qg=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],Vg=Ue("circle-stop",qg);/**
|
|
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 Wg=[["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"}]],vr=Ue("circle-x",Wg);/**
|
|
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 Kg=[["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"}]],Gg=Ue("clipboard-list",Kg);/**
|
|
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 Jg=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],yi=Ue("clock",Jg);/**
|
|
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 Yg=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Fh=Ue("code",Yg);/**
|
|
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 Qg=[["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"}]],Xg=Ue("columns-3",Qg);/**
|
|
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 Zg=[["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"}]],Fi=Ue("copy",Zg);/**
|
|
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 ex=[["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"}]],tx=Ue("cpu",ex);/**
|
|
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 nx=[["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"}]],sx=Ue("download",nx);/**
|
|
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 ix=[["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"}]],ax=Ue("ellipsis-vertical",ix);/**
|
|
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 rx=[["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"}]],hc=Ue("ellipsis",rx);/**
|
|
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 ox=[["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"}]],lx=Ue("external-link",ox);/**
|
|
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 cx=[["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"}]],pc=Ue("eye-off",cx);/**
|
|
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 dx=[["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"}]],da=Ue("eye",dx);/**
|
|
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 ux=[["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"}]],Is=Ue("file-code",ux);/**
|
|
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 mx=[["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"}]],Oh=Ue("file-diff",mx);/**
|
|
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 hx=[["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"}]],px=Ue("file-minus",hx);/**
|
|
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 fx=[["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"}]],Uh=Ue("file-pen",fx);/**
|
|
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 gx=[["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"}]],xx=Ue("file-plus",gx);/**
|
|
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 bx=[["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"}]],vx=Ue("file-question-mark",bx);/**
|
|
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 yx=[["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"}]],Oi=Ue("file-text",yx);/**
|
|
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 kx=[["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"}]],jx=Ue("file-type",kx);/**
|
|
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 wx=[["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"}]],Bh=Ue("file",wx);/**
|
|
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 Nx=[["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"}]],fc=Ue("folder-git-2",Nx);/**
|
|
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 Sx=[["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"}]],Ed=Ue("folder-root",Sx);/**
|
|
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 Cx=[["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"}]],In=Ue("folder",Cx);/**
|
|
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 Ex=[["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"}]],uo=Ue("funnel",Ex);/**
|
|
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 _x=[["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"}]],Js=Ue("git-branch",_x);/**
|
|
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 Mx=[["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"}]],lr=Ue("git-commit-horizontal",Mx);/**
|
|
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 Ax=[["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"}]],Hh=Ue("git-merge",Ax);/**
|
|
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 Rx=[["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"}]],hs=Ue("git-pull-request",Rx);/**
|
|
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 Tx=[["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"}]],To=Ue("globe",Tx);/**
|
|
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 Px=[["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"}]],qh=Ue("grid-3x3",Px);/**
|
|
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 Ix=[["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"}]],Jc=Ue("grip-vertical",Ix);/**
|
|
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 $x=[["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"}]],Dx=Ue("hard-drive",$x);/**
|
|
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 Lx=[["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"}]],zx=Ue("heart",Lx);/**
|
|
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 Fx=[["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"}]],cr=Ue("history",Fx);/**
|
|
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 Ox=[["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"}]],Za=Ue("inbox",Ox);/**
|
|
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 Ux=[["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"}]],Vh=Ue("key",Ux);/**
|
|
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 Bx=[["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"}]],Hx=Ue("keyboard",Bx);/**
|
|
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 qx=[["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"}]],Ui=Ue("layers",qx);/**
|
|
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 Vx=[["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"}]],Bi=Ue("layout-grid",Vx);/**
|
|
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 Wx=[["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"}]],Ys=Ue("lightbulb",Wx);/**
|
|
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 Kx=[["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"}]],ua=Ue("link",Kx);/**
|
|
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 Gx=[["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"}]],Jx=Ue("list-plus",Gx);/**
|
|
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 Yx=[["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"}]],Po=Ue("list-tree",Yx);/**
|
|
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 Qx=[["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"}]],gc=Ue("list",Qx);/**
|
|
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 Xx=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],ot=Ue("loader-circle",Xx);/**
|
|
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 Zx=[["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"}]],Io=Ue("lock",Zx);/**
|
|
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 eb=[["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"}]],ma=Ue("mail",eb);/**
|
|
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 tb=[["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"}]],xc=Ue("map",tb);/**
|
|
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 nb=[["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"}]],$o=Ue("maximize-2",nb);/**
|
|
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 sb=[["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"}]],ib=Ue("message-square-plus",sb);/**
|
|
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 ab=[["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"}]],bi=Ue("message-square",ab);/**
|
|
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 rb=[["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"}]],yr=Ue("minimize-2",rb);/**
|
|
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 ob=[["path",{d:"M5 12h14",key:"1ays0h"}]],lb=Ue("minus",ob);/**
|
|
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 cb=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],dr=Ue("monitor",cb);/**
|
|
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 db=[["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"}]],ub=Ue("move",db);/**
|
|
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 mb=[["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"}]],bc=Ue("package",mb);/**
|
|
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 hb=[["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"}]],pb=Ue("paperclip",hb);/**
|
|
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 fb=[["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"}]],Gs=Ue("pause",fb);/**
|
|
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 gb=[["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"}]],Yn=Ue("pencil",gb);/**
|
|
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 xb=[["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"}]],xn=Ue("play",xb);/**
|
|
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 bb=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Zt=Ue("plus",bb);/**
|
|
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 vb=[["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"}]],Wh=Ue("radio",vb);/**
|
|
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 yb=[["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"}]],Nn=Ue("refresh-cw",yb);/**
|
|
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 kb=[["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"}]],_d=Ue("rocket",kb);/**
|
|
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 jb=[["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"}]],wb=Ue("rotate-ccw",jb);/**
|
|
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 Nb=[["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"}]],Sb=Ue("rotate-cw",Nb);/**
|
|
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 Cb=[["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"}]],Kh=Ue("save",Cb);/**
|
|
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 Eb=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],oa=Ue("search",Eb);/**
|
|
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 _b=[["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"}]],Di=Ue("send",_b);/**
|
|
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 Mb=[["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"}]],mo=Ue("server",Mb);/**
|
|
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 Ab=[["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"}]],sr=Ue("settings",Ab);/**
|
|
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 Rb=[["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"}]],Tb=Ue("shield-alert",Rb);/**
|
|
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 Pb=[["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"}]],Ib=Ue("shield",Pb);/**
|
|
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 $b=[["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"}]],Db=Ue("skull",$b);/**
|
|
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 Lb=[["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"}]],qn=Ue("sparkles",Lb);/**
|
|
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 zb=[["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"}]],Gh=Ue("square-check-big",zb);/**
|
|
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 Fb=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],ms=Ue("square",Fb);/**
|
|
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 Ob=[["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"}]],ls=Ue("target",Ob);/**
|
|
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 Ub=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],ri=Ue("terminal",Ub);/**
|
|
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 Bb=[["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"}]],ho=Ue("text-wrap",Bb);/**
|
|
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 Hb=[["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"}]],Xt=Ue("trash-2",Hb);/**
|
|
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 qb=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],Vb=Ue("trending-up",qb);/**
|
|
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 Wb=[["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"}]],Yc=Ue("triangle-alert",Wb);/**
|
|
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 Kb=[["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"}]],Md=Ue("unlink",Kb);/**
|
|
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 Gb=[["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"}]],Qi=Ue("user",Gb);/**
|
|
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 Jb=[["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"}]],Jh=Ue("webhook",Jb);/**
|
|
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 Yb=[["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"}]],vc=Ue("workflow",Yb);/**
|
|
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 Qb=[["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"}]],Xb=Ue("wrench",Qb);/**
|
|
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 Zb=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Ot=Ue("x",Zb);/**
|
|
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 ev=[["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"}]],Pn=Ue("zap",ev),yc="fusion:version-reload",kc="fusion:version-update";function tv(){try{if(sessionStorage.getItem(kc))return sessionStorage.removeItem(kc),!0}catch{}return!1}function Yh(e){if(sessionStorage.getItem(yc)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}sessionStorage.setItem(yc,"1"),console.info("[versionCheck] reloading:",e),window.location.reload()}function nv(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return/Failed to fetch dynamically imported module|error loading dynamically imported module|Importing a module script failed|is not a valid JavaScript MIME type|ChunkLoadError/i.test(n)}function sv(e){return nv(e)?(Yh(`chunk load error: ${e?.message??e}`),!0):!1}async function iv(){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}}let al=!1;async function rl(){if(!(al||document.visibilityState!=="visible")){al=!0;try{const e=await iv();if(e&&e!=="mojjkega-50ad5fc1"){try{sessionStorage.setItem(kc,"1")}catch{}Yh(`build version changed: mojjkega-50ad5fc1 -> ${e}`)}}finally{al=!1}}}function av(){window.setTimeout(()=>sessionStorage.removeItem(yc),5e3),document.addEventListener("visibilitychange",()=>{rl()}),window.addEventListener("focus",()=>{rl()}),window.setTimeout(()=>void rl(),2e3)}class Do extends a.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),!sv(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",i=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(Yc,{size:40})}),t.jsx("div",{className:"error-boundary__title",children:i}),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 Jn({children:e,onError:n}){return t.jsx(Do,{level:"page",onError:n,children:e})}function Ti({children:e,onError:n}){return t.jsx(Do,{level:"modal",onError:n,children:e})}function rv({children:e,onError:n}){return t.jsx(Do,{level:"root",onError:n,children:e})}const ov="modulepreload",lv=function(e){return"/"+e},Ad={},nn=function(n,s,i){let r=Promise.resolve();if(s&&s.length>0){let l=function(d){return Promise.all(d.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]"),u=c?.nonce||c?.getAttribute("nonce");r=l(s.map(d=>{if(d=lv(d),d in Ad)return;Ad[d]=!0;const m=d.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${h}`))return;const g=document.createElement("link");if(g.rel=m?"stylesheet":ov,m||(g.as="script"),g.crossOrigin="",g.href=d,u&&g.setAttribute("nonce",u),document.head.appendChild(g),m)return new Promise((p,f)=>{g.addEventListener("load",p),g.addEventListener("error",()=>f(new Error(`Unable to preload CSS for ${d}`)))})}))}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)})},Qc="fn.authToken",Rd="token",cv="fn_token";let la,Td=!1,po=!1;const jc="fn:auth-token-recovery-required";function dv(){try{const e=window.localStorage.getItem(Qc);return e&&e.length>0?e:void 0}catch{return}}function Qh(e){try{window.localStorage.setItem(Qc,e)}catch{}}function uv(){if(!(Td||typeof window>"u")){Td=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(Rd);if(!n)return;Qh(n),e.searchParams.delete(Rd);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function ha(){if(la!==void 0)return la;const e=uv();if(e)return la=e,e;const n=dv();if(n)return la=n,n}function mv(e){la=e,po=!1,Qh(e)}function hv(){la=void 0,po=!1;try{window.localStorage.removeItem(Qc)}catch{}}function Pd(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function pv(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function fv(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!pv(e.protocol))return!1;const s=e.hostname===n.hostname,i=e.port===n.port,r=Pd(e.protocol)===Pd(n.protocol);return s&&i&&r}function gv(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 Qs(e){const n=ha();if(!n||typeof window>"u")return e;const s=gv(e);return!s||!fv(s.parsed)?e:(s.parsed.searchParams.set(cv,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function ki(e){const n=ha();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function xv(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function bv(){typeof window>"u"||po||(po=!0,window.dispatchEvent(new CustomEvent(jc)))}async function vv(e){if(e.status===401)try{const n=e.clone();if(!(n.headers.get("content-type")??"").toLowerCase().includes("application/json"))return;const i=await n.json();xv(i)&&bv()}catch{}}function yv(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,ha();const e=window.fetch.bind(window);window.fetch=function(s,i){const r=ha(),o=typeof s=="string"?s:s instanceof URL?s.toString():s.url;if(!(()=>{try{const u=new URL(o,window.location.origin);return u.origin!==window.location.origin?!1:u.pathname.startsWith("/api/")||u.pathname==="/api"}catch{return o.startsWith("/api/")||o==="/api"}})())return e(s,i);const c=new Headers(i?.headers??(s instanceof Request?s.headers:void 0));return r&&!c.has("Authorization")&&c.set("Authorization",`Bearer ${r}`),e(s,{...i,headers:c}).then(u=>(vv(u),u))}}class kv extends Error{status;details;constructor(n,s,i){super(n),this.name="ApiRequestError",this.status=s,this.details=i}}function jv(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function Zn(e){return`/api${e}`}async function L(e,n={}){const s=Zn(e),i=ha(),r=(()=>{if(i){const g=new Headers(n.headers??{});return g.has("Content-Type")||g.set("Content-Type","application/json"),ki(g)}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(),u=l.includes("application/json");if(l.includes("text/html")||jv(c))throw new Error(`API returned HTML instead of JSON for ${s}. The endpoint may not be properly configured. (${o.status} ${o.statusText})`);if(!u){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 kv(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function UP(){return L("/health")}function BP(){return L("/updates/check")}function wv(e,n,s,i,r){const o=new URLSearchParams;s&&o.set("projectId",s),i&&o.set("q",i),r&&o.set("includeArchived","1");const l=o.size>0?`?${o.toString()}`:"";return L(`/tasks${l}`)}async function fo(e,n){const i=Zn(K(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(i,{headers:ki({"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 Xh(e,n){const{title:s,description:i,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:u,modelPresetId:d,modelProvider:m,modelId:h,validatorModelProvider:g,validatorModelId:p,planningModelProvider:f,planningModelId:x,thinkingLevel:v,summarize:b,reviewLevel:y,executionMode:S,priority:k}=e;return L(K("/tasks",n),{method:"POST",body:JSON.stringify({title:s,description:i,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:u,modelPresetId:d,modelProvider:m,modelId:h,validatorModelProvider:g,validatorModelId:p,planningModelProvider:f,planningModelId:x,thinkingLevel:v,summarize:b,reviewLevel:y,executionMode:S,priority:k})})}function Ks(e,n,s){return L(K(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Nv(e,n,s,i,r,o,l,c,u){return L(K("/tasks/batch-update-models",u),{method:"POST",body:JSON.stringify({taskIds:e,modelProvider:n,modelId:s,validatorModelProvider:i,validatorModelId:r,planningModelProvider:o,planningModelId:l,nodeId:c})})}function Sv(e,n,s){return L(K(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n})})}function Cv(e,n,s){const i=new URLSearchParams,r=i.size>0?`?${i.toString()}`:"";return L(K(`/tasks/${e}${r}`,n),{method:"DELETE"})}function Ev(e,n){return L(K(`/tasks/${e}/merge`,n),{method:"POST"})}function _v(e,n){return L(K(`/tasks/${e}/retry`,n),{method:"POST"})}function Mv(e,n){return L(K(`/tasks/${e}/duplicate`,n),{method:"POST"})}function Zh(e,n){return L(K(`/tasks/${e}/pause`,n),{method:"POST"})}function Av(e,n){return L(K(`/tasks/${e}/unpause`,n),{method:"POST"})}function Rv(e,n){return L(K(`/tasks/${e}/archive`,n),{method:"POST"})}function Tv(e,n){return L(K(`/tasks/${e}/unarchive`,n),{method:"POST"})}function Pv(e){return L(K("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function Iv(e,n){return L(K(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function $v(e,n){return L(K(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function Dv(e){return L(K("/config",e))}function Lo(e){return L(K("/settings",e))}function zr(e,n){return L(K("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function Lv(e){return L(K("/update-check",e))}function HP(e){return L(K("/remote/settings",e))}function qP(e,n){return L(K("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function VP(e){return L(K("/remote/status",e))}function WP(e){return L(K("/remote/tunnel/start",e),{method:"POST"})}function KP(e){return L(K("/remote/tunnel/stop",e),{method:"POST"})}function GP(e){return L(K("/remote/token/persistent/regenerate",e),{method:"POST"})}function JP(e,n){return L(K("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function ep(e,n,s){const i=new URLSearchParams;e&&i.set("format",e),i.set("tokenType",n),n==="short-lived"&&typeof s=="number"&&Number.isFinite(s)&&i.set("ttlMs",String(s));const r=i.toString();return r?`?${r}`:""}function YP(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:i}=e,r=ep(null,s,i);return L(K(`/remote/url${r}`,n))}function QP(e="text",n={}){const{projectId:s,tokenType:i="persistent",ttlMs:r}=n,o=ep(e,i,r);return L(K(`/remote/qr${o}`,s))}function XP(e){return L(K("/memory",e))}function ZP(e,n){return L(K("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function eI(e){return L(K("/memory/files",e))}function tI(e,n){const s=`path=${encodeURIComponent(e)}`;return L(K(`/memory/file?${s}`,n))}function nI(e,n,s){return L(K("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function sI(e,n){let s,i=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:i=r}return L(K("/memory/compact",i),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function iI(e){return L(K("/memory/dream",e),{method:"POST"})}function aI(e){return L(K("/memory/insights",e))}function rI(e,n){return L(K("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function oI(e){return L(K("/memory/extract",e),{method:"POST"})}function lI(e){return L(K("/memory/audit",e))}function cI(e){return L(K("/memory/stats",e))}function dI(e){return L(K("/memory/backend",e))}function uI(e){return L(K("/memory/install-qmd",e),{method:"POST"})}function mI(e,n){return L(K("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function Vi(){return L("/settings/global")}function sn(e){return L("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function hI(e){return L(K("/settings/scopes",e))}function pI(e){return L(K("/settings/pi-extensions",e))}function fI(e,n){return L(K("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function gI(e,n,s){return L(K("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function xI(){return L("/pi-settings")}async function bI(e){return L("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function vI(e){return L("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function yI(e){return L(K("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function ur(e,n,s){const i=new FormData;i.append("file",n);const r=await fetch(Zn(K(`/tasks/${e}/attachments`,s)),{method:"POST",headers:ki(),body:i}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function zv(e,n,s){return L(K(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function Id(e,n,s){const i=new URLSearchParams;s?.limit!==void 0&&i.set("limit",String(s.limit)),s?.offset!==void 0&&i.set("offset",String(s.offset));const r=i.toString()?`?${i.toString()}`:"",o=K(`/tasks/${e}/logs${r}`,n),l=await fetch(Zn(o),{headers:ki()});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(),u=l.headers.has("X-Total-Count")?parseInt(l.headers.get("X-Total-Count"),10):c.length,d=l.headers.has("X-Has-More")?l.headers.get("X-Has-More")==="true":!1;return{entries:c,total:u,hasMore:d}}function Fv(e,n,s,i){return L(K(`/tasks/${e}/comments/${n}`,i),{method:"PATCH",body:JSON.stringify({text:s})})}function Ov(e,n,s){return L(K(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function Uv(e,n){return L(K(`/tasks/${e}/documents`,n))}function Bv(e,n,s){return L(K(`/tasks/${e}/documents/${n}/revisions`,s))}async function kI(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 i=s.toString(),r=`/documents${i?`?${i}`:""}`;return L(K(r,n))}function jI(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const i=s.toString(),r=`/files/markdown-list${i?`?${i}`:""}`;return L(K(r,e))}function $d(e,n,s,i,r){return L(K(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:i?.author,metadata:i?.metadata})})}function Hv(e,n,s){return L(K(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function qv(e,n,s){return L(K(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function Vv(e,n,s){return L(K(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Wv(e,n){return L(K(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function Kv(e,n,s){return L(K(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function cs(){return L("/models")}function Gv(){return L("/usage")}function Jv(){return L("/providers/claude-cli/status")}async function wI(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return L(`/providers/hermes/status${n}`)}async function NI(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await L(`/providers/hermes/profiles${n}`)).profiles??[]}async function SI(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return L(`/providers/openclaw/status${n}`)}async function CI(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),L(`/providers/paperclip/status?${n.toString()}`)}async function EI(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),(await L(`/providers/paperclip/companies?${n.toString()}`)).companies??[]}async function _I(e){const n=new URLSearchParams({apiUrl:e.apiUrl,companyId:e.companyId});return e.apiKey&&n.set("apiKey",e.apiKey),(await L(`/providers/paperclip/agents?${n.toString()}`)).agents??[]}async function MI(e){return L("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function AI(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return L(`/providers/paperclip/cli-status${s?`?${s}`:""}`)}async function RI(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 L(`/providers/paperclip/cli-companies${s?`?${s}`:""}`)).companies??[]}async function TI(e){const n=new URLSearchParams({companyId:e.companyId});return e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath),(await L(`/providers/paperclip/cli-agents?${n.toString()}`)).agents??[]}async function PI(e={}){const n=new URLSearchParams;e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return L(`/providers/paperclip/cli-discovery${s?`?${s}`:""}`)}function Yv(e){return L("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function mr(){return L("/auth/status")}function Qv(e){return L("/auth/login",{method:"POST",body:JSON.stringify({provider:e})})}function Xv(e){return L("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function Zv(e,n){return L("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function ey(e){return L("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function ty(e,n,s,i){return L("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:i})})}function ny(e,n,s,i){return L(K("/github/issues/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function sy(e,n,s){return L("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function iy(e,n,s,i){return L(K("/github/pulls/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function ay(e){return L(K("/git/remotes",e))}function ry(e){return L(K("/git/remotes/detailed",e))}function oy(e,n,s){return L(K("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function ly(e,n){return L(K(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function cy(e,n,s){return L(K(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function dy(e,n,s){return L(K(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function uy(e,n,s){return L(K(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function my(e,n){return L(K(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function hy(e,n){return(await L(K("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function Fr(e,n,s,i){return L(K("/terminal/sessions",i),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function Dd(e,n){return L(K(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function py(e){return L(K("/terminal/sessions",e))}function Ps(e){return L(K("/git/status",e))}function fy(e,n){const s=e?`?limit=${e}`:"";return L(K(`/git/commits${s}`,n))}function go(e,n){return L(K(`/git/commits/${e}/diff`,n))}function gy(e){return L(K("/git/commits/ahead",e))}function xy(e,n,s,i){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return L(K(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,i))}function Pa(e){return L(K("/git/branches",e))}function by(e,n,s){const i=`?limit=${n}`;return L(K(`/git/branches/${encodeURIComponent(e)}/commits${i}`,s))}function vy(e){return L(K("/git/worktrees",e))}function yy(e,n,s){return L(K("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function ky(e,n){return L(K(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function Ld(e,n,s){const i=n?"?force=true":"";return L(K(`/git/branches/${encodeURIComponent(e)}${i}`,s),{method:"DELETE"})}function jy(e,n){return L(K("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function wy(e){return L(K("/git/pull",e),{method:"POST"})}function Ny(e){return L(K("/git/push",e),{method:"POST"})}function Or(e){return L(K("/git/stashes",e))}function Sy(e,n){return L(K("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function Cy(e,n,s){return L(K(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function Ey(e,n){return L(K(`/git/stashes/${e}`,n),{method:"DELETE"})}function _y(e,n,s){const i=new URLSearchParams;return i.set("path",e),i.set("staged",String(n)),L(K(`/git/diff/file?${i.toString()}`,s))}function Xi(e){return L(K("/git/changes",e))}function zd(e,n){return L(K("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function My(e,n){return L(K("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function Fd(e,n){return L(K("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function Ay(e,n){return L(K("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function Ry(e){return L(K("/workspaces",e))}function Ty(e,n,s){const i=new URLSearchParams({workspace:e});return n&&i.set("path",n),s&&i.set("projectId",s),L(`/files?${i.toString()}`)}function Py(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),L(`/files/${encodeURIComponent(n)}?${i.toString()}`)}function Iy(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),L(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function $y(e,n,s){const i=new URLSearchParams({q:e});return n&&i.set("workspace",n),s&&i.set("projectId",s),L(`/files/search?${i.toString()}`)}function Dy(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),L(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function Ly(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),L(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function zy(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),L(`/files/${encodeURIComponent(n)}/delete?${i.toString()}`,{method:"POST"})}function Fy(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),L(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function tp(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${i.toString()}`}function Oy(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${i.toString()}`}function Uy(e,n,s){return L(K("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function By(e,n,s,i){return L(K("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Hy(e,n,s){return L(K(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function qy(e,n,s){return L(K(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function np(e,n,s){return L(K("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function Vy(e,n,s){return L(K("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Wy(e,n,s){return L(K("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Ky(e,n,s){return L(K("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const wc=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(wc))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function Gy(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function kr(e,n,s={}){const i=s.maxReconnectAttempts??10;let r=null,o=!1,l=0,c=null,u=null,d=!1;const m=p=>{const f=p.lastEventId;if(!f)return!0;const x=Number.parseInt(f,10);return Number.isFinite(x)?u!==null&&x<=u?!1:(u=x,!0):!0},h=()=>{if(o)return;const p=Gy(e,u),f=new EventSource(Qs(p));r=f,f.onopen=()=>{l=0,d=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},f.onmessage=x=>{const v=x;m(v)&&n.onMessage?.(v)};for(const[x,v]of Object.entries(n.events??{}))f.addEventListener(x,b=>{const y=b;m(y)&&v(y)});f.onerror=()=>{if(o||r!==f)return;if(f.readyState===EventSource.CONNECTING){d||(d=!0,s.onConnectionStateChange?.("reconnecting"));return}if(f.close(),l>=i){s.onFatalError?.("Connection lost");return}d=!0,s.onConnectionStateChange?.("reconnecting"),l+=1;const v=Math.min(1e3*2**(l-1),3e4);c=setTimeout(()=>{c=null,h()},v)}};h();const g={close:()=>{o=!0,c&&(clearTimeout(c),c=null),r?.close(),wc.delete(g)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return wc.add(g),g}function Od(e){const n=typeof e.source=="string"&&e.source.trim().length>0?e.source.trim():"root",s=n==="root"?".":n,i=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:i,packagePath:r,confidence:o,cwd:s,source:n,workspaceName:typeof e.packageName=="string"?e.packageName:void 0,label:`${c} · ${i} (${l})`}}function pa(e){const n=e.status,s=n==="starting"||n==="running"||n==="failed"||n==="stopped"?n:"stopped",i=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:i,detectedUrl:typeof e.detectedUrl=="string"?e.detectedUrl:i,detectedPort:e.detectedPort,manualPreviewUrl:r,manualUrl:typeof e.manualUrl=="string"?e.manualUrl:r,logs:Array.isArray(e.logHistory)?e.logHistory:[],exitCode:e.exitCode}}function Jy(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 Yy(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((i,r)=>Jy(i,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function Qy(e,n){const s=typeof n.maxLines=="number"&&Number.isFinite(n.maxLines)?Math.max(1,Math.floor(n.maxLines)):100,i=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((d,m)=>({id:m+1,text:d,stream:"stdout",timestamp:""}));if(r!==null)return{lines:l.filter(d=>d.id>r).slice(0,s),totalLines:o};const c=Math.max(o-i,0),u=Math.max(c-s,0);return{lines:l.slice(u,c),totalLines:o}}function Ud(e){return Array.isArray(e)?e.map(Od):(e.candidates??[]).map(Od)}async function Xy(e){try{const n=await L(K("/dev-server/candidates",e));return Ud(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await L(K("/dev-server/detect",e));return Ud(s)}throw n}}function Xc(e){return L(K("/dev-server/status",e)).then(pa)}async function II(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 i=s.size>0?`?${s.toString()}`:"";try{const r=await L(K(`/dev-server/logs/history${i}`,n));return Yy(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await Xc(n);return Qy(o.logs,e)}throw r}}function Zy(e,n){const s=e.cwd??e.packagePath??".",i=e.scriptName;return L(K("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:i,scriptId:i,cwd:s,packagePath:e.packagePath})}).then(pa)}function ek(e){return L(K("/dev-server/stop",e),{method:"POST"}).then(pa)}function tk(e){return L(K("/dev-server/restart",e),{method:"POST"}).then(pa)}async function nk(e,n){const s=typeof e=="string"?{url:e}:e;try{const i=await L(K("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return pa(i)}catch(i){if(i instanceof Error&&/\/dev-server\/preview-url/.test(i.message)){const r=await L(K("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return pa(r)}throw i}}function $I(e){return Zn(K("/dev-server/logs/stream",e))}async function DI(e){try{return(await L(K("/devserver",e))).sessions??[]}catch{try{const n=await Xc(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(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}]}catch{return[]}}}async function LI(e,n){try{return await L(K(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await Xc(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(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}:null}catch{return null}}}async function zI(e,n){try{return await L(K(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await Zy({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(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}}async function FI(e,n){try{return await L(K(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await ek(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(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}}async function OI(e,n){try{return await L(K(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await tk(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(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}}async function UI(e,n,s){try{const i=await L(K(`/devserver/${encodeURIComponent(e)}/preview`,s),{method:"POST",body:JSON.stringify({url:n})});return{url:i.url??null,source:i.source??null}}catch{const i=await nk({url:n},s);return{url:i.previewUrl??i.manualUrl??null,source:"manual"}}}async function BI(e){try{return(await L(K("/devserver/detect",e))).candidates??[]}catch{try{return(await Xy(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function HI(e,n){return Zn(K(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function jr(e,n,s=25e3){const i=setInterval(()=>{Dj(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(i)}}}function sk(e,n){return Zn(K(`/planning/${encodeURIComponent(e)}/stream`,n))}function ik(e,n,s,i){const r=sk(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},u=kr(r,{onOpen:()=>{c(),o=jr(e,n)},onMessage:d=>{d.data.startsWith(":")},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},question:d=>{try{s.onQuestion?.(JSON.parse(d.data))}catch(m){console.error("[planning] Failed to parse question event:",m)}},summary:d=>{try{s.onSummary?.(JSON.parse(d.data))}catch(m){console.error("[planning] Failed to parse summary event:",m)}},error:d=>{try{const m=JSON.parse(d.data);s.onError?.(m.message||m)}catch{s.onError?.(d.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{c(),s.onError?.(d)}});return l={close:()=>{c(),u.close()},isConnected:u.isConnected},l}function wr(e,n){const s=new URLSearchParams;n?.scope&&s.set("scope",n.scope),n?.projectId&&s.set("projectId",n.projectId);const i=s.toString();return i?`${e}?${i}`:e}function ak(e){return L(wr("/routines",e))}function rk(e,n){return L(wr("/routines",n),{method:"POST",body:JSON.stringify(e)})}function Bd(e,n,s){return L(wr(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function ok(e,n){await L(wr(`/routines/${e}`,n),{method:"DELETE"})}function lk(e,n){return L(wr(`/routines/${e}/trigger`,n),{method:"POST"})}function Hd(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 L(`/activity${s}`)}function ck(e){const n=K("/activity",e);return L(n,{method:"DELETE"})}function zo(e){return L(K("/workflow-steps",e))}function qd(e,n){return L(K("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function dk(e,n,s){return L(K(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function uk(e,n){return L(K(`/workflow-steps/${e}`,n),{method:"DELETE"})}function Vd(e,n){return L(K(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function mk(e,n){return L(K(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function hk(){return L("/workflow-step-templates")}function pk(e,n){return L(K(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function hr(e){return L(K("/scripts",e))}function fk(e,n,s){return L(K("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function gk(e,n){return L(K(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function sp(e,n,s){return(await L(K("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const Ur={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 ip(e){if(!(e instanceof Error))return Ur.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?Ur.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?Ur.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:Ur.NETWORK}function xk(e,n){return L(K("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function bk(e,n,s){return L(K(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function vk(e,n){return Zn(K(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function yk(e,n,s,i){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=kr(vk(e,n),{onOpen:()=>{l(),r=jr(e,n)},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},subtasks:u=>{try{s.onSubtasks?.(JSON.parse(u.data))}catch(d){console.error("[subtasks] Failed to parse subtasks event:",d)}},error:u=>{try{const d=JSON.parse(u.data),m=typeof d=="string"&&d.length>0?d:null;s.onError?.(m||"Stream error")}catch{s.onError?.("Stream error")}o?.close()},complete:()=>{s.onComplete?.(),o?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{l(),s.onError?.(u)}});return o={close:()=>{l(),c.close()},isConnected:c.isConnected},o}function kk(e,n,s,i){return L(K("/subtasks/create-tasks",i),{method:"POST",body:JSON.stringify({sessionId:e,parentTaskId:s,subtasks:n.map(r=>({tempId:r.id,title:r.title,description:r.description,size:r.suggestedSize,dependsOn:r.dependsOn}))})})}function ap(e,n,s){return L(K("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function K(e,n){if(!n)return e;const s=e.includes("?")?"&":"?";return`${e}${s}projectId=${encodeURIComponent(n)}`}function jk(e,n,s){if(!n||n===s)return e;const i="/api",r=e.startsWith(i)?e.slice(i.length):e;return`/proxy/${encodeURIComponent(n)}${r}`}function Fo(e,n){const{nodeId:s,localNodeId:i,...r}=n??{},o=jk(e,s,i);return L(o,r)}function Na(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 i=s.size>0?`?${s.toString()}`:"";return L(`/agents${i}`)}function rp(e,n){return L(K(`/agents/${encodeURIComponent(e)}`,n))}function wk(e,n){return L(K("/agents",n),{method:"POST",body:JSON.stringify(e)})}function Nk(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function qI(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function VI(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function WI(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function KI(e,n){return L(K(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function GI(e,n,s){const i=`path=${encodeURIComponent(n)}`;return L(K(`/agents/${encodeURIComponent(e)}/memory/file?${i}`,s))}function JI(e,n,s,i){return L(K(`/agents/${encodeURIComponent(e)}/memory/file`,i),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function Sk(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function Ck(e,n){return L(K(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function YI(e,n,s){const i=new URLSearchParams;i.set("limit",String(n)),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return L(`/agents/${encodeURIComponent(e)}/runs${r}`)}function QI(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function XI(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function ZI(e,n,s){const i=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return L(K(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:i,triggerDetail:r})})}function e$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function Ek(e){return L(K("/agents/stats",e))}function t$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function n$(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const i=s.toString();return L(`/agents/org-tree${i?`?${i}`:""}`)}function s$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function Wd(e,n,s){return L(K(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function i$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/tasks`,n))}function a$(){return L("/agents/companies")}function r$(e,n){return L(K("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function o$(e,n){return L(K("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function l$(e,n){return L(K(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function c$(e){return L(K("/backups",e))}function d$(e){return L(K("/backups",e),{method:"POST"})}function u$(e,n){const s=K("/settings/export",n),i=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return L(i)}function m$(e,n,s){return L(K("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function Kd(){return L("/projects/across-nodes")}function ir(e,n){L("/_perf/dashboard-load",{method:"POST",body:JSON.stringify({source:e,message:n})}).catch(()=>{})}function xo(){return L("/nodes")}function _k(e){return L("/nodes",{method:"POST",body:JSON.stringify(e)})}function Mk(e,n){return L(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function Ak(e){return L(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Rk(e){const n=await L(`/nodes/${encodeURIComponent(e)}/health-check`,{method:"POST"});return{nodeId:n.nodeId??e,status:n.status,responseTimeMs:n.responseTimeMs,error:n.error,checkedAt:n.checkedAt??new Date().toISOString()}}function h$(e,n,s,i){const r=s&&s!==i?s:void 0,o=new URLSearchParams;e&&o.set("path",e),n&&o.set("showHidden","true"),r&&o.set("nodeId",r);const l=ha();l&&o.set("fn_token",l);const c=o.toString(),u=`/browse-directory${c?`?${c}`:""}`;return L(u)}function Tk(e){return L("/projects",{method:"POST",body:JSON.stringify(e)})}function op(e){return L(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function Gd(e){return L(`/projects/${encodeURIComponent(e)}/health`)}function Pk(e){return L(K("/executor/stats",e))}function Ik(e){return L(K("/system-stats",e))}function $k(e){return L(K("/kill-vitest",e),{method:"POST"})}function Jd(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 L(`/activity-feed${s}`)}function Dk(e){return L(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function Lk(e){return L(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function p$(){return L("/global-concurrency")}function f$(e){return L("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function zk(e,n){return L(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function lp(e,n,s){const i=new URLSearchParams;n&&i.set("worktree",n),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return L(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function Fk(e){return L(K("/missions",e))}function Ok(e,n){return L(K("/missions",n),{method:"POST",body:JSON.stringify(e)})}function cp(e,n){return L(K(`/missions/${encodeURIComponent(e)}`,n))}function Uk(e,n,s){return L(K(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Bk(e,n){return L(K(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Hk(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset));const r=i.size>0?`?${i.toString()}`:"";return L(K(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function qk(e){return L(K("/missions/health",e))}function Vk(e,n,s){return L(K(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function Wk(e,n,s){return L(K(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Kk(e,n){return L(K(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Gk(e,n,s){return L(K(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function Jk(e,n,s){return L(K(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Yk(e,n){return L(K(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Qk(e,n){return L(K(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function Xk(e,n,s){return L(K(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function Zk(e,n,s){return L(K(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function ej(e,n){return L(K(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function tj(e,n,s){return L(K(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function nj(e,n){return L(K(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function sj(e,n,s,i){return L(K(`/missions/features/${encodeURIComponent(e)}/triage`,i),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function ij(e,n){return L(K(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST"})}function ol(e,n){return L(K(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function aj(e,n,s){return L(K(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function rj(e,n,s){return L(K(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function oj(e,n,s){return L(K(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function lj(e,n,s){return L(K(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function cj(e,n){return L(K(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function ll(e,n){return L(K(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function Yd(e,n){return L(K(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function dj(e,n){return L(K(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function Qd(e,n){return L(K(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function uj(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset));const r=i.size>0?`?${i.toString()}`:"";return L(K(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function mj(e,n){return L(K(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function hj(e,n){return L(K(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function pj(e,n){return L(K(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function fj(e,n){return L(K(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function gj(e,n,s){return L(K(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function xj(e,n,s){return L(K("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function bj(e,n,s,i){return L(K("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function vj(e,n,s){return L(K(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function dp(e,n,s){return L(K("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function yj(e,n,s){return L(K("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function kj(e,n,s,i){const r=Zn(K(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=kr(r,{onOpen:()=>{c(),o=jr(e,n)},onMessage:d=>{d.data.startsWith(":")},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},question:d=>{try{s.onQuestion?.(JSON.parse(d.data))}catch(m){console.error("[mission-interview] Failed to parse question event:",m)}},summary:d=>{try{s.onSummary?.(JSON.parse(d.data))}catch(m){console.error("[mission-interview] Failed to parse summary event:",m)}},error:d=>{try{const m=JSON.parse(d.data);s.onError?.(m.message||m)}catch{s.onError?.(d.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{c(),s.onError?.(d)}});return l={close:()=>{c(),u.close()},isConnected:u.isConnected},l}function Nr(e,n,s){return K(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function Sr(e,n,s){return K(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function jj(e,n){return L(Nr(e,"/start",n),{method:"POST"})}function wj(e,n,s,i){return L(Nr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Nj(e,n,s,i){const r=Zn(Nr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=kr(r,{onOpen:()=>{c(),o=jr(e,n)},onMessage:d=>{d.data.startsWith(":")},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},question:d=>{try{s.onQuestion?.(JSON.parse(d.data))}catch(m){console.error("[milestone-interview] Failed to parse question event:",m)}},summary:d=>{try{s.onSummary?.(JSON.parse(d.data))}catch(m){console.error("[milestone-interview] Failed to parse summary event:",m)}},error:d=>{try{const m=JSON.parse(d.data);s.onError?.(m.message||m)}catch{s.onError?.(d.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{c(),s.onError?.(d)}});return l={close:()=>{c(),u.close()},isConnected:u.isConnected},l}function Sj(e,n,s){return L(Nr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Cj(e,n){return L(Nr(e,"/skip",n),{method:"POST"})}function Ej(e,n){return L(Sr(e,"/start",n),{method:"POST"})}function _j(e,n,s,i){return L(Sr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Mj(e,n,s,i){const r=Zn(Sr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=kr(r,{onOpen:()=>{c(),o=jr(e,n)},onMessage:d=>{d.data.startsWith(":")},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},question:d=>{try{s.onQuestion?.(JSON.parse(d.data))}catch(m){console.error("[slice-interview] Failed to parse question event:",m)}},summary:d=>{try{s.onSummary?.(JSON.parse(d.data))}catch(m){console.error("[slice-interview] Failed to parse summary event:",m)}},error:d=>{try{const m=JSON.parse(d.data);s.onError?.(m.message||m)}catch{s.onError?.(d.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{c(),s.onError?.(d)}});return l={close:()=>{c(),u.close()},isConnected:u.isConnected},l}function Aj(e,n,s){return L(Sr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Rj(e,n){return L(Sr(e,"/skip",n),{method:"POST"})}async function Tj(e,n){try{return await L(K(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function g$(e){return L(K("/roadmaps",e))}function x$(e,n){return L(K("/roadmaps",n),{method:"POST",body:JSON.stringify(e)})}function b$(e,n){return L(K(`/roadmaps/${encodeURIComponent(e)}`,n))}function v$(e,n,s){return L(K(`/roadmaps/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function y$(e,n){return L(K(`/roadmaps/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function k$(e,n,s){return L(K(`/roadmaps/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function j$(e,n,s){return L(K(`/roadmaps/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function w$(e,n){return L(K(`/roadmaps/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function N$(e,n,s){return L(K(`/roadmaps/milestones/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function S$(e,n,s){return L(K(`/roadmaps/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function C$(e,n){return L(K(`/roadmaps/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function E$(e,n,s){return L(K(`/roadmaps/${encodeURIComponent(e)}/milestones/reorder`,s),{method:"POST",body:JSON.stringify({orderedMilestoneIds:n})})}function _$(e,n,s){return L(K(`/roadmaps/milestones/${encodeURIComponent(e)}/features/reorder`,s),{method:"POST",body:JSON.stringify({orderedFeatureIds:n})})}function M$(e,n,s,i){return L(K(`/roadmaps/features/${encodeURIComponent(e)}/move`,i),{method:"POST",body:JSON.stringify({targetMilestoneId:n,targetIndex:s})})}function A$(e,n){return L(K(`/roadmaps/${encodeURIComponent(e)}/handoff`,n))}function R$(e,n,s,i){return L(K(`/roadmaps/${encodeURIComponent(e)}/suggestions/milestones`,i),{method:"POST",body:JSON.stringify({goalPrompt:n.trim(),...s!==void 0?{count:s}:{}})})}function T$(e,n,s){return L(K(`/roadmaps/milestones/${encodeURIComponent(e)}/suggestions/features`,s),{method:"POST",body:JSON.stringify({...n?.prompt!==void 0?{prompt:n.prompt.trim()}:{},...n?.count!==void 0?{count:n.count}:{}})})}function P$(e){return L(K("/todos",e))}function I$(e,n){const s={title:e};return L(K("/todos",n),{method:"POST",body:JSON.stringify(s)})}function $$(e,n,s){const i={title:n};return L(K(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function D$(e,n){return L(K(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function L$(e,n,s){const i={text:n};return L(K(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(i)})}function z$(e,n,s){const i=n;return L(K(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function F$(e,n){return L(K(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function O$(e,n,s){return L(K(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function fa(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function Zc(e){const n=e?`?projectId=${encodeURIComponent(e)}`:"",s=await fetch(Zn(`/ai-sessions${n}`),{headers:ki()});return s.ok?(await s.json()).sessions??[]:[]}async function oi(e){const n=await fetch(Zn(`/ai-sessions/${encodeURIComponent(e)}`),{headers:ki()});return n.ok?n.json():null}async function Pj(e,n){const s=await L(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function Ij(e,n){return L(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function $j(e,n){return L(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function up(e){await fetch(Zn(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:ki()})}function Dj(e,n){return L(K(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function Lj(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 i=s.size>0?`?${s.toString()}`:"";return L(`/messages/inbox${i}`)}function zj(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 i=s.size>0?`?${s.toString()}`:"";return L(`/messages/outbox${i}`)}function mp(e){return L(K("/messages/unread-count",e))}function Fj(e,n){return L(K("/messages",n),{method:"POST",body:JSON.stringify(e)})}function Oj(e,n){return L(K(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function Uj(e){return L(K("/messages/read-all",e),{method:"POST"})}function Bj(e,n){return L(K(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Hj(e,n,s){const i=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return L(K(i,s))}function qj(e,n){return L(K(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function U$(e,n,s){const i=new URLSearchParams;i.set("limit",String(n)),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return L(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function B$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function H$(e,n,s){const i=new URLSearchParams;s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return L(`/agents/${encodeURIComponent(e)}/performance${r}`)}function q$(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.category&&i.set("category",n.category),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return L(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function V$(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function W$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function K$(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function G$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/budget`,n))}function J$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function Y$(e){return L(K("/plugins",e))}async function Q$(e,n){return L(K("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function X$(e,n){return L(K(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function Z$(e,n){return L(K(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function eD(e,n){return L(K(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function tD(e,n){return L(K(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function nD(e,n,s){return L(K(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function sD(e,n){return L(K(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function Vj(e){return L(K("/plugins/ui-slots",e))}async function iD(e){return L(K("/plugins/runtimes",e))}async function aD(e){return(await L(K("/skills/discovered",e))).skills}async function rD(e,n,s){return L(K("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function oD(e,n,s){const i=new URLSearchParams;e&&i.set("q",e),i.set("limit",String(n));const r=i.size>0?`?${i.toString()}`:"";return L(K(`/skills/catalog${r}`,s))}async function lD(e,n){return(await L(K(`/skills/${encodeURIComponent(e)}/content`,n))).content}function cD(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const i=s.toString();return L(`/chat/sessions${i?`?${i}`:""}`)}async function Wj(e,n){const s=e.agentId.trim();if(!s)throw new Error("agentId is required");const i=e.modelProvider?.trim(),r=e.modelId?.trim();if(i&&!r||!i&&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),i&&r&&(o.set("modelProvider",i),o.set("modelId",r)),{session:(await L(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function Kj(e,n){return L(K("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function dD(e,n,s){return L(K(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function uD(e,n){return L(K(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Xd(e,n,s){const i=new URLSearchParams;n?.limit!==void 0&&i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset)),n?.before&&i.set("before",n.before);const r=i.toString();return L(K(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function Gj(e,n){return L(K(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function Jj(e,n,s,i,r){const o=Zn(K(`/chat/sessions/${encodeURIComponent(e)}/messages`,i)),l=new AbortController;let c=!1;const u=(d,m)=>{if(!(!d||!m))switch(d){case"thinking":try{s.onThinking?.(JSON.parse(m))}catch{s.onThinking?.(m)}break;case"text":try{s.onText?.(JSON.parse(m))}catch{s.onText?.(m)}break;case"tool_start":try{s.onToolStart?.(JSON.parse(m))}catch{}break;case"tool_end":try{s.onToolEnd?.(JSON.parse(m))}catch{}break;case"done":try{s.onDone?.(JSON.parse(m))}catch{s.onDone?.({messageId:""})}break;case"error":try{const h=JSON.parse(m);s.onError?.(h.message||h)}catch{s.onError?.(m||"Stream error")}break}};return(async()=>{try{const d=await fetch(o,{method:"POST",headers:ki({"Content-Type":"application/json"}),body:JSON.stringify({content:n}),signal:l.signal});if(!d.ok){const v=await d.text();let b=`Request failed: ${d.status}`;try{b=JSON.parse(v).error||b}catch{}s.onError?.(b);return}if(!d.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected");const m=d.body.getReader(),h=new TextDecoder;let g="",p="",f=[];const x=(v,b=!1)=>{g+=v;const y=g.split(`
|
|
613
|
+
`);g=y.pop()||"",b&&g.length>0&&(y.push(g),g="");for(const S of y){const k=S.endsWith("\r")?S.slice(0,-1):S;if(k.startsWith("event:"))p=k.slice(6).trim();else if(k.startsWith("data:")){const R=k.slice(5);f.push(R.startsWith(" ")?R.slice(1):R)}else if(k===""){const R=f.join(`
|
|
614
|
+
`);u(p,R),p="",f=[]}}if(b&&p&&f.length>0){const S=f.join(`
|
|
615
|
+
`);u(p,S),p="",f=[]}};for(;;){const{done:v,value:b}=await m.read();if(v){x(h.decode(),!0);break}x(h.decode(b,{stream:!0}))}}catch(d){if(d instanceof DOMException&&d.name==="AbortError"){c||s.onError?.("Connection aborted");return}if(c)return;s.onError?.(d instanceof Error?d.message:"Connection error")}})(),{close:()=>{c=!0,l.abort()},isConnected:()=>!c}}function mD(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 i=s.size>0?`?${s.toString()}`:"";return L(K(`/insights${i}`,n))}function hD(e,n){return L(K(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function pD(e="manual",n,s){return L(K("/insights/run",s),{method:"POST",body:JSON.stringify({trigger:e,inputMetadata:n})})}function fD(e){return L(K("/insights/runs",e))}function gD(e,n){return L(K(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function Yj(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 Qj({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:i}=Yj(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 ${i}`,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]})]})}const Zd=new Map,Xj=6e4;function hp(e){const[n,s]=a.useState([]),[i,r]=a.useState(!0),[o,l]=a.useState(null),c=a.useRef(!1),u=a.useRef(!1),d=a.useCallback(m=>n.filter(h=>h.slot.slotId===m),[n]);return a.useEffect(()=>{const m=e??"default";let h=!1;async function g(){const p=Zd.get(m);if(p&&Date.now()<p.expiresAt){if(h||u.current)return;s(p.slots),r(!1);return}!c.current&&r(!0),l(null);try{const x=await Vj(e);if(h||u.current)return;Zd.set(m,{slots:x,expiresAt:Date.now()+Xj}),s(x),c.current=!0}catch(x){if(h||u.current)return;l(x instanceof Error?x.message:"Failed to fetch UI slots"),c.current=!0}finally{!h&&!u.current&&r(!1)}}return g(),()=>{h=!0}},[e]),a.useEffect(()=>{c.current=!1,u.current=!1},[e]),a.useEffect(()=>()=>{u.current=!0},[]),a.useMemo(()=>({slots:n,getSlotsForId:d,loading:i,error:o}),[n,d,i,o])}function Oo({slotId:e,projectId:n}){const{getSlotsForId:s,loading:i,error:r}=hp(n);if(i||r||!e)return null;const o=s(e);return o.length===0?null:t.jsx(Do,{level:"page",children:t.jsx(t.Fragment,{children:o.map(l=>t.jsx("div",{"data-plugin-slot":!0,"data-slot-id":l.slot.slotId,"data-plugin-id":l.pluginId,"data-component-path":l.slot.componentPath,"aria-label":l.slot.label},`${l.pluginId}-${l.slot.slotId}`))})})}function Zj(){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 Cr(){const[e,n]=a.useState(Zj);return a.useEffect(()=>{if(typeof window>"u")return;const s=window.matchMedia("(max-width: 768px)"),i=window.matchMedia("(min-width: 769px) and (max-width: 1024px)"),r=()=>{s.matches?n("mobile"):i.matches?n("tablet"):n("desktop")};return s.addEventListener("change",r),i.addEventListener("change",r),()=>{s.removeEventListener("change",r),i.removeEventListener("change",r)}},[]),e}const pp={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function ew({projects:e,currentProject:n,onViewAll:s,onSelectProject:i}){const[r,o]=a.useState(!1),l=a.useRef(null);a.useEffect(()=>{if(!r)return;const u=d=>{l.current&&!l.current.contains(d.target)&&o(!1)};return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[r]),a.useEffect(()=>{if(!r)return;const u=d=>{d.key==="Escape"&&o(!1)};return document.addEventListener("keydown",u),()=>document.removeEventListener("keydown",u)},[r]);const c=a.useCallback(u=>{i?.(u),o(!1)},[i]);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(u=>!u),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(qt,{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(u=>{const d=n?.id===u.id,m=pp[u.status]?.color;return t.jsxs("button",{className:`project-selector-item${d?" project-selector-item--current":""}`,onClick:()=>c(u),role:"option","aria-selected":d,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:u.name}),t.jsx("span",{className:"project-selector-path",children:u.path.split("/").slice(-2).join("/")})]}),d&&t.jsx(Mn,{size:14,className:"project-selector-check"})]},u.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 eu({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 tw({onOpenSettings:e,onOpenGitHubImport:n,onOpenPlanning:s,onResumePlanning:i,activePlanningSessionCount:r=0,onOpenUsage:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:u,mailboxUnreadCount:d=0,onOpenSchedules:m,onOpenGitManager:h,onOpenNodes:g,showNodesButton:p,onOpenWorkflowSteps:f,onOpenScripts:x,onRunScript:v,onToggleTerminal:b,onOpenFiles:y,filesOpen:S,globalPaused:k,enginePaused:R,onToggleGlobalPause:N,onToggleEnginePause:M,view:C="board",onChangeView:z,showSkillsTab:A,showAgentsTab:P,searchQuery:F="",onSearchChange:W,projects:$=[],currentProject:_,onSelectProject:I,onViewAllProjects:O,projectId:J,isElectron:Q=!1,mobileNavEnabled:E,availableNodes:D=[],currentNode:T,onSelectNode:w,isRemote:q=!1,experimentalFeatures:G}){const me=Cr(),ce=me==="mobile",pe=ce||me==="tablet",U=ce&&E,[Ne,ne]=a.useState(!1),[xe,le]=a.useState(!1),[ve,ee]=a.useState(!1),[Ee,Fe]=a.useState(!1),[Ke,Ze]=a.useState(!1),[Xe,Qe]=a.useState(!1),[it,Ie]=a.useState(!1),[Ge,se]=a.useState(!1),[ye,Z]=a.useState(!1),[Te,ze]=a.useState(!1),[be,Me]=a.useState(!1),[Be,lt]=a.useState({}),[je,ie]=a.useState(!1),[Ae,he]=a.useState(-1),[Re,Je]=a.useState(null),[$e,de]=a.useState({}),[re,ue]=a.useState(!1),Pe=a.useRef(null),Se=a.useRef(null),fe=a.useRef(null),tt=a.useRef(null),ut=a.useRef(null),vt=a.useRef(null),gt=a.useRef(!1),dt=a.useRef(null),wt=a.useRef(null),Mt=a.useRef(null),yt=a.useRef(null),Et=a.useRef(null),Nt=a.useRef(null),Tt=a.useRef(null),Ht=a.useRef(null),Ut=a.useRef(!1),Vt=a.useMemo(()=>D.filter(we=>we.type==="remote"),[D]),zt=Vt.length>0,Ct=a.useMemo(()=>Object.entries(Be).sort(([we],[rt])=>we.localeCompare(rt)),[Be]),At=Ct.length>0,kt=Ct.length+(At?1:0),Kt=a.useMemo(()=>Object.entries($e).sort(([we],[rt])=>we.localeCompare(rt)),[$e]),$t=a.useMemo(()=>!!(G?.todoView||G?.insights||G?.roadmap||A||G?.memoryView||G?.devServerView),[G,A]),B=a.useCallback(()=>{const we=window.visualViewport;return we&&we.width>0&&we.height>0?{width:we.width,height:we.height,offsetTop:we.offsetTop,offsetLeft:we.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),ge=a.useCallback(()=>{const we=Tt.current;if(!we)return;const rt=we.getBoundingClientRect(),Jt=Ht.current,{width:Sn,height:Cn,offsetTop:pn,offsetLeft:bn}=B(),Rn=16,vn=16,Y=6,Oe=Jt?.offsetWidth||Math.max(rt.width,260),Ye=Math.min(Oe,Math.max(Sn-Rn*2,160)),st=Jt?.offsetHeight||280,pt=Math.min(st,Math.max(Cn-vn*2,160)),jt=rt.top-pn,_t=rt.bottom-pn,yn=rt.right-bn,en=Cn-_t,xt=jt,ts=en<pt&&xt>en,ns=Math.min(Math.max(yn-Ye,Rn),Sn-Rn-Ye)+bn,ss=ts?Math.max(vn+pn,jt-pt-Y+pn):Math.min(_t+Y+pn,Cn+pn-vn-pt);Je({top:ss,left:ns,width:Ye})},[B]),te=a.useCallback((we,rt)=>{v?.(we,rt),Me(!1),he(-1)},[v]),j=a.useCallback(()=>{x?.(),Me(!1),he(-1)},[x]),V=a.useCallback(we=>{switch(we.key){case"ArrowDown":we.preventDefault(),kt>0&&he(rt=>rt<kt-1?rt+1:0);break;case"ArrowUp":we.preventDefault(),kt>0&&he(rt=>rt>0?rt-1:kt-1);break;case"Enter":if(we.preventDefault(),Ae>=0)if(Ae<Ct.length){const[rt,Jt]=Ct[Ae];te(rt,Jt)}else At&&Ae===Ct.length&&j();break;case"Home":we.preventDefault(),kt>0&&he(0);break;case"End":we.preventDefault(),kt>0&&he(kt-1);break}},[j,te,Ae,Ct,At,kt]);a.useEffect(()=>{gt.current=Ke},[Ke]),a.useEffect(()=>{Ut.current=be},[be]),a.useEffect(()=>{if(!Ke||!pe)return;let we=!1;return ue(!0),hr(J).then(rt=>{we||de(rt)}).catch(()=>{we||de({})}).finally(()=>{we||ue(!1)}),()=>{we=!0}},[Ke,pe,J]),a.useEffect(()=>{if(!be||pe)return;let we=!1;return ie(!0),hr(J).then(rt=>{we||lt(rt)}).catch(()=>{we||lt({})}).finally(()=>{we||ie(!1)}),()=>{we=!0}},[be,pe,J]),a.useEffect(()=>{if(!be)return;const we=rt=>{Nt.current&&!Nt.current.contains(rt.target)&&Me(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[be]),a.useEffect(()=>{if(!be)return;const we=rt=>{rt.key==="Escape"&&(Me(!1),Tt.current?.focus())};return document.addEventListener("keydown",we),()=>document.removeEventListener("keydown",we)},[be]),a.useEffect(()=>{if(be){he(-1);const we=window.setTimeout(()=>Ht.current?.focus(),0);return()=>window.clearTimeout(we)}Je(null)},[be]),a.useEffect(()=>{if(!be)return;const we=requestAnimationFrame(()=>{ge()});return()=>cancelAnimationFrame(we)},[be,je,Ct.length,At,ge]),a.useEffect(()=>{if(!be)return;const we=()=>ge();window.addEventListener("resize",we),window.addEventListener("scroll",we,!0);const rt=window.visualViewport;return rt&&(rt.addEventListener("resize",we),rt.addEventListener("scroll",we)),()=>{window.removeEventListener("resize",we),window.removeEventListener("scroll",we,!0),rt&&(rt.removeEventListener("resize",we),rt.removeEventListener("scroll",we))}},[be,ge]),a.useEffect(()=>{pe&&(Me(!1),he(-1))},[pe]);const De=Ne||F.length>0,nt=(xe||F.length>0)&&!ve,St=(C==="board"||C==="list")&&!ce&&W&&!ve&&F.length===0,Pt=(C==="board"||C==="list")&&!ce&&W;a.useEffect(()=>{F===""&&ee(!1)},[F]),a.useEffect(()=>{if(!Ee)return;const we=rt=>{Se.current&&!Se.current.contains(rt.target)&&Pe.current&&!Pe.current.contains(rt.target)&&Fe(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[Ee]),a.useEffect(()=>{if(!ye)return;const we=rt=>{tt.current&&!tt.current.contains(rt.target)&&fe.current&&!fe.current.contains(rt.target)&&Z(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[ye]),a.useEffect(()=>{if(!Xe)return;const we=rt=>{dt.current&&!dt.current.contains(rt.target)&&Qe(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[Xe]),a.useEffect(()=>{const we=rt=>{if(rt.key==="Escape"){if(se(!1),Z(!1),gt.current){Ze(!1);return}if(Ut.current){Me(!1),Tt.current?.focus();return}Fe(!1),ne(!1),Qe(!1),Ie(!1)}};return document.addEventListener("keydown",we),()=>document.removeEventListener("keydown",we)},[]),a.useEffect(()=>{if(!it)return;const we=rt=>{wt.current&&!wt.current.contains(rt.target)&&Ie(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[it]),a.useEffect(()=>{if(!Te)return;const we=rt=>{Et.current&&!Et.current.contains(rt.target)&&ze(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[Te]),a.useEffect(()=>{if(!Te)return;const we=rt=>{rt.key==="Escape"&&ze(!1)};return document.addEventListener("keydown",we),()=>document.removeEventListener("keydown",we)},[Te]),a.useEffect(()=>{if(!Ge)return;const we=rt=>{Mt.current&&!Mt.current.contains(rt.target)&&yt.current&&!yt.current.contains(rt.target)&&se(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[Ge]);const Rt=a.useCallback(()=>{ne(we=>!we)},[]),un=a.useCallback(()=>{le(!0),ee(!1)},[]),mn=a.useCallback(()=>{le(!1),ee(!0),W&&W("")},[W]),wn=a.useCallback(()=>{Fe(we=>!we)},[]),Gt=a.useCallback(we=>{we&&we(),Fe(!1),Ze(!1)},[]),es=a.useCallback(()=>{ne(!1),W&&W("")},[W]);return t.jsxs("div",{className:"header-wrapper",children:[t.jsxs("header",{className:"header",children:[t.jsxs("div",{className:"header-left",children:[t.jsxs("div",{className:"header-brand",children:[t.jsxs("svg",{className:"header-logo",width:24,height:24,viewBox:"0 0 128 128",fill:"none","aria-label":"Fusion logo",role:"img",children:[t.jsx("circle",{cx:"64",cy:"64",r:"52",stroke:"currentColor",strokeWidth:"8"}),t.jsx("path",{d:"M26 101C44 82 62 64 82 45C90 37 98 30 104 24C96 35 89 47 81 60C70 79 57 95 43 108C38 112 32 108 26 101Z",fill:"currentColor"})]}),t.jsx("h1",{className:"logo",children:"Fusion"})]}),ce&&$.length>=1&&I&&t.jsxs("div",{className:"mobile-project-switch",ref:wt,children:[t.jsx("button",{className:`mobile-project-switch-trigger${it?" mobile-project-switch-trigger--open":""}`,onClick:()=>Ie(we=>!we),title:"Switch project","aria-label":"Switch project","aria-expanded":it,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(qt,{size:14,className:`mobile-project-switch-chevron${it?" mobile-project-switch-chevron--open":""}`})}),it&&t.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:$.map(we=>{const rt=_?.id===we.id,Jt=pp[we.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${rt?" mobile-project-switch-item--current":""}`,onClick:()=>{I(we),Ie(!1)},role:"option","aria-selected":rt,"data-testid":`mobile-project-switch-item-${we.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:Jt||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:we.name}),t.jsx("span",{className:"mobile-project-switch-path",children:we.path.split("/").slice(-2).join("/")})]}),rt&&t.jsx(Mn,{size:14,className:"mobile-project-switch-check"})]},we.id)})})]}),!pe&&$.length>=1&&O&&t.jsx(ew,{projects:$,currentProject:_??null,onViewAll:O,onSelectProject:I}),zt&&t.jsxs("div",{className:`header-node-selector${ce?" header-node-selector--mobile":""}`,ref:ce?void 0:dt,children:[t.jsx(Qj,{node:T??null,showDetails:!ce}),!ce&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${Xe?" node-selector-trigger--open":""}`,onClick:()=>Qe(we=>!we),title:"Switch node","aria-label":"Switch node","aria-expanded":Xe,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(hn,{size:12,className:`node-selector-chevron${Xe?" node-selector-chevron--open":""}`})}),Xe&&t.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[t.jsxs("button",{className:`node-selector-option${q?"":" node-selector-option--active"}`,onClick:()=>{w?.(null),Qe(!1)},role:"option","aria-selected":!q,"data-testid":"node-option-local",children:[t.jsx("span",{className:"node-selector-option-dot node-selector-option-dot--local"}),t.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),Vt.map(we=>t.jsxs("button",{className:`node-selector-option${T?.id===we.id?" node-selector-option--active":""}`,onClick:()=>{w?.(we),Qe(!1)},role:"option","aria-selected":T?.id===we.id,"data-testid":`node-option-${we.id}`,children:[t.jsx("span",{className:`node-selector-option-dot node-selector-option-dot--${we.status}`}),t.jsx("span",{className:"node-selector-option-label",children:we.name}),t.jsx("span",{className:"node-selector-option-status",children:we.status})]},we.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[U&&z&&(C==="board"||C==="list")&&t.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${C==="board"?" active":""}`,onClick:()=>z("board"),title:"Board view","aria-label":"Board view","aria-pressed":C==="board","data-testid":"mobile-view-toggle-board",children:t.jsx(Bi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="list"?" active":""}`,onClick:()=>z("list"),title:"List view","aria-label":"List view","aria-pressed":C==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(gc,{size:16})})]}),W&&ce&&(U||C==="board"||C==="list")&&!De&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:Rt,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx(oa,{size:16})}),St&&t.jsx("button",{className:"btn-icon",onClick:un,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(oa,{size:16})}),ce&&U&&o&&t.jsx("button",{className:"btn-icon",onClick:we=>o(we.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(Cs,{size:16})}),!U&&z&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${C==="board"?" active":""}`,onClick:()=>z("board"),title:"Board view","aria-label":"Board view","aria-pressed":C==="board",children:t.jsx(Bi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="list"?" active":""}`,onClick:()=>z("list"),title:"List view","aria-label":"List view","aria-pressed":C==="list",children:t.jsx(gc,{size:16})}),P&&t.jsx("button",{className:`view-toggle-btn${C==="agents"?" active":""}`,onClick:()=>z("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":C==="agents",children:t.jsx(gn,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="missions"?" active":""}`,onClick:()=>z("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":C==="missions",children:t.jsx(ls,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="chat"?" active":""}`,onClick:()=>z("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":C==="chat",children:t.jsx(bi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="documents"?" active":""}`,onClick:()=>z("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":C==="documents",children:t.jsx(Oi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="mailbox"?" active":""}`,onClick:()=>z("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":C==="mailbox",children:t.jsx(ma,{size:16})}),$t&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:yt,className:`view-toggle-btn${["skills","roadmaps","insights","memory","dev-server","devserver"].includes(C)||G?.todoView&&C==="todos"?" active":""}`,onClick:()=>se(we=>!we),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":Ge,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(qt,{size:12})}),Ge&&t.jsxs("div",{ref:Mt,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[G?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="insights"?" active":""}`,onClick:()=>{z("insights"),se(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(qn,{size:14}),t.jsx("span",{children:"Insights"})]}),G?.roadmap&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="roadmaps"?" active":""}`,onClick:()=>{z("roadmaps"),se(!1)},role:"menuitem","data-testid":"view-overflow-roadmaps",children:[t.jsx(xc,{size:14}),t.jsx("span",{children:"Roadmaps"})]}),A&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="skills"?" active":""}`,onClick:()=>{z("skills"),se(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(Pn,{size:14}),t.jsx("span",{children:"Skills"})]}),G?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="memory"?" active":""}`,onClick:()=>{z("memory"),se(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(co,{size:14}),t.jsx("span",{children:"Memory"})]}),G?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="dev-server"||C==="devserver"?" active":""}`,onClick:()=>{z("devserver"),se(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(dr,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]}),G?.todoView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="todos"?" active":""}`,onClick:()=>{z("todos"),se(!1)},role:"menuitem","data-testid":"view-overflow-todos",children:[t.jsx(Gh,{size:14}),t.jsx("span",{children:"Todos"})]})]})]})]}),!pe&&o&&t.jsx("button",{className:"btn-icon",onClick:we=>o(we.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"desktop-header-usage-btn",children:t.jsx(Cs,{size:16})}),!pe&&c&&t.jsx("button",{className:"btn-icon",onClick:c,title:"System Stats","data-testid":"desktop-header-system-stats-btn",children:t.jsx(dr,{size:16})}),!pe&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(cr,{size:16})}),!pe&&!Q&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(eu,{size:16})}),!pe&&t.jsxs("button",{className:`btn-icon${r>0?" btn-icon--has-indicator":""}`,onClick:r>0&&i?i:s,title:r>0?"Resume planning session":"Create a task with AI planning","data-testid":"planning-btn",style:{position:"relative"},children:[t.jsx(Ys,{size:16}),r>0&&t.jsx("span",{className:"header-badge header-badge--pulse","data-testid":"planning-badge","aria-label":`${r} active planning session${r!==1?"s":""}`,children:r})]}),!pe&&t.jsxs("div",{className:"terminal-split-btn",ref:Nt,children:[t.jsx("button",{className:"btn-icon btn-icon--terminal terminal-split-btn__main",onClick:b,title:"Open Terminal","data-testid":"terminal-toggle-btn",children:t.jsx(ri,{size:16})}),x&&v&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"terminal-split-btn__divider"}),t.jsx("button",{ref:Tt,className:`btn-icon terminal-split-btn__chevron${be?" btn-icon--active":""}`,onClick:()=>Me(we=>!we),title:"Scripts","aria-haspopup":"listbox","aria-expanded":be,"aria-label":"Quick scripts","data-testid":"scripts-btn",children:t.jsx(qt,{size:12,className:`quick-scripts-dropdown__trigger-chevron${be?" rotate":""}`})}),be&&t.jsx("div",{ref:Ht,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:V,"data-testid":"quick-scripts-dropdown",style:Re?{position:"fixed",top:`${Re.top}px`,left:`${Re.left}px`,width:`${Re.width}px`,right:"auto"}:void 0,children:je?t.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[t.jsx(ot,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):Ct.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(ri,{size:16})}),t.jsx("p",{children:"No scripts configured"}),t.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:j,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:Ct.map(([we,rt],Jt)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${Ae===Jt?"highlighted":""}`,onClick:()=>te(we,rt),role:"option","aria-selected":Ae===Jt,"data-testid":`quick-script-item-${we}`,children:[t.jsx(xn,{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:we}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:rt,children:rt.length>50?`${rt.slice(0,50)}...`:rt})]})]},we))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${At&&Ae===Ct.length?"highlighted":""}`,onClick:j,"data-testid":"quick-scripts-manage",children:[t.jsx(sr,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})]}),!pe&&y&&t.jsx("button",{className:`btn-icon${S?" btn-icon--active":""}`,onClick:y,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(In,{size:16})}),!pe&&h&&t.jsx("button",{className:"btn-icon",onClick:h,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Js,{size:16})}),!pe&&f&&t.jsx("button",{className:"btn-icon",onClick:f,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(vc,{size:16})}),!pe&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:fe,className:"btn-icon",onClick:()=>Z(we=>!we),title:"More actions","aria-label":"More actions","aria-expanded":ye,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(hc,{size:16})}),ye&&t.jsxs("div",{ref:tt,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[g&&p!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{g(),Z(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx(mo,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{Gt(m),Z(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(yi,{size:14}),t.jsx("span",{children:"Automation"})]})]})]}),t.jsxs("div",{className:"engine-control-split-btn",ref:Et,children:[t.jsx("button",{className:`btn-icon engine-control-split-btn__main${k?" btn-icon--stopped":""}`,onClick:N,title:k?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:k?t.jsx(xn,{size:16}):t.jsx(ms,{size:16})}),t.jsx("span",{className:"engine-control-split-btn__divider"}),t.jsx("button",{className:`btn-icon engine-control-split-btn__chevron${Te?" btn-icon--active":""}`,onClick:()=>ze(we=>!we),title:"Engine options","aria-haspopup":"menu","aria-expanded":Te,"data-testid":"engine-control-chevron-btn",children:t.jsx(qt,{size:12})}),Te&&t.jsx("div",{className:"engine-control-split-btn__menu",role:"menu",children:t.jsxs("button",{className:`engine-control-split-btn__menu-item${R?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{M?.(),ze(!1)},role:"menuitem",title:R?"Resume scheduling":"Pause triage",disabled:!!k,"data-testid":"engine-control-pause-triage-btn",children:[R?t.jsx(xn,{size:14}):t.jsx(Gs,{size:14}),t.jsx("span",{children:R?"Resume scheduling":"Pause triage"})]})})]}),!pe&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(sr,{size:16})}),t.jsx(Oo,{slotId:"header-action",projectId:J}),pe&&!U&&t.jsx("button",{ref:Pe,className:"btn-icon compact-overflow-trigger",onClick:wn,title:"More header actions","aria-label":"More header actions","aria-expanded":Ee,"aria-haspopup":"menu",children:t.jsx(hc,{size:16})}),pe&&!U&&Ee&&t.jsxs("div",{ref:Se,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[$.length>=1&&O&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Gt(O),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(qh,{size:16}),t.jsx("span",{children:"Projects"})]}),y&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Gt(y),role:"menuitem","data-testid":"overflow-files-btn",children:[t.jsx(In,{size:16}),t.jsx("span",{children:"Browse Files"})]}),t.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>Gt(r>0&&i?i:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx(Ys,{size:16}),r>0&&t.jsx("span",{className:"header-badge header-badge--pulse","data-testid":"overflow-planning-badge",children:r})]}),t.jsx("span",{children:r>0?`Resume planning session (${r})`:"Create a task with AI planning"})]}),h&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Gt(h),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(Js,{size:16}),t.jsx("span",{children:"Git Manager"})]}),g&&p!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Gt(g),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(mo,{size:16}),t.jsx("span",{children:"Nodes"})]}),!Q&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Gt(n),role:"menuitem",children:[t.jsx(eu,{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:()=>Gt(b),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[t.jsx(ri,{size:16}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>Ze(we=>!we),role:"menuitem","aria-expanded":Ke,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(hn,{size:14,className:`mobile-overflow-chevron${Ke?" mobile-overflow-chevron--open":""}`})})]}),Ke&&t.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:re?t.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[t.jsx(ot,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):Kt.length>0?t.jsxs(t.Fragment,{children:[Kt.map(([we,rt])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{v&&v(we,rt),Fe(!1),Ze(!1)},role:"menuitem","data-testid":`overflow-script-item-${we}`,children:[t.jsx(xn,{size:14}),t.jsx("span",{children:we})]},we)),x&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>Gt(x),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Is,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):x&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>Gt(x),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Is,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Gt(m),role:"menuitem","data-testid":"overflow-schedules-btn",children:[t.jsx(yi,{size:16}),t.jsx("span",{children:"Automation"})]}),l&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Gt(l),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[t.jsx(cr,{size:16}),t.jsx("span",{children:"View Activity Log"})]}),u&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Gt(u),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(ma,{size:16}),t.jsxs("span",{children:["Mailbox",d>0?` (${d})`:""]})]}),o&&t.jsxs("button",{className:"mobile-overflow-item",onClick:we=>Gt(()=>o(we.currentTarget.getBoundingClientRect())),role:"menuitem","data-testid":"overflow-usage-btn",children:[t.jsx(Cs,{size:16}),t.jsx("span",{children:"View Usage"})]}),f&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Gt(f),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(vc,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Gt(e),role:"menuitem",children:[t.jsx(sr,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),Pt&&nt&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{className:"header-search",children:[t.jsx(oa,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:F,onChange:we=>W(we.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:mn,"aria-label":"Close search",children:t.jsx(Ot,{size:14})})]})}),W&&ce&&De&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{ref:ut,className:"header-search mobile-search-expanded",children:[t.jsx(oa,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:vt,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:F,onChange:we=>W(we.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:es,"aria-label":"Close search",children:t.jsx(Ot,{size:14})})]})})]})}const nw={themeMode:"dark",colorTheme:"default",defaultProvider:void 0,defaultModelId:void 0,fallbackProvider:void 0,fallbackModelId:void 0,defaultThinkingLevel:void 0,ntfyEnabled:!1,ntfyTopic:void 0,ntfyBaseUrl:void 0,ntfyEvents:["in-review","merged","failed","awaiting-approval","awaiting-user-review","planning-awaiting-input","gridlock"],ntfyDashboardHost:void 0,webhookEnabled:!1,webhookUrl:void 0,webhookFormat:"generic",webhookEvents:[],notificationProviders:[],defaultProjectId:void 0,setupComplete:void 0,favoriteProviders:void 0,favoriteModels:void 0,openrouterModelSync:!0,updateCheckEnabled:!0,updateCheckFrequency:"daily",showGitHubStarButton:!0,modelOnboardingComplete:void 0,useClaudeCli: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},sw={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",pushAfterMerge:!1,pushRemote:"origin",unavailableNodePolicy:"block",defaultNodeId:void 0,worktreeInitCommand:void 0,testCommand:void 0,buildCommand:void 0,recycleWorktrees:!1,worktreeNaming:"random",taskPrefix:"FN",includeTaskIdInCommit:!0,commitAuthorEnabled:!0,commitAuthorName:"Fusion",commitAuthorEmail:"noreply@runfusion.ai",planningProvider:void 0,planningModelId:void 0,planningFallbackProvider:void 0,planningFallbackModelId:void 0,defaultProviderOverride:void 0,defaultModelIdOverride:void 0,executionProvider:void 0,executionModelId:void 0,validatorProvider:void 0,validatorModelId:void 0,validatorFallbackProvider:void 0,validatorFallbackModelId:void 0,modelPresets:[],autoSelectModelPreset:!1,defaultPresetBySize:{},autoResolveConflicts:!0,smartConflictResolution:!0,worktreeRebaseBeforeMerge:!0,worktreeRebaseRemote:"",worktreeRebaseLocalBase:!0,mergeConflictStrategy:"smart-prefer-main",workflowStepTimeoutMs:36e4,strictScopeEnforcement:!1,buildRetryCount:0,verificationFixRetries:3,buildTimeoutMs:3e5,requirePlanApproval:!1,specStalenessEnabled:!1,specStalenessMaxAgeMs:360*60*1e3,taskStuckTimeoutMs:void 0,aiSessionTtlMs:10080*60*1e3,aiSessionCleanupIntervalMs:3600*1e3,autoUnpauseEnabled:!0,autoUnpauseBaseDelayMs:3e5,autoUnpauseMaxDelayMs:36e5,maxStuckKills:6,maxPostReviewFixes:1,maxSpawnedAgentsPerParent:5,maxSpawnedAgentsGlobal:20,maintenanceIntervalMs:9e5,autoArchiveDoneTasksEnabled:!0,autoArchiveDoneAfterMs:2880*60*1e3,archiveAgentLogMode:"compact",autoUpdatePrStatus:!1,autoCreatePr:!1,githubCommentOnDone:!1,githubCommentTemplate:void 0,autoBackupEnabled:!1,autoBackupSchedule:"0 2 * * *",autoBackupRetention:7,autoBackupDir:".fusion/backups",autoSummarizeTitles:!1,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,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,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}},reflectionEnabled:!1,reflectionIntervalMs:36e5,reflectionAfterTask:!0,reviewHandoffPolicy:"disabled",showQuickChatFAB:!1,experimentalFeatures:{}},iw=Object.freeze(Object.keys(nw)),aw=Object.freeze(Object.keys(sw));function xD(e){return iw.includes(e)}function bD(e){return aw.includes(e)}function ke(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function rw(e){return!!(e?.provider&&e?.modelId)}function ji(...e){for(const n of e)if(rw(n))return{provider:n.provider,modelId:n.modelId};return{}}function Uo(e){return ji({provider:e?.defaultProviderOverride,modelId:e?.defaultModelIdOverride},{provider:e?.defaultProvider,modelId:e?.defaultModelId})}function ow(e){return ji({provider:e?.executionProvider,modelId:e?.executionModelId},{provider:e?.executionGlobalProvider,modelId:e?.executionGlobalModelId},Uo(e))}function lw(e){return ji({provider:e?.planningProvider,modelId:e?.planningModelId},{provider:e?.planningGlobalProvider,modelId:e?.planningGlobalModelId},Uo(e))}function cw(e){return ji({provider:e?.validatorProvider,modelId:e?.validatorModelId},{provider:e?.validatorGlobalProvider,modelId:e?.validatorGlobalModelId},Uo(e))}function vD(e){return ji({provider:e?.titleSummarizerProvider,modelId:e?.titleSummarizerModelId},{provider:e?.titleSummarizerGlobalProvider,modelId:e?.titleSummarizerGlobalModelId},{provider:e?.planningProvider,modelId:e?.planningModelId},Uo(e))}function fp(e,n){return ji({provider:e.modelProvider,modelId:e.modelId},ow(n))}function gp(e,n){return ji({provider:e.validatorModelProvider,modelId:e.validatorModelId},cw(n))}function xp(e,n){return ji({provider:e.planningModelProvider,modelId:e.planningModelId},lw(n))}const yD=["off","minimal","low","medium","high"],zi=["triage","todo","in-progress","in-review","done","archived"],ed=["low","normal","high","urgent"],ps="normal",dw=["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"],_n={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},uw={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"},Nc={triage:["todo"],todo:["in-progress","triage"],"in-progress":["in-review","todo","triage","done"],"in-review":["done","in-progress","todo"],done:["todo","triage","archived"],archived:["done"]};function mw(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 hw(e,n=1400){const s=a.useRef(null),[i,r]=a.useState(!1),o=a.useRef(null);return a.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]),i}function pw({isOpen:e,options:n,onConfirm:s,onCancel:i}){const r=a.useRef(null);return a.useEffect(()=>{if(!e)return;r.current?.focus();const o=l=>{l.key==="Escape"&&(l.preventDefault(),i())};return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[e,i]),!e||!n?null:t.jsx("div",{className:"modal-overlay open",onClick:i,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:i,"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:i,children:n.cancelLabel??"Cancel"}),t.jsx("button",{className:`btn ${n.danger?"btn-danger":"btn-primary"}`,onClick:s,children:n.confirmLabel??"Confirm"})]})]})})}const bp=a.createContext(null);function fw({children:e}){const[n,s]=a.useState([]),i=a.useRef([]),r=a.useCallback(d=>{s(m=>{const h=d(m);return i.current=h,h})},[]),o=a.useCallback(d=>new Promise(m=>{r(h=>[...h,{options:d,resolve:m}])}),[r]),l=a.useCallback(d=>{const m=i.current[0];m&&(m.resolve(d),r(h=>h.slice(1)))},[r]),c=n[0]??null,u=a.useMemo(()=>({confirm:o}),[o]);return lo.createElement(bp.Provider,{value:u},e,lo.createElement(pw,{isOpen:c!==null,options:c?.options??null,onConfirm:()=>l(!0),onCancel:()=>l(!1)}))}function Ds(){const e=a.useContext(bp);return e||{confirm:async n=>!1}}function gw(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 vp({prInfo:e,issueInfo:n,onIssueRefresh:s}){const i=()=>{e?.url&&window.open(e.url,"_blank","noopener,noreferrer")},r=()=>{n?.url&&window.open(n.url,"_blank","noopener,noreferrer")};return t.jsxs(t.Fragment,{children:[e&&t.jsxs("span",{className:`card-github-badge card-github-badge--${e.status}`,title:`PR #${e.number}: ${e.title}`,onClick:i,children:[t.jsx(hs,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("span",{className:`card-github-badge ${gw(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,onClick:r,children:[t.jsx(Ro,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function Br(e,n){return`${e??"default"}:${n}`}class xw{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,i=[];for(const[r,o]of this.subscriptionsByTask){const l=r.split(":").slice(1).join(":");for(const c of o)i.push({hookId:c,taskId:l})}if(this.projectId=n,this.reset(),s){for(const{hookId:r,taskId:o}of i){const l=Br(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const i=Br(this.projectId,s),r=this.subscriptionsByTask.get(i)??new Set,o=!r.has(n);r.add(n),this.subscriptionsByTask.set(i,r),this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect(),o&&this.send({type:"subscribe",taskId:s,projectId:this.projectId})}unsubscribeTask(n,s){const i=Br(this.projectId,s),r=this.subscriptionsByTask.get(i);r&&(r.delete(n),r.size===0&&(this.subscriptionsByTask.delete(i),this.badgeUpdates.delete(i),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 i=s.split(":").slice(1).join(":");this.unsubscribeTask(n,i)}}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 i=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/ws`;this.projectId&&(i+=`?projectId=${encodeURIComponent(this.projectId)}`);const r=new WebSocket(Qs(i));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=Br(this.projectId,l.taskId),u=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:tu(l,"prInfo")?l.prInfo??null:u?.prInfo,issueInfo:tu(l,"issueInfo")?l.issueInfo??null:u?.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,i=Math.min(this.reconnectDelayMs,5e3);this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.projectContextVersionRef===s&&this.shouldReconnect&&this.connect()},i),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 Pi=new xw;let bw=0;function tu(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function yp(e){const n=a.useRef(null);n.current===null&&(n.current=`badge-hook-${bw++}`);const s=a.useSyncExternalStore(o=>Pi.subscribe(o),()=>Pi.getSnapshot(),()=>Pi.getSnapshot()),i=a.useCallback(o=>{Pi.subscribeTask(n.current,o)},[]),r=a.useCallback(o=>{Pi.unsubscribeTask(n.current,o)},[]);return a.useEffect(()=>{Pi.setProjectId(e??null)},[e]),a.useEffect(()=>()=>{Pi.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:i,unsubscribeFromBadge:r}}function bo(e,n,s,i){return e===void 0||!n?s:!i||n>=i?e??void 0:s}function vw({taskId:e,prInfo:n,issueInfo:s,updatedAt:i,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:u}=yp(o),d=!!(n||s);a.useEffect(()=>{if(!d||!r){u(e);return}return c(e),()=>{u(e)}},[d,r,o,c,e,u]);const m=l.get(`${o??"default"}:${e}`),h=bo(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??i),g=bo(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??i);return!h&&!g?null:t.jsx(vp,{prInfo:h,issueInfo:g})}const yw=a.memo(vw);yw.displayName="TaskCardBadge";const kw={sm:16,md:20,lg:24};function jw({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 nu({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 Bs({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 ww({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 su({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 Nw({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 cl({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 iu({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 au({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 ru({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 Ia({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 ou({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 dl({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 lu({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 ul({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 Sw({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 Cw({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 cu({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 ml({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 Ew({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 du({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 hl({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 uu({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 pl({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 mu({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"})]})}const _w={anthropic:{component:jw,color:"var(--provider-anthropic)"},"claude-cli":{component:mu,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:mu,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},openai:{component:nu,color:"var(--provider-openai)"},"openai-codex":{component:nu,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:Bs,color:"var(--provider-gemini)"},gemini:{component:Bs,color:"var(--provider-gemini)"},"google-antigravity":{component:Bs,color:"var(--provider-gemini)",label:"Google Gemini"},antigravity:{component:Bs,color:"var(--provider-gemini)",label:"Google Gemini"},"google-vertex":{component:Bs,color:"var(--provider-gemini)",label:"Google Vertex AI"},vertex:{component:Bs,color:"var(--provider-gemini)",label:"Google Vertex AI"},"google-cloud-code":{component:Bs,color:"var(--provider-gemini)",label:"Google Cloud Code"},"cloud-code":{component:Bs,color:"var(--provider-gemini)",label:"Google Cloud Code"},"google-gemini-cli":{component:Bs,color:"var(--provider-gemini)",label:"Google Gemini CLI"},"google-generative-ai":{component:Bs,color:"var(--provider-gemini)",label:"Google Generative AI"},ollama:{component:ww,color:"var(--text)"},github:{component:du,color:"var(--text)"},"github-copilot":{component:du,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:Ew,color:"var(--provider-openrouter)"},minimax:{component:su,color:"var(--provider-minimax)"},"minimax-cn":{component:su,color:"var(--provider-minimax)",label:"MiniMax (CN)"},zai:{component:Nw,color:"var(--provider-zai)"},kimi:{component:cl,color:"var(--provider-kimi)"},moonshot:{component:cl,color:"var(--provider-kimi)"},"kimi-coding":{component:cl,color:"var(--provider-kimi)",label:"Kimi"},bedrock:{component:iu,color:"var(--provider-bedrock)"},"amazon-bedrock":{component:iu,color:"var(--provider-bedrock)",label:"Amazon Bedrock"},xai:{component:au,color:"var(--text)"},grok:{component:au,color:"var(--text)",label:"xAI"},opencode:{component:ru,color:"var(--provider-opencode)"},"opencode-go":{component:ru,color:"var(--provider-opencode)",label:"Opencode (Go)"},qwen:{component:Ia,color:"var(--provider-qwen)"},"qwen-ai":{component:Ia,color:"var(--provider-qwen)",label:"Qwen"},"qwen-coder":{component:Ia,color:"var(--provider-qwen)",label:"Qwen Coder"},alibaba:{component:Ia,color:"var(--provider-qwen)",label:"Qwen"},tongyi:{component:Ia,color:"var(--provider-qwen)",label:"Qwen"},lmstudio:{component:ou,color:"var(--provider-lmstudio)",label:"LM Studio"},"lm-studio":{component:ou,color:"var(--provider-lmstudio)",label:"LM Studio"},huggingface:{component:dl,color:"var(--provider-huggingface)",label:"Hugging Face"},"hugging-face":{component:dl,color:"var(--provider-huggingface)",label:"Hugging Face"},hf:{component:dl,color:"var(--provider-huggingface)",label:"Hugging Face"},mistral:{component:lu,color:"var(--provider-mistral)",label:"Mistral AI"},"mistral-ai":{component:lu,color:"var(--provider-mistral)",label:"Mistral AI"},azure:{component:ul,color:"var(--provider-azure)"},"azure-openai":{component:ul,color:"var(--provider-azure)",label:"Azure OpenAI"},"azure-openai-responses":{component:ul,color:"var(--provider-azure)",label:"Azure OpenAI"},fireworks:{component:ml,color:"var(--provider-fireworks)",label:"Fireworks AI"},"fireworks-ai":{component:ml,color:"var(--provider-fireworks)",label:"Fireworks AI"},fireworksai:{component:ml,color:"var(--provider-fireworks)",label:"Fireworks AI"},cerebras:{component:Sw,color:"var(--provider-cerebras)"},groq:{component:Cw,color:"var(--provider-groq)"},vercel:{component:cu,color:"var(--provider-vercel)"},"vercel-ai-gateway":{component:cu,color:"var(--provider-vercel)",label:"Vercel AI Gateway"},hermes:{component:hl,color:"var(--provider-hermes)",label:"Hermes"},"hermes-agent":{component:hl,color:"var(--provider-hermes)",label:"Hermes"},hermesagent:{component:hl,color:"var(--provider-hermes)",label:"Hermes"},openclaw:{component:uu,color:"var(--provider-openclaw)",label:"OpenClaw"},"open-claw":{component:uu,color:"var(--provider-openclaw)",label:"OpenClaw"},paperclip:{component:pl,color:"var(--provider-paperclip)",label:"Paperclip"},paperclipai:{component:pl,color:"var(--provider-paperclip)",label:"Paperclip"},"paperclip-ai":{component:pl,color:"var(--provider-paperclip)",label:"Paperclip"}};function An({provider:e,size:n="sm"}){const s=e.toLowerCase(),i=_w[s],r=i?.component,o=i?.color??"var(--text-muted)",l=i?.label,c=kw[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(tx,{size:c})})}const js={data:new Map,pendingPromise:null,lastFetchTime:null},Mw=5e3;function ao(e,n){return n?`${n}::${e}`:e}function Aw(e,n){const s=js.data.get(ao(e,n));if(!(!s||Date.now()-s.timestamp>Mw))return s}function Rw(e){const[n,s]=a.useState(!1),i=a.useRef(null),r=a.useCallback(async c=>{let d=null;for(let m=0;m<3;m++)try{return await hy(c,e)}catch(h){d=h instanceof Error?h:new Error(String(h));const g=ke(h);if(g?.includes("429")||g?.toLowerCase().includes("rate limit")){const p=Math.min(1e3*Math.pow(2,m),3e4);await new Promise(f=>setTimeout(f,p));continue}break}if(d)throw d;return{}},[e]),o=a.useCallback(async c=>{if(c.length===0)return;const d=Date.now()-5e3;if(c.every(g=>{const p=js.data.get(ao(g,e));return p&&p.timestamp>d})&&js.lastFetchTime&&js.lastFetchTime>d)return;if(i.current&&(clearTimeout(i.current),i.current=null),js.pendingPromise){s(!0);try{await js.pendingPromise}finally{s(!1)}return}s(!0);const h=r(c);js.pendingPromise=h;try{const g=await h,p=Date.now();for(const[f,x]of Object.entries(g))js.data.set(ao(f,e),{result:x,timestamp:p});js.lastFetchTime=p}catch{}finally{js.pendingPromise=null,s(!1)}},[r,e]),l=a.useCallback(c=>js.data.get(ao(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:js.lastFetchTime,getBatchData:l}}const Sc=new Map,Tw=3e4;function kp(e,n,s,i){return`${e}:${n??""}:${s??""}:${i??""}`}function Pw(e,n,s,i){const r=kp(e,n,s,i),o=Sc.get(r);return o?Date.now()>o.expiresAt?(Sc.delete(r),null):o.stats:null}function Iw(e,n,s,i,r){const o=kp(e,n,s,i);Sc.set(o,{stats:r,expiresAt:Date.now()+Tw})}function $w(e,n,s,i,r={}){const o=r.enabled??!0,l=r.worktree,c=r.stepVersion,u=r.pollIntervalMs,[d,m]=a.useState(null),[h,g]=a.useState(!1);return a.useEffect(()=>{if(!o){m(null),g(!1);return}const p=n==="done"&&!!s,f=(n==="in-progress"||n==="in-review")&&!!l;if(!e||!p&&!f){m(null),g(!1);return}const x=f?l:void 0,v=c!==void 0?String(c):void 0;let b=!1;async function y(k=!1){if(!k){const R=Pw(e,i,x,v);if(R){b||(m(R),g(!1));return}}g(!0);try{const R=await lp(e,x,i);b||(m(R.stats),Iw(e,i,x,v,R.stats))}catch{b||m(null)}finally{b||g(!1)}}y();let S;return u&&f&&(S=setInterval(()=>{y(!0)},u)),()=>{b=!0,S&&clearInterval(S)}},[e,n,s,i,o,l,c,u]),{stats:d,loading:h}}const Dw=new Set(["failed","stuck-killed"]);function vo(e,n,s){if(e.column!=="in-progress"||e.status&&Dw.has(e.status)||!n||n<=0)return!1;const i=new Date(e.updatedAt).getTime();return(s??Date.now())-i>n}function Lw(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function zw(e){return e==="done"||e==="skipped"}function Fw(e,n,s){const i=s?.get(e)?.trim();if(i)return i;const r=n?.workflowStepName?.trim();return r||e}function jp(e,n){const s=(e.steps??[]).map((u,d)=>({id:`step-${d}`,name:u.name,status:u.status,source:"step",phase:"pre-merge"})),i=new Map((e.workflowStepResults??[]).map(u=>[u.workflowStepId,u])),r=(e.enabledWorkflowSteps??[]).map(u=>{const d=i.get(u);return{id:`workflow-${u}`,name:Fw(u,d,n),status:d?Lw(d.status):"pending",source:"workflow",phase:d?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(u=>zw(u.status)).length;return{total:l,completed:c,items:o}}function Ow(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 wp(e){return e.filter(n=>{const s=typeof n.action=="string"?n.action:"",i=typeof n.outcome=="string"?n.outcome:"";return s.includes("[timing]")||i.includes("[timing]")}).map(n=>{const i=`${n.action??""}
|
|
616
|
+
${n.outcome??""}`.match(/(\d+(?:\.\d+)?)ms\b/i),r=i?Number(i[1]):void 0;return{timestamp:n.timestamp,durationMs:Number.isFinite(r)?r:void 0,summary:Ow(n)}})}function Uw(e){if(!e||e.length===0)return null;let n=0,s=0;for(const i of wp(e))typeof i.durationMs=="number"&&(n+=i.durationMs,s+=1);return s>0?n:null}const Cc=new Map;async function Bw(e,n){const s=Cc.get(e);if(s)return s;try{const i=await cp(e,n);return Cc.set(e,i.title),i.title}catch{return e}}const hu=12;function Hw(e){return e.length<=hu?e:e.slice(0,hu-3)+"..."}const Ec=new Map;async function qw(e,n){const s=Ec.get(e);if(s)return s;try{const i=await rp(e,n);return Ec.set(e,i.name),i.name}catch{return e}}function Vw(e){return typeof e=="string"&&ed.includes(e)?e:ps}function Ww(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}const Kw=new Set(["triage","todo"]),pu=new Set(["planning","researching","executing","finalizing","merging"]),Gw={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},Jw=new Set(["in-progress","in-review","done"]),Yw=3e4;function _c(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function Qw(e){const n=_c(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function Xw(e,n){const s=e.workflowStepResults;if(!s||s.length===0)return null;let i=0,r=0;for(const o of s){if(!o.startedAt)continue;const l=_c(o.startedAt);if(l==null)continue;let c;if(o.completedAt){const u=_c(o.completedAt);if(u==null||u<l)continue;c=u}else c=Math.max(l,n);i+=c-l,r+=1}return r>0?i:null}function fu(e,n){const s=typeof e.timedExecutionMs=="number"?e.timedExecutionMs:Uw(e.log),i=Xw(e,n);return s==null&&i==null?null:(s??0)+(i??0)}function Zw(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 eN(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 gu(e,n){if(!e&&!n)return!0;if(!e||!n)return!1;const s=Object.keys(e),i=Object.keys(n);return s.length!==i.length?!1:s.every(r=>e[r]===n[r])}function tN(e,n){return e.length!==n.length?!1:e.every((s,i)=>s.name===n[i]?.name&&s.status===n[i]?.status)}function nN(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function sN(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function iN(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(i=>typeof i=="string")};const s=e.message.match(/[A-Z]+-\d+/g)??[];return s.length>1?{dependentIds:[...new Set(s.slice(1))]}:null}function aN(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>{const r=n[i];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 rN(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>{const r=n[i];return r?s.filename===r.filename&&s.mimeType===r.mimeType&&s.size===r.size:!1})}function oN(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>{const r=n[i];return r?s.author===r.author&&s.text===r.text&&s.createdAt===r.createdAt:!1})}function lN(e,n){const s=e.task,i=n.task;return e.queued===n.queued&&e.projectId===n.projectId&&e.globalPaused===n.globalPaused&&e.taskStuckTimeoutMs===n.taskStuckTimeoutMs&&e.onOpenDetail===n.onOpenDetail&&e.addToast===n.addToast&&e.onUpdateTask===n.onUpdateTask&&e.onArchiveTask===n.onArchiveTask&&e.onUnarchiveTask===n.onUnarchiveTask&&e.onDeleteTask===n.onDeleteTask&&e.onRetryTask===n.onRetryTask&&e.onOpenDetailWithTab===n.onOpenDetailWithTab&&e.onOpenMission===n.onOpenMission&&e.onMoveTask===n.onMoveTask&&e.workflowStepNameLookup===n.workflowStepNameLookup&&s.id===i.id&&s.title===i.title&&s.description===i.description&&s.column===i.column&&s.columnMovedAt===i.columnMovedAt&&s.timedExecutionMs===i.timedExecutionMs&&s.updatedAt===i.updatedAt&&s.createdAt===i.createdAt&&s.status===i.status&&s.priority===i.priority&&s.executionMode===i.executionMode&&s.paused===i.paused&&s.error===i.error&&s.size===i.size&&s.blockedBy===i.blockedBy&&s.worktree===i.worktree&&s.baseBranch===i.baseBranch&&s.breakIntoSubtasks===i.breakIntoSubtasks&&s.currentStep===i.currentStep&&s.modelProvider===i.modelProvider&&s.modelId===i.modelId&&s.validatorModelProvider===i.validatorModelProvider&&s.validatorModelId===i.validatorModelId&&s.planningModelProvider===i.planningModelProvider&&s.planningModelId===i.planningModelId&&s.reviewLevel===i.reviewLevel&&s.missionId===i.missionId&&s.assignedAgentId===i.assignedAgentId&&s.mergeRetries===i.mergeRetries&&rN(s.attachments,i.attachments)&&oN(s.comments,i.comments)&&nN(s.dependencies,i.dependencies)&&tN(s.steps,i.steps)&&sN(s.enabledWorkflowSteps,i.enabledWorkflowSteps)&&aN(s.workflowStepResults,i.workflowStepResults)&&gu(s.prInfo,i.prInfo)&&gu(s.issueInfo,i.issueInfo)}function cN({task:e,projectId:n,queued:s,onOpenDetail:i,addToast:r,globalPaused:o,onUpdateTask:l,onArchiveTask:c,onUnarchiveTask:u,onDeleteTask:d,onRetryTask:m,onOpenDetailWithTab:h,taskStuckTimeoutMs:g,onOpenMission:p,onMoveTask:f,lastFetchTimeMs:x,workflowStepNameLookup:v}){const[b,y]=a.useState(!1),[S,k]=a.useState(!1),[R,N]=a.useState(!1),[M,C]=a.useState(e.description||""),[z,A]=a.useState(!1),[P,F]=a.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(j=>j.status==="done"||j.status==="skipped")),[W,$]=a.useState(null),[_,I]=a.useState(null),[O,J]=a.useState(!1),[Q,E]=a.useState(!1),[D,T]=a.useState(()=>Date.now()),w=a.useRef(null),q=a.useRef(!1),G=a.useRef(null),me=a.useRef(null),[ce,ae]=a.useState(!1),{badgeUpdates:pe,subscribeToBadge:U,unsubscribeFromBadge:Ne}=yp(n),{confirm:ne}=Ds(),xe=a.useRef(null),le=a.useRef(!1),ve=a.useCallback(j=>j instanceof Element?!!j.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);a.useEffect(()=>{C(e.description||"")},[e.id,e.description]),a.useEffect(()=>{if(!O)return;const j=V=>{me.current&&!me.current.contains(V.target)&&J(!1)};return document.addEventListener("click",j),()=>document.removeEventListener("click",j)},[O]),a.useEffect(()=>{if(!e.missionId){$(null);return}const j=Cc.get(e.missionId);if(j){$(j);return}let V=!1;return Bw(e.missionId,n).then(De=>{V||$(De)}),()=>{V=!0}},[e.missionId,n]),a.useEffect(()=>{if(!e.assignedAgentId){I(null);return}const j=Ec.get(e.assignedAgentId);if(j){I(j);return}I(null);let V=!1;return qw(e.assignedAgentId,n).then(De=>{V||I(De)}),()=>{V=!0}},[e.assignedAgentId,n]),a.useEffect(()=>{if(R&&w.current){const j=w.current;j.focus(),j.style.height="auto",j.style.height=j.scrollHeight+"px"}},[R]),a.useEffect(()=>{if(typeof IntersectionObserver>"u"){ae(!0);return}const j=G.current;if(!j)return;const V=new IntersectionObserver(([De])=>{ae(De?.isIntersecting??!0)},{rootMargin:"200px"});return V.observe(j),()=>V.disconnect()},[R,e.id]);const ee=a.useCallback(j=>{j.dataTransfer.setData("text/plain",e.id),j.dataTransfer.effectAllowed="move",y(!0)},[e.id]),Ee=a.useCallback(()=>{y(!1)},[]),Fe=a.useCallback(j=>j.dataTransfer.types.includes("Files"),[]),Ke=a.useCallback(j=>{Fe(j)&&(j.preventDefault(),j.stopPropagation(),j.dataTransfer.dropEffect="copy",k(!0))},[Fe]),Ze=a.useCallback(j=>{Fe(j)&&(j.preventDefault(),j.stopPropagation(),k(!1))},[Fe]),Xe=a.useCallback(async j=>{if(!Fe(j))return;j.preventDefault(),j.stopPropagation(),k(!1);const V=Array.from(j.dataTransfer.files);for(const De of V)try{await ur(e.id,De,n),r(`Attached ${De.name} to ${e.id}`,"success")}catch(nt){r(`Failed to attach ${De.name}: ${ke(nt)}`,"error")}},[e.id,Fe,r]),Qe=a.useCallback(()=>{R||i(e)},[e,i,R]),it=a.useCallback(j=>{if(q.current){q.current=!1;return}ve(j.target)||Qe()},[Qe,ve]),Ie=a.useCallback(j=>{const V=j.touches[0];V&&(xe.current={x:V.clientX,y:V.clientY,time:Date.now()},le.current=!1)},[]),Ge=a.useCallback(j=>{if(!xe.current)return;const V=j.touches[0];if(!V)return;const De=Math.abs(V.clientX-xe.current.x),nt=Math.abs(V.clientY-xe.current.y);(De>xu||nt>xu)&&(le.current=!0)},[]),se=a.useCallback(j=>{if(ve(j.target)||!xe.current)return;const De=Date.now()-xe.current.time<dN,nt=!le.current;De&&nt&&(q.current=!0,Qe()),xe.current=null,le.current=!1},[Qe,ve]),ye=a.useCallback(async(j,V)=>{j.stopPropagation();try{const De=await fo(V,n);i(De)}catch{r(`Failed to load dependency ${V}`,"error")}},[i,r]),Z=e.status==="failed",Te=e.paused===!0,ze=Vw(e.priority),be=ze!==ps,Me=vo(e,g,x),Be=e.column==="triage"&&e.status==="awaiting-approval",lt=e.column==="archived",je=!o&&!s&&!Z&&!Te&&!Me&&!Be&&(e.column==="in-progress"||pu.has(e.status)),ie=!s&&!Te&&!R&&!lt,Ae=Kw.has(e.column)&&!je&&!Te&&!s&&l,he=!!(e.prInfo||e.issueInfo),Re=!!(e.assignedAgentId&&_===null),Je=a.useMemo(()=>{const j=[];return e.modelProvider&&j.push(e.modelProvider),e.validatorModelProvider&&!j.includes(e.validatorModelProvider)&&j.push(e.validatorModelProvider),e.planningModelProvider&&!j.includes(e.planningModelProvider)&&j.push(e.planningModelProvider),j},[e.modelProvider,e.validatorModelProvider,e.planningModelProvider]),$e=a.useMemo(()=>jp(e,v),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,v]),de=$e.total>0&&(e.status==="executing"||e.column==="in-progress");a.useEffect(()=>{if(e.column!=="in-progress"&&e.column!=="in-review"||e.column==="in-progress"&&!(e.workflowStepResults??[]).some(De=>De.startedAt&&!De.completedAt)||e.column==="in-review"&&fu(e,Date.now())==null)return;T(Date.now());const j=window.setInterval(()=>{T(Date.now())},Yw);return()=>window.clearInterval(j)},[e.column,e.workflowStepResults,e.timedExecutionMs]);const re=a.useMemo(()=>{if(!Jw.has(e.column))return null;const j=fu(e,D);if(j==null)return null;if(e.column==="in-progress"){const St=Zw(j);return St?{label:St,title:`Execution time ${St}`,ariaLabel:`Execution time ${St}`}:null}const V=eN(j);if(!V)return null;const De=Qw(e);if(De==null)return{label:V,title:`Execution time ${V}`,ariaLabel:`Execution time ${V}`};const nt=new Date(De).toLocaleString();return{label:V,title:`Execution time ${V}. Completed ${nt}`,ariaLabel:`Execution time ${V}. Completed ${nt}`}},[e.column,e.columnMovedAt,e.timedExecutionMs,e.updatedAt,e.workflowStepResults,e.log,D]);a.useEffect(()=>{if(!he||!ce){Ne(e.id);return}return U(e.id),()=>{Ne(e.id)}},[he,ce,U,e.id,Ne]);const ue=pe.get(`${n??"default"}:${e.id}`),Pe=e.column==="in-progress"||e.column==="in-review",Se=a.useMemo(()=>e.steps.map(j=>`${j.name}:${j.status}`).join("|"),[e.steps]),{stats:fe}=$w(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:ce,worktree:e.worktree,stepVersion:Pe?Se:void 0,pollIntervalMs:Pe?3e4:void 0}),tt=a.useMemo(()=>Aw(e.id,n),[e.id,n]),ut=a.useMemo(()=>{const j=ue?.prInfo,V=ue?.timestamp,De=tt?.result?.prInfo,nt=tt?.timestamp?new Date(tt.timestamp).toISOString():void 0,St=e.prInfo,Pt=e.prInfo?.lastCheckedAt??e.updatedAt;let Rt=bo(j,V,St,Pt);const un=V&&V>=Pt?V:Pt;return De&&nt&&(!un||nt>un)&&(Rt=De),Rt},[ue,tt,e.prInfo,e.updatedAt]),vt=a.useMemo(()=>{const j=ue?.issueInfo,V=ue?.timestamp,De=tt?.result?.issueInfo,nt=tt?.timestamp?new Date(tt.timestamp).toISOString():void 0,St=e.issueInfo,Pt=e.issueInfo?.lastCheckedAt??e.updatedAt;let Rt=bo(j,V,St,Pt);const un=V&&V>=Pt?V:Pt;return De&&nt&&(!un||nt>un)&&(Rt=De),Rt},[ue,tt,e.issueInfo,e.updatedAt]),gt=a.useCallback(j=>{j?.stopPropagation(),!(!Ae||z)&&(N(!0),C(e.description||""))},[Ae,z,e.description]),dt=a.useCallback(()=>{N(!1),C(e.description||"")},[e.description]),wt=a.useCallback(()=>M!==(e.description||""),[M,e.description]),Mt=a.useCallback(async()=>{if(!(!l||z)){if(!wt()){dt();return}A(!0);try{await l(e.id,{description:M.trim()||void 0}),r(`Updated ${e.id}`,"success"),N(!1)}catch(j){r(`Failed to update ${e.id}: ${ke(j)}`,"error")}finally{A(!1)}}},[l,e.id,M,z,wt,dt,r]),yt=a.useCallback(j=>{j.key==="Enter"&&!j.shiftKey?(j.preventDefault(),Mt()):j.key==="Escape"&&(j.preventDefault(),dt())},[Mt,dt]),Et=a.useCallback(()=>{setTimeout(()=>{const j=document.activeElement;j===w.current||j?.closest(".card-editing-content")||(wt()?Mt():dt())},0)},[wt,Mt,dt]),Nt=a.useCallback(j=>{Ae&&(j.stopPropagation(),gt(j))},[Ae,gt]),Tt=a.useCallback(j=>{j.stopPropagation(),gt(j)},[gt]),Ht=a.useCallback(j=>{C(j.target.value);const V=j.target;V.style.height="auto",V.style.height=V.scrollHeight+"px"},[]),Ut=a.useCallback(j=>{j.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch(V=>{r(`Failed to archive ${e.id}: ${ke(V)}`,"error")})},[r,c,e.id]),Vt=a.useCallback(j=>{j.stopPropagation(),u&&u(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch(V=>{r(`Failed to unarchive ${e.id}: ${ke(V)}`,"error")})},[r,u,e.id]),zt=a.useCallback(async j=>{if(j.stopPropagation(),!(!d||!await ne({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0})))try{await d(e.id),r(`Deleted ${e.id}`,"success")}catch(De){const nt=iN(De);if(!nt||nt.dependentIds.length===0){r(`Failed to delete ${e.id}: ${ke(De)}`,"error");return}const St=nt.dependentIds.join(", ");if(!await ne({title:"Force Delete Task",message:`${e.id} is a dependency of ${St}.
|
|
617
|
+
|
|
618
|
+
Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await d(e.id,{removeDependencyReferences:!0}),r(`Deleted ${e.id} after removing dependency references`,"success")}catch(Rt){r(`Failed to delete ${e.id}: ${ke(Rt)}`,"error")}}},[r,ne,d,e.id]),Ct=a.useCallback(j=>{j.stopPropagation(),h?.(e,"changes")},[e,h]),At=a.useCallback(j=>{j.stopPropagation(),F(V=>!V)},[]),kt=a.useCallback(j=>{j.stopPropagation(),e.missionId&&p&&p(e.missionId)},[e.missionId,p]),Kt=a.useCallback(j=>{j.stopPropagation(),J(V=>!V)},[]),$t=a.useCallback((j,V)=>{j.stopPropagation(),J(!1),f&&f(e.id,V).then(()=>{r(`Moved ${e.id} to ${_n[V]}`,"success")}).catch(De=>{r(`Failed to move ${e.id}: ${ke(De)}`,"error")})},[r,f,e.id]),B=a.useCallback(async j=>{if(j.stopPropagation(),!(!m||Q)){E(!0);try{await m(e.id)}catch(V){r(`Failed to retry ${e.id}: ${ke(V)}`,"error")}finally{E(!1)}}},[r,Q,m,e.id]),ge=`card${b?" dragging":""}${s?" queued":""}${je?" agent-active":""}${Z?" failed":""}${Te?" paused":""}${Me?" stuck":""}${Be?" awaiting-approval":""}${S?" file-drop-target":""}${R?" card-editing":""}${z?" card-saving":""}`,te=(()=>{if(e.worktree&&e.column==="in-progress"){const j=fe?.filesChanged;return j==null||j===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Ct,disabled:!h,children:[t.jsx(In,{size:12}),t.jsxs("span",{children:[j," ",j===1?"file":"files"," changed"]})]})}if(e.column==="in-review"){const j=fe?.filesChanged,V=j==null?e.modifiedFiles?.length:void 0,De=j??V;return De==null||De===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Ct,disabled:!h,children:[t.jsx(In,{size:12}),t.jsxs("span",{children:[De," ",De===1?"file":"files"," changed"]})]})}if(e.column==="done"){const j=fe?.filesChanged,V=e.mergeDetails?.filesChanged,De=j??V;if(De!=null&&De>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Ct,disabled:!h,children:[t.jsx(In,{size:12}),t.jsxs("span",{children:[De," ",De===1?"file":"files"," changed"]})]});const nt=e.modifiedFiles?.length;if(nt!=null&&nt>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Ct,disabled:!h,children:[t.jsx(In,{size:12}),t.jsxs("span",{children:[nt," ",nt===1?"file":"files"," changed"]})]})}return null})();return R?t.jsx("div",{ref:G,className:ge,"data-id":e.id,onDoubleClick:Nt,children:t.jsxs("div",{className:"card-editing-content",children:[t.jsx("textarea",{ref:w,className:"card-edit-desc-textarea",placeholder:"Task description",value:M,onChange:Ht,onKeyDown:yt,onBlur:Et,disabled:z,rows:4}),z&&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:G,className:ge,"data-id":e.id,draggable:ie,onDragStart:ie?ee:void 0,onDragEnd:ie?Ee:void 0,onDragOver:Ke,onDragLeave:Ze,onDrop:Xe,onClick:it,onTouchStart:Ie,onTouchMove:Ge,onTouchEnd:se,onDoubleClick:Nt,children:[t.jsxs("div",{className:"card-header",children:[t.jsx("span",{className:"card-id",children:e.id}),Te&&t.jsx("span",{className:"card-status-badge paused",children:"paused"}),!Te&&e.status&&e.status!=="queued"&&t.jsx("span",{className:`card-status-badge card-status-badge--${e.column}${Be?" awaiting-approval":""}${pu.has(e.status)?" pulsing":""}${Z?" failed":""}${Me?" stuck":""}`,children:Me?"Stuck":Be?"Awaiting Approval":e.status}),Me&&(Te||!e.status||e.status==="queued")&&t.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),he&&t.jsx(vp,{prInfo:ut,issueInfo:vt}),be&&t.jsx("span",{className:`card-priority-badge card-priority-badge--${ze}`,children:ze}),e.executionMode==="fast"&&t.jsx("span",{className:"card-execution-mode-badge card-execution-mode-badge--fast",children:"Fast"}),e.missionId&&t.jsxs("span",{className:"card-mission-badge",onClick:kt,title:`Mission: ${W??e.missionId}`,role:p?"button":void 0,tabIndex:p?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.jsx(ls,{size:11}),Hw(W??e.missionId)]}),t.jsxs("div",{className:"card-header-actions",children:[Ae&&t.jsx("button",{className:"card-edit-btn",onClick:Tt,title:"Edit task","aria-label":"Edit task",children:t.jsx(Yn,{size:12})}),e.column==="triage"&&d&&t.jsx("button",{className:"card-delete-btn",onClick:zt,title:"Delete task","aria-label":"Delete task",children:t.jsx(Xt,{size:12})}),e.column==="done"&&c&&t.jsx("button",{className:"card-archive-btn",onClick:Ut,title:"Archive task","aria-label":"Archive task",children:"Archive"}),e.column==="archived"&&u&&t.jsx("button",{className:"card-unarchive-btn",onClick:Vt,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),e.column==="in-progress"&&f&&t.jsxs("div",{className:"card-send-back",ref:me,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(qt,{size:10})]}),O&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:Nc["in-progress"].filter(j=>j!=="in-review").map(j=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:V=>$t(V,j),children:_n[j]},j))})]}),e.column==="in-review"&&f&&t.jsxs("div",{className:"card-send-back",ref:me,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(qt,{size:10})]}),O&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:Nc["in-review"].map(j=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:V=>$t(V,j),children:j==="done"?"Done (no merge)":_n[j]},j))})]}),e.size&&t.jsx("span",{className:`card-size-badge size-${e.size.toLowerCase()}`,children:e.size})]})]}),Z&&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:B,disabled:Q,children:[t.jsx(Sb,{size:12}),Q?"Retrying…":"Retry"]})]}),t.jsx("div",{className:"card-title",title:e.title||e.description||void 0,children:vu(e.title,bu)||vu(e.description,bu)||e.id}),de&&(()=>{const j=$e.completed/$e.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:`${j}%`,backgroundColor:Gw[e.column]}})}),t.jsxs("span",{className:"card-progress-label",children:[$e.completed,"/",$e.total]})]}),t.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:At,"aria-expanded":P,"aria-label":P?"Hide steps":"Show steps",children:[t.jsxs("span",{children:[$e.total," step",$e.total===1?"":"s"]}),t.jsx(qt,{size:14,className:`card-steps-toggle-icon${P?" expanded":""}`})]}),P&&t.jsx("div",{className:"card-steps-list",children:$e.items.map(V=>{const De=V.source==="workflow"&&V.status==="failed";return t.jsxs("div",{className:"card-step-item",children:[t.jsx("span",{className:`card-step-dot card-step-dot--${V.status}${De?" card-step-dot--workflow-failed":""}`,"aria-hidden":"true"}),t.jsx("span",{className:`card-step-name${V.status==="done"?" completed":""}`,children:V.name}),V.source==="workflow"&&t.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${V.phase}`,title:"Workflow check",children:"workflow"})]},V.id)})})]})})(),(te||re)&&t.jsxs("div",{className:"card-footer-row",children:[te,re&&t.jsxs("span",{className:"card-time-indicator",title:re.title,"aria-label":re.ariaLabel,children:[t.jsx(yi,{size:12}),t.jsx("span",{children:re.label})]})]}),(e.dependencies&&e.dependencies.length>0||s||e.status==="queued"||e.blockedBy)&&t.jsxs("div",{className:"card-meta",children:[e.dependencies&&e.dependencies.length>0&&t.jsx("div",{className:"card-dep-list",children:e.dependencies.map(j=>t.jsxs("span",{className:"card-dep-badge clickable",onClick:V=>void ye(V,j),title:`Click to view ${j}`,children:[t.jsx(ua,{size:12,style:{verticalAlign:"middle"}})," ",j]},j))}),e.blockedBy&&t.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${e.blockedBy} (file overlap)`,children:[t.jsx(Ui,{size:12,style:{verticalAlign:"middle"}})," ",e.blockedBy]}),(s||e.status==="queued")&&e.column!=="in-progress"&&t.jsxs("span",{className:"queued-badge",children:[t.jsx(yi,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),(e.assignedAgentId||Je.length>0)&&t.jsxs("div",{className:"card-agent-row",children:[Je.length>0&&t.jsx("span",{className:"card-provider-icons","data-testid":"card-provider-icons",children:Je.map(j=>t.jsx(An,{provider:j,size:"sm"},j))}),e.assignedAgentId&&t.jsxs("span",{className:`card-agent-badge${Re?" card-agent-badge--loading":""}`,title:`Assigned to ${_??e.assignedAgentId}`,children:[t.jsx(gn,{size:11}),t.jsx("span",{className:"card-agent-badge-text",children:Ww(_??e.assignedAgentId,15)})]})]}),t.jsx(Oo,{slotId:"task-card-badge",projectId:n})]})}const xu=10,dN=300,bu=140;function vu(e,n){return e?e.length>n?e.slice(0,n)+"…":e:""}const yo=a.memo(cN,lN);yo.displayName="TaskCard";function uN({label:e,activeTasks:n,queuedTasks:s,projectId:i,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:u,onOpenDetailWithTab:d,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:g,workflowStepNameLookup:p}){return t.jsxs("div",{className:"worktree-group",children:[t.jsxs("div",{className:"worktree-group-header",children:[t.jsx("span",{className:"worktree-icon",children:e==="Up Next"||e==="Unassigned"?t.jsx(Gg,{size:14}):t.jsx(Js,{size:14})}),t.jsx("span",{className:"worktree-label",children:e})]}),n.map(f=>t.jsx(yo,{task:f,projectId:i,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:u,onOpenDetailWithTab:d,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:g,workflowStepNameLookup:p},f.id)),s.map(f=>t.jsx(yo,{task:f,projectId:i,queued:!0,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:u,onOpenDetailWithTab:d,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:g,workflowStepNameLookup:p},f.id))]})}const Np=a.memo(uN);Np.displayName="WorktreeGroup";function yu(e){return e.toLowerCase().replace(/[-_./]/g,"")}function mN(e,n){let s=0;for(let i=0;i<n.length&&s<e.length;i++)e[s]===n[i]&&s++;return s===e.length}function hN(e,n,s){const i=e.length,r=n.length;if(i===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<=i;c++){const u=new Array(r+1);u[0]=c;for(let d=1;d<=r;d++){const m=e[c-1]===n[d-1]?0:1;u[d]=Math.min(l[d]+1,u[d-1]+1,l[d-1]+m),c>=2&&d>=2&&e[c-1]===n[d-2]&&e[c-2]===n[d-1]&&(u[d]=Math.min(u[d],o[d-2]+1))}o=l,l=u}for(let c=0;c<=r;c++)if(l[c]<=s)return!0;return!1}function pN(e,n){const s=yu(e),i=yu(n);if(s.length===0||i.includes(s))return!0;const r=i.split(/\s+/).filter(Boolean);for(const o of r)if(s.length>=3&&mN(s,o)||s.length>=4&&hN(s,o,1))return!0;return!1}function fN(e,n){const s=n.toLowerCase().trim().split(/\s+/).filter(Boolean);return s.length===0?e:e.filter(i=>{const r=`${i.provider} ${i.id} ${i.name}`;return s.every(o=>pN(o,r))})}function $n({models:e,value:n,onChange:s,placeholder:i="Select a model…",disabled:r=!1,id:o,label:l,favoriteProviders:c=[],onToggleFavorite:u,favoriteModels:d=[],onToggleModelFavorite:m,noChangeValue:h,noChangeLabel:g="No change"}){const[p,f]=a.useState(!1),[x,v]=a.useState(""),[b,y]=a.useState(0),[S,k]=a.useState(null),[R,N]=a.useState(null),M=a.useRef(null),C=a.useRef(null),z=a.useRef(null),A=a.useRef(null),P=a.useRef(null),F=a.useMemo(()=>fN(e,x),[e,x]),W=a.useMemo(()=>F.reduce((ne,xe)=>((ne[xe.provider]??=[]).push(xe),ne),{}),[F]),$=a.useMemo(()=>{const ne=[];for(const xe of d){const le=xe.indexOf("/");if(le===-1)continue;const ve=xe.slice(0,le),ee=xe.slice(le+1),Ee=F.find(Fe=>Fe.provider===ve&&Fe.id===ee);Ee&&ne.push({model:Ee,fullId:xe})}return ne},[d,F]),_=a.useMemo(()=>{const ne=Object.entries(W),xe=new Set(c);return ne.sort(([le],[ve])=>{const ee=xe.has(le),Ee=xe.has(ve);if(ee&&!Ee)return-1;if(!ee&&Ee)return 1;if(ee&&Ee){const Fe=c.indexOf(le),Ke=c.indexOf(ve);if(Fe!==Ke)return Fe-Ke}return le.localeCompare(ve)})},[W,c]),I=typeof h=="string"&&h.length>0,O=a.useMemo(()=>{if(!n||I&&n===h)return null;const ne=n.indexOf("/");return ne===-1?null:n.slice(0,ne)},[I,h,n]),J=a.useMemo(()=>{const ne=[];return I&&ne.push({type:"no-change",value:h,label:g}),ne.push({type:"default",value:"",label:"Use default"}),ne},[I,g,h]),Q=a.useMemo(()=>{const ne=[...J];for(const{model:xe,fullId:le}of $)ne.push({type:"favorite",value:le,label:xe.name,provider:xe.provider});return _.forEach(([xe,le])=>{ne.push({type:"provider",value:`__group_${xe}`,label:xe,provider:xe}),le.forEach(ve=>{ne.push({type:"model",value:`${ve.provider}/${ve.id}`,label:ve.name,provider:ve.provider})})}),ne},[$,_,J]),E=a.useMemo(()=>{if(I&&n===h)return g;if(!n)return"Use default";const ne=n.indexOf("/");if(ne===-1)return n;const xe=n.slice(0,ne),le=n.slice(ne+1);return e.find(ee=>ee.provider===xe&&ee.id===le)?.name||n},[I,g,h,n,e]),D=a.useMemo(()=>Q.findIndex(ne=>ne.value===n),[Q,n]),T=a.useCallback(()=>{const ne=window.visualViewport;return ne&&ne.height>0&&ne.width>0?{width:ne.width,height:ne.height,offsetTop:ne.offsetTop,offsetLeft:ne.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),w=a.useCallback(()=>{const{height:ne}=T(),xe=typeof window.matchMedia=="function",le=xe?window.matchMedia("(max-width: 640px)").matches:!1,ve=xe?window.matchMedia("(max-width: 768px)").matches:!1;return ne<=0?320:le?Math.min(ne*.6,360):ve?Math.min(ne*.7,420):320},[T]),q=a.useCallback(()=>{const ne=C.current;if(!ne)return;const xe=ne.getBoundingClientRect(),{width:le,height:ve,offsetTop:ee,offsetLeft:Ee}=T(),Fe=16,Ke=16,Ze=4,Xe=w(),Qe=xe.bottom-ee,it=xe.top-ee,Ie=xe.left-Ee,Ge=ve-Qe,se=it,ye=Math.max(Ge-Ke-Ze,160),Z=Math.max(se-Ke-Ze,160),Te=Ge<Xe&&se>Ge,ze=Math.max(Math.min(Te?Z:ye,Xe),160),be=Math.min(xe.width,le-Fe*2),Me=Math.min(Math.max(Ie,Fe),le-Fe-be)+Ee,Be=Te?Math.max(Ke+ee,it-ze-Ze+ee):Math.min(Qe+Ze+ee,ve+ee-Ke-ze);k({top:Be,left:Me,width:be,maxHeight:ze})},[T,w]);a.useEffect(()=>{N(document.body)},[]);const G=a.useRef(!1);a.useEffect(()=>{if(!p){G.current=!1;return}if(G.current||Q.length===0)return;const ne=Q.findIndex((xe,le)=>le>=(D>=0?D:0)&&xe.type!=="provider");y(ne>=0?ne:0),G.current=!0},[p,Q,D]),a.useEffect(()=>{p&&G.current&&(y(0),P.current&&(P.current.scrollTop=0))},[x,p]),a.useEffect(()=>{if(!p)return;q();const ne=requestAnimationFrame(()=>A.current?.focus());return()=>cancelAnimationFrame(ne)},[p,q]),a.useEffect(()=>{if(!p)return;const ne=()=>q();window.addEventListener("resize",ne),window.addEventListener("scroll",ne,!0);const xe=window.visualViewport;return xe&&(xe.addEventListener("resize",ne),xe.addEventListener("scroll",ne)),()=>{window.removeEventListener("resize",ne),window.removeEventListener("scroll",ne,!0),xe&&(xe.removeEventListener("resize",ne),xe.removeEventListener("scroll",ne))}},[p,q]),a.useEffect(()=>{if(!p)return;const ne=xe=>{const le=xe.target,ve=M.current?.contains(le),ee=z.current?.contains(le);!ve&&!ee&&(f(!1),v(""))};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[p]);const me=a.useCallback(ne=>{switch(ne.key){case"ArrowDown":if(ne.preventDefault(),!p)f(!0);else{let xe=b;for(let le=1;le<=Q.length;le++){const ve=(b+le)%Q.length;if(Q[ve]?.type!=="provider"){xe=ve;break}}y(xe)}break;case"ArrowUp":if(ne.preventDefault(),p){let xe=b;for(let le=1;le<=Q.length;le++){const ve=(b-le+Q.length)%Q.length;if(Q[ve]?.type!=="provider"){xe=ve;break}}y(xe)}break;case"Enter":if(ne.preventDefault(),p){const xe=Q[b];xe&&xe.type!=="provider"&&xe.type!=="favorite"&&(s(xe.value),f(!1),v(""))}else f(!0);break;case"Escape":ne.preventDefault(),f(!1),v("");break;case"Tab":p&&(f(!1),v(""));break}},[p,b,Q,s]),ce=a.useCallback(ne=>{s(ne),f(!1),v("")},[s]),ae=a.useCallback(()=>{v(""),A.current?.focus()},[]),pe=a.useCallback(()=>{r||f(ne=>!ne)},[r]);a.useEffect(()=>{if(p&&P.current){const ne=P.current.querySelector(`[data-index="${b}"]`);ne&&typeof ne.scrollIntoView=="function"&&ne.scrollIntoView({block:"nearest"})}},[b,p]);const U=x.length>0,Ne=p&&S?t.jsxs("div",{ref:z,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:me,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:A,type:"text",className:"model-combobox-search",placeholder:"Filter models…",value:x,onChange:ne=>v(ne.target.value),onClick:ne=>ne.stopPropagation()}),U&&t.jsx("button",{type:"button",className:"model-combobox-clear",onClick:ae,"aria-label":"Clear filter",children:"×"})]}),t.jsxs("div",{className:"model-combobox-results-count",children:[F.length," model",F.length!==1?"s":""]}),t.jsxs("div",{ref:P,className:"model-combobox-list",children:[J.map((ne,xe)=>t.jsx("div",{"data-index":xe,className:`model-combobox-option ${b===xe?"model-combobox-option--highlighted":""} ${n===ne.value?"model-combobox-option--selected":""}`,onClick:()=>ce(ne.value),onMouseEnter:()=>y(xe),role:"option","aria-selected":n===ne.value,children:t.jsx("span",{className:"model-combobox-option-text model-combobox-option-text--default",children:ne.label})},`${ne.type}-${ne.value}`)),$.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"model-combobox-divider"}),$.map(({model:ne,fullId:xe},le)=>{const ve=le+J.length,ee=b===ve,Ee=n===xe;return t.jsxs("div",{"data-index":ve,className:`model-combobox-option model-combobox-option--favorite ${ee?"model-combobox-option--highlighted":""} ${Ee?"model-combobox-option--selected":""}`,onClick:()=>ce(xe),onMouseEnter:()=>y(ve),role:"option","aria-selected":Ee,children:[t.jsxs("span",{className:"model-combobox-option-main",children:[t.jsx("span",{className:"model-combobox-option-icon",children:t.jsx(An,{provider:ne.provider,size:"sm"})}),t.jsx("span",{className:"model-combobox-option-text",children:ne.name})]}),t.jsx("span",{className:"model-combobox-option-id",children:ne.id}),m&&t.jsx("button",{type:"button",className:"model-combobox-option-favorite model-combobox-option-favorite--active",onClick:Fe=>{Fe.stopPropagation(),m(xe)},title:"Remove from favorites","aria-label":`Remove ${ne.name} from favorites`,children:"★"})]},xe)}),t.jsx("div",{className:"model-combobox-divider"})]}),_.map(([ne,xe])=>{const le=Q.findIndex(Ee=>Ee.value===`__group_${ne}`),ve=c.includes(ne),ee=xe.filter(Ee=>{const Fe=`${Ee.provider}/${Ee.id}`;return!d.includes(Fe)});return ee.length===0?null:t.jsxs("div",{className:"model-combobox-group",children:[t.jsxs("div",{className:"model-combobox-optgroup","data-index":le,children:[t.jsx(An,{provider:ne,size:"sm"}),t.jsx("span",{className:"model-combobox-optgroup-text",children:ne}),u&&t.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${ve?"model-combobox-optgroup-favorite--active":""}`,onClick:Ee=>{Ee.stopPropagation(),u(ne)},title:ve?"Remove from favorites":"Add to favorites","aria-label":ve?`Remove ${ne} from favorites`:`Add ${ne} to favorites`,children:"★"})]}),ee.map(Ee=>{const Fe=`${Ee.provider}/${Ee.id}`,Ke=Q.findIndex(it=>it.value===Fe),Ze=b===Ke,Xe=n===Fe,Qe=d.includes(Fe);return t.jsxs("div",{"data-index":Ke,className:`model-combobox-option ${Ze?"model-combobox-option--highlighted":""} ${Xe?"model-combobox-option--selected":""}`,onClick:()=>ce(Fe),onMouseEnter:()=>y(Ke),role:"option","aria-selected":Xe,children:[t.jsx("span",{className:"model-combobox-option-text",children:Ee.name}),t.jsx("span",{className:"model-combobox-option-id",children:Ee.id}),m&&t.jsx("button",{type:"button",className:`model-combobox-option-favorite ${Qe?"model-combobox-option-favorite--active":""}`,onClick:it=>{it.stopPropagation(),m(Fe)},title:Qe?"Remove from favorites":"Add to favorites","aria-label":Qe?`Remove ${Ee.name} from favorites`:`Add ${Ee.name} to favorites`,children:Qe?"★":"☆"})]},Fe)})]},ne)}),F.length===0&&U&&t.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",x,"'"]})]})]}):null;return t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:M,className:"model-combobox",onKeyDown:me,children:t.jsxs("button",{ref:C,type:"button",id:o,className:"model-combobox-trigger",onClick:pe,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":l,children:[O&&t.jsx("span",{className:"model-combobox-trigger-icon",children:t.jsx(An,{provider:O,size:"sm"})}),t.jsx("span",{className:"model-combobox-trigger-text",children:E||i}),t.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),R&&Ne?Xa.createPortal(Ne,R):null]})}function td(e,n){return typeof n!="string"||n.length===0?e:`kb:${n}:${e}`}function Dn(e,n){return typeof window>"u"?null:window.localStorage.getItem(td(e,n))}function os(e,n,s){typeof window>"u"||window.localStorage.setItem(td(e,s),n)}function pr(e,n){typeof window>"u"||window.localStorage.removeItem(td(e,n))}const gN=1e4,xN=1e3;function Bo(){const[e,n]=a.useState([]),[s,i]=a.useState(!0),[r,o]=a.useState(null),l=a.useRef(null),c=a.useRef(0),u=a.useCallback(async()=>{try{o(null);const p=await xo();n(p)}catch(p){o(p instanceof Error?p.message:"Failed to fetch nodes")}},[]);a.useEffect(()=>{let p=!1;async function f(){i(!0);try{const v=await xo();p||(n(v),o(null))}catch(v){p||o(v instanceof Error?v.message:"Failed to fetch nodes")}finally{p||i(!1)}}f();const x=()=>{if(document.visibilityState!=="visible")return;const v=Date.now();v-c.current<xN||(c.current=v,u())};return document.addEventListener("visibilitychange",x),()=>{p=!0,document.removeEventListener("visibilitychange",x)}},[u]),a.useEffect(()=>{if(!s)return l.current=setInterval(()=>{u()},gN),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async p=>{const f=await _k(p);return n(x=>[...x,f]),f},[]),m=a.useCallback(async(p,f)=>{const x=await Mk(p,f);return n(v=>v.map(b=>b.id===p?x:b)),x},[]),h=a.useCallback(async p=>{await Ak(p),n(f=>f.filter(x=>x.id!==p))},[]),g=a.useCallback(async p=>{const f=await Rk(p);n(x=>x.map(v=>v.id===p?{...v,status:f.status,updatedAt:f.checkedAt}:v))},[]);return{nodes:e,loading:s,error:r,refresh:u,register:d,update:m,unregister:h,healthCheck:g}}const $a="kb-quick-entry-text",bN=["image/png","image/jpeg","image/gif","image/webp"];function ku(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function vN(e){return e==="online"?"quick-entry-node-status--online":e==="connecting"?"quick-entry-node-status--connecting":e==="error"?"quick-entry-node-status--error":"quick-entry-node-status--offline"}function fl(e,n){return e&&n?`${e}/${n}`:""}function gl(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 Sp({onCreate:e,addToast:n,tasks:s=[],availableModels:i,onPlanningMode:r,onSubtaskBreakdown:o,projectId:l,autoExpand:c=!0,favoriteProviders:u,favoriteModels:d,onToggleFavorite:m,onToggleModelFavorite:h}){const[g,p]=a.useState(()=>typeof window<"u"&&Dn($a,l)||""),[f,x]=a.useState(!1),[v,b]=a.useState(!1),[y,S]=a.useState(!1),k=a.useRef(null),R=a.useRef(null),N=a.useRef(!1),M=a.useRef(l),[C,z]=a.useState([]),A=a.useRef([]),[P,F]=a.useState([]),[W,$]=a.useState(!1),[_,I]=a.useState(""),[O,J]=a.useState(null),[Q,E]=a.useState([]),[D,T]=a.useState(void 0),[w,q]=a.useState(!1),[G,me]=a.useState(!1),[ce,ae]=a.useState(!1),[pe,U]=a.useState(null),[Ne,ne]=a.useState(void 0),[xe,le]=a.useState(void 0),[ve,ee]=a.useState(void 0),[Ee,Fe]=a.useState(void 0),[Ke,Ze]=a.useState(void 0),[Xe,Qe]=a.useState(void 0),it=a.useRef(null),Ie=a.useRef(null),Ge=a.useRef(null),se=a.useRef(null),[ye,Z]=a.useState(null),[Te,ze]=a.useState(null),be=a.useRef(null),Me=a.useRef(null),[Be,lt]=a.useState(null),[je]=a.useState(()=>typeof document<"u"?document.body:null),[ie,Ae]=a.useState(!1),[he,Re]=a.useState(null),[Je,$e]=a.useState(i??[]),[de,re]=a.useState([]),[ue,Pe]=a.useState([]),[Se,fe]=a.useState(null),[tt,ut]=a.useState(void 0),[vt,gt]=a.useState(!1),[dt,wt]=a.useState(void 0),{nodes:Mt}=Bo(),[yt,Et]=a.useState(!1),[Nt,Tt]=a.useState(!1),Ht=a.useRef(null),Ut=a.useRef(null),[Vt,zt]=a.useState(null),Ct=u??de,At=d??ue,kt=!e;a.useEffect(()=>{if(i)$e(i),Ae(!1),Re(null);else{let oe=!1;return Ae(!0),Re(null),cs().then(_e=>{oe||($e(_e.models),u||re(_e.favoriteProviders),d||Pe(_e.favoriteModels))}).catch(_e=>{oe||Re(ke(_e)||"Failed to load models")}).finally(()=>{oe||Ae(!1)}),Lo(l).then(_e=>{oe||fe(_e)}).catch(()=>{}),()=>{oe=!0}}},[i,u,d,l]);const Kt=fl(Ne,xe),$t=fl(ve,Ee),B=fl(Ke,Xe),ge=!!(Ne&&xe),te=!!(ve&&Ee),j=!!(Ke&&Xe),V=Number(ge)+Number(te)+Number(j),De=tt?Se?.modelPresets?.find(oe=>oe.id===tt)?.name??"Models":V>0?`${V} model${V===1?"":"s"}`:"Models",nt=a.useCallback((oe,_e)=>{if(!oe||!_e)return"Using default";const at=Je.find(We=>We.provider===oe&&We.id===_e);return at?`${at.provider}/${at.id}`:`${oe}/${_e}`},[Je]);a.useEffect(()=>{p(Dn($a,l)||"")},[l]),a.useEffect(()=>{typeof window<"u"&&os($a,g,l)},[g,l]),a.useEffect(()=>{M.current!==l&&(M.current=l,E([]),T(void 0),J(null),q(!1),Z(null))},[l]),a.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),a.useEffect(()=>{A.current=C},[C]),a.useEffect(()=>()=>{A.current.forEach(oe=>URL.revokeObjectURL(oe.previewUrl))},[]);const St=a.useCallback(()=>{const oe=k.current;if(!oe)return;oe.style.height="auto";const _e=Math.min(oe.scrollHeight,200);oe.style.height=`${_e}px`},[]);a.useEffect(()=>{v&&St()},[g,v,St]),a.useEffect(()=>{if(!f&&g===""&&k.current){const oe=setTimeout(()=>{k.current?.focus()},0);return()=>clearTimeout(oe)}},[f,g]),a.useEffect(()=>{W||I("")},[W]),a.useEffect(()=>{if(!yt)return;const oe=_e=>{const at=_e.target,We=Ht.current?.contains(at),mt=Ut.current?.contains(at);!We&&!mt&&Et(!1)};return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[yt]),a.useEffect(()=>{if(!ce)return;const oe=_e=>{const at=_e.target,We=it.current?.contains(at),mt=Ie.current?.contains(at),fn=at instanceof Element&&at.closest?.(".model-combobox-dropdown--portal")!=null;!We&&!mt&&!fn&&(ae(!1),U(null))};return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[ce]),a.useEffect(()=>{if(!w)return;const oe=_e=>{const at=_e.target;Ge.current?.contains(at)||se.current?.contains(at)||(q(!1),Z(null))};return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[w]);const Pt=a.useCallback(()=>{C.forEach(oe=>URL.revokeObjectURL(oe.previewUrl)),z([]),R.current&&(R.current.value=""),p(""),F([]),J(null),q(!1),Z(null),ne(void 0),le(void 0),ee(void 0),Fe(void 0),Ze(void 0),Qe(void 0),ut(void 0),gt(!1),wt(void 0),$(!1),ae(!1),ze(null),U(null),Et(!1),Tt(!1),b(!1),S(!1),N.current=!0,k.current&&(k.current.style.height="auto"),typeof window<"u"&&pr($a,l)},[C,l]),Rt=a.useCallback(oe=>{if(!oe||oe.length===0)return;const _e=[];for(let at=0;at<oe.length;at++){const We=oe[at];bN.includes(We.type)&&_e.push({file:We,previewUrl:URL.createObjectURL(We)})}_e.length>0&&z(at=>[...at,..._e])},[]),un=a.useCallback(oe=>{f||Rt(oe.clipboardData?.files)},[Rt,f]),mn=a.useCallback(oe=>{z(_e=>{const at=_e[oe];return at&&URL.revokeObjectURL(at.previewUrl),_e.filter((We,mt)=>mt!==oe)})},[]),wn=a.useCallback(async()=>{const oe=g.trim();if(!oe||f||!e)return;const _e=g;x(!0),p("");try{const at=await e({description:oe,column:"triage",dependencies:P.length?P:void 0,...O?{assignedAgentId:O}:{},modelPresetId:tt,modelProvider:ge?Ne:void 0,modelId:ge?xe:void 0,validatorModelProvider:te?ve:void 0,validatorModelId:te?Ee:void 0,planningModelProvider:j?Ke:void 0,planningModelId:j?Xe:void 0,...vt?{executionMode:"fast"}:{},nodeId:dt});if(at&&C.length>0){const We=[];for(const mt of C)try{await ur(at.id,mt.file,l)}catch{We.push(mt.file.name)}We.length>0&&n(`Failed to upload: ${We.join(", ")}`,"error")}Pt()}catch(at){p(_e),n(ke(at)||"Failed to create task","error")}finally{x(!1)}},[g,f,e,P,O,ge,Ne,xe,te,ve,Ee,j,Ke,Xe,C,l,n,Pt,vt,dt]),Gt=a.useCallback(oe=>{if(oe.key==="Enter"){if(oe.shiftKey&&v)return;oe.preventDefault(),wn()}else if(oe.key==="Escape"){if(oe.preventDefault(),pe){U(null);return}if(ce){ae(!1),ze(null);return}if(W){$(!1);return}if(yt){Et(!1);return}if(w){q(!1),Z(null);return}g.trim()&&(p(""),k.current&&(k.current.style.height="auto"),typeof window<"u"&&pr($a,l)),b(!1),S(!1),k.current?.blur()}},[wn,g,v,W,w,ce,pe,yt,l,S]),es=a.useCallback(()=>{N.current&&(N.current=!1)},[]),we=a.useCallback(()=>{c&&b(!0)},[c]),rt=a.useCallback(oe=>{F(_e=>_e.includes(oe)?_e.filter(at=>at!==oe):[..._e,oe])},[]),Jt=a.useCallback(()=>{const oe=window.visualViewport;return oe&&oe.width>0&&oe.height>0?{width:oe.width,height:oe.height,offsetTop:oe.offsetTop,offsetLeft:oe.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),Sn=a.useCallback(()=>{const oe=it.current;if(!oe)return;const _e=oe.getBoundingClientRect(),{width:at,height:We,offsetTop:mt,offsetLeft:fn}=Jt(),Yt=16,tn=16,rn=4,On=at<=768,Un=Math.min(On?We*.6:We*.5,360),xs=On?Math.min(at-Yt*2,360):Math.max(_e.width,240),kn=Math.min(xs,Math.max(at-Yt*2,200)),Ln=_e.top-mt,Wn=_e.bottom-mt,_s=_e.left-fn,zn=We-Wn,is=Ln,Ms=Math.max(zn-tn-rn,160),bs=Math.max(is-tn-rn,160),Kn=zn<Un&&is>zn,Gn=Math.max(Math.min(Kn?bs:Ms,Un),160),ei=Math.min(Math.max(_s,Yt),at-Yt-kn)+fn,zs=Kn?Math.max(tn+mt,Ln-Gn-rn+mt):Math.min(Wn+rn+mt,We+mt-tn-Gn);ze({top:zs,left:ei,width:kn,maxHeight:Gn})},[Jt]),Cn=a.useCallback(()=>{const oe=Ht.current?.querySelector(".refine-button");if(!oe)return;const _e=oe.getBoundingClientRect(),{width:at,height:We,offsetTop:mt,offsetLeft:fn}=Jt(),Yt=8,tn=12,rn=4,On=Math.min(200,Math.max(We-tn*2,160)),Un=Math.min(200,at-Yt*2),xs=_e.top-mt,kn=_e.bottom-mt,Ln=_e.left-fn,Wn=We-kn,_s=xs,zn=Wn<On&&_s>Wn,is=Math.min(Math.max(Ln,Yt),at-Yt-Un)+fn,Ms=zn?Math.max(tn+mt,xs-On-rn+mt):Math.min(kn+rn+mt,We+mt-tn-On);zt({top:Ms,left:is})},[Jt]),pn=a.useCallback(()=>{const oe=be.current;if(!oe)return;const _e=oe.getBoundingClientRect(),{width:at,height:We,offsetTop:mt,offsetLeft:fn}=Jt(),Yt=16,tn=16,rn=4,On=at<=768,Un=Math.min(On?We*.6:We*.5,320),xs=On?Math.min(at-Yt*2,360):Math.max(_e.width,280),kn=Math.min(xs,Math.max(at-Yt*2,240)),Ln=_e.top-mt,Wn=_e.bottom-mt,_s=_e.left-fn,zn=We-Wn,is=Ln,Ms=Math.max(zn-tn-rn,200),bs=Math.max(is-tn-rn,200),Kn=zn<Un&&is>zn,Gn=Math.max(Math.min(Kn?bs:Ms,Un),200),ei=Math.min(Math.max(_s,Yt),at-Yt-kn)+fn,zs=Kn?Math.max(tn+mt,Ln-Gn-rn+mt):Math.min(Wn+rn+mt,We+mt-tn-Gn);lt({top:zs,left:ei,width:kn,maxHeight:Gn})},[Jt]),bn=a.useCallback(()=>{const oe=Ge.current?.querySelector("button");if(!oe)return;const _e=oe.getBoundingClientRect(),{width:at,height:We,offsetTop:mt,offsetLeft:fn}=Jt(),Yt=16,tn=16,rn=4,On=at<=768,Un=Math.min(On?We*.6:We*.5,320),xs=On?Math.min(at-Yt*2,280):Math.max(_e.width,240),kn=Math.min(xs,Math.max(at-Yt*2,200)),Ln=_e.top-mt,Wn=_e.bottom-mt,_s=_e.left-fn,zn=We-Wn,is=Ln,Ms=Math.max(zn-tn-rn,160),bs=Math.max(is-tn-rn,160),Kn=zn<Un&&is>zn,Gn=Math.max(Math.min(Kn?bs:Ms,Un),160),ei=Math.min(Math.max(_s,Yt),at-Yt-kn)+fn,zs=Kn?Math.max(tn+mt,Ln-Gn-rn+mt):Math.min(Wn+rn+mt,We+mt-tn-Gn);Z({top:zs,left:ei,width:kn,maxHeight:Gn})},[Jt]);a.useEffect(()=>{if(!ce)return;const oe=()=>Sn();window.addEventListener("resize",oe),window.addEventListener("scroll",oe,!0);const _e=window.visualViewport;return _e&&(_e.addEventListener("resize",oe),_e.addEventListener("scroll",oe)),()=>{window.removeEventListener("resize",oe),window.removeEventListener("scroll",oe,!0),_e&&(_e.removeEventListener("resize",oe),_e.removeEventListener("scroll",oe))}},[ce,Sn]),a.useEffect(()=>{if(!yt)return;const oe=()=>Cn();window.addEventListener("resize",oe),window.addEventListener("scroll",oe,!0);const _e=window.visualViewport;return _e&&(_e.addEventListener("resize",oe),_e.addEventListener("scroll",oe)),()=>{window.removeEventListener("resize",oe),window.removeEventListener("scroll",oe,!0),_e&&(_e.removeEventListener("resize",oe),_e.removeEventListener("scroll",oe))}},[yt,Cn]),a.useEffect(()=>{if(!W)return;const oe=()=>pn();window.addEventListener("resize",oe),window.addEventListener("scroll",oe,!0);const _e=window.visualViewport;return _e&&(_e.addEventListener("resize",oe),_e.addEventListener("scroll",oe)),()=>{window.removeEventListener("resize",oe),window.removeEventListener("scroll",oe,!0),_e&&(_e.removeEventListener("resize",oe),_e.removeEventListener("scroll",oe))}},[W,pn]),a.useEffect(()=>{if(!w)return;const oe=()=>bn();window.addEventListener("resize",oe),window.addEventListener("scroll",oe,!0);const _e=window.visualViewport;return _e&&(_e.addEventListener("resize",oe),_e.addEventListener("scroll",oe)),()=>{window.removeEventListener("resize",oe),window.removeEventListener("scroll",oe,!0),_e&&(_e.removeEventListener("resize",oe),_e.removeEventListener("scroll",oe))}},[w,bn]);const Rn=a.useCallback(oe=>{const _e=gl(oe);Ze(_e.provider),Qe(_e.modelId)},[]),vn=a.useCallback(oe=>{const _e=gl(oe);ne(_e.provider),le(_e.modelId)},[]),Y=a.useCallback(oe=>{const _e=gl(oe);ee(_e.provider),Fe(_e.modelId)},[]),Oe=a.useCallback(async oe=>{if(m){m(oe);return}const _e=de,We=_e.includes(oe)?_e.filter(mt=>mt!==oe):[oe,..._e];re(We);try{await sn({favoriteProviders:We,favoriteModels:ue})}catch{re(_e)}},[de,ue,m]),Ye=a.useCallback(async oe=>{if(h){h(oe);return}const _e=ue,We=_e.includes(oe)?_e.filter(mt=>mt!==oe):[oe,..._e];Pe(We);try{await sn({favoriteProviders:de,favoriteModels:We})}catch{Pe(_e)}},[ue,de,h]),st=a.useCallback(()=>{const oe=g.trim();if(!oe){n("Enter a description first","error");return}r?.(oe),Pt()},[g,r,n,Pt]),pt=a.useCallback(()=>{const oe=g.trim();if(!oe){n("Enter a description first","error");return}o?.(oe),Pt()},[g,o,n,Pt]),jt=a.useCallback(()=>{wn()},[wn]),_t=a.useCallback(async oe=>{const _e=g.trim();if(!(!_e||Nt)){Et(!1),Tt(!0);try{const at=await sp(_e,oe,l);p(at),n("Description refined with AI","success"),k.current&&(k.current.style.height="auto",k.current.style.height=`${Math.min(k.current.scrollHeight,200)}px`)}catch(at){const We=ip(at);n(We,"error")}finally{Tt(!1)}}},[g,Nt,n,l]),yn=(oe,_e)=>oe.length>_e?oe.slice(0,_e)+"…":oe,en=a.useCallback(async()=>{if(i){$e(i),Re(null),Ae(!1);return}Ae(!0),Re(null);try{const oe=await cs();$e(oe.models),u||re(oe.favoriteProviders),d||Pe(oe.favoriteModels)}catch(oe){Re(ke(oe)||"Failed to load models")}finally{Ae(!1)}},[i,u,d]),xt=a.useCallback(async()=>{if(Q.length>0&&D===l){q(!0),bn();return}me(!0);try{const oe=await Na(void 0,l);E(oe),T(l),q(!0),bn()}catch(oe){const _e=ke(oe);n(_e?`Failed to load agents: ${_e}`:"Failed to load agents","error"),q(!1)}finally{me(!1)}},[Q.length,D,l,n,bn]),ns=(O?Q.find(oe=>oe.id===O):void 0)?.name??O,ss=y,Si=a.useCallback(()=>{S(oe=>{const _e=!oe;return b(_e),_e})},[]);return t.jsxs("div",{className:`quick-entry-box ${y?"quick-entry-box--expanded":"quick-entry-box--collapsed"}`,"data-testid":"quick-entry-box",children:[t.jsx("div",{className:"description-with-refine",children:t.jsxs("div",{className:"quick-entry-main-row",children:[t.jsx("div",{className:"quick-entry-textarea-wrap",children:t.jsx("textarea",{ref:k,className:`quick-entry-input ${v?"quick-entry-input--expanded":""}`,placeholder:f?"Creating...":"Add a task...",value:g,onChange:oe=>p(oe.target.value),onKeyDown:Gt,onPaste:un,onFocus:we,onBlur:es,disabled:f||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:Si,"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(qt,{size:14})})]})}),t.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!ss,"aria-hidden":!ss,children:[ss&&!f&&t.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:st,onMouseDown:oe=>oe.preventDefault(),disabled:!g.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[t.jsx(Ys,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:pt,onMouseDown:oe=>oe.preventDefault(),disabled:!g.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[t.jsx(Po,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),t.jsxs("div",{className:"refine-trigger-wrap",ref:Ht,children:[t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${Nt?"refine-button--loading":""}`,onClick:()=>{Et(oe=>{const _e=!oe;return _e?Cn():zt(null),_e})},disabled:!g.trim()||Nt,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(qn,{size:12,style:{verticalAlign:"middle"}}),Nt?"Refining...":"Refine"]}),yt&&je&&Vt&&Xa.createPortal(t.jsxs("div",{ref:Ut,className:"refine-menu refine-menu--portal",onMouseDown:oe=>oe.preventDefault(),style:{position:"fixed",top:`${Vt.top}px`,left:`${Vt.left}px`},children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>_t("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:()=>_t("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:()=>_t("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:()=>_t("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"})]})]}),je)]}),t.jsx("div",{className:"dep-trigger-wrap",children:t.jsxs("button",{ref:be,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{$(oe=>{const _e=!oe;return _e?(ae(!1),ze(null),U(null),q(!1),pn()):lt(null),_e})},children:[t.jsx(ua,{size:12,style:{verticalAlign:"middle"}}),P.length>0?`${P.length} deps`:"Deps"]})}),W&&je&&Be&&(()=>{const oe=_.toLowerCase(),_e=(oe?s.filter(at=>at.id.toLowerCase().includes(oe)||at.title&&at.title.toLowerCase().includes(oe)||at.description&&at.description.toLowerCase().includes(oe)):[...s]).sort((at,We)=>{const mt=We.createdAt.localeCompare(at.createdAt);if(mt!==0)return mt;const fn=parseInt(at.id.slice(at.id.lastIndexOf("-")+1),10)||0;return(parseInt(We.id.slice(We.id.lastIndexOf("-")+1),10)||0)-fn});return Xa.createPortal(t.jsxs("div",{ref:Me,className:"dep-dropdown dep-dropdown--portal",onMouseDown:at=>at.preventDefault(),style:{position:"fixed",top:`${Be.top}px`,left:`${Be.left}px`,width:`${Be.width}px`,maxHeight:Be.maxHeight?`${Be.maxHeight}px`:void 0,overflowY:Be.maxHeight?"auto":void 0},children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:_,onChange:at=>I(at.target.value),onClick:at=>at.stopPropagation()}),_e.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):_e.map(at=>t.jsxs("div",{className:`dep-dropdown-item${P.includes(at.id)?" selected":""}`,onMouseDown:We=>We.preventDefault(),onClick:()=>rt(at.id),children:[t.jsx("span",{className:"dep-dropdown-id",children:at.id}),t.jsx("span",{className:"dep-dropdown-title",children:yn(at.title||at.description||at.id,60)})]},at.id))]}),je)})(),t.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>R.current?.click(),children:[t.jsx(pb,{size:12,style:{verticalAlign:"middle"}}),C.length>0?`Attach (${C.length})`:"Attach"]}),t.jsxs("button",{ref:it,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{$(!1),q(!1),U(null),ae(!0),Sn()},children:[t.jsx(co,{size:12,style:{verticalAlign:"middle"}}),De]}),t.jsxs("label",{className:"quick-entry-node-wrap",htmlFor:"quick-entry-node-select",children:[t.jsx("span",{className:"visually-hidden",children:"Execution Node Override"}),t.jsxs("select",{id:"quick-entry-node-select",className:"select quick-entry-node-select","data-testid":"quick-entry-node-select",value:dt??"",onChange:oe=>{const _e=oe.target.value;wt(_e||void 0)},children:[t.jsx("option",{value:"",children:"Execution Node: Project default / local"}),Mt.map(oe=>t.jsx("option",{value:oe.id,children:`${oe.name} (${ku(oe.status)})`},oe.id))]}),(()=>{const oe=Mt.find(_e=>_e.id===dt);return oe?t.jsxs("span",{className:`quick-entry-node-status ${vN(oe.status)}`,children:[t.jsx("span",{className:"quick-entry-node-status__dot","aria-hidden":"true"}),ku(oe.status)]}):null})()]}),t.jsx("div",{className:"agent-trigger-wrap",ref:Ge,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{w?(q(!1),Z(null)):xt()},"data-testid":"quick-entry-agent-button",children:[t.jsx(gn,{size:12,style:{verticalAlign:"middle"}}),ns?` ${ns}`:" Agent"]})}),w&&je&&ye&&Xa.createPortal(t.jsxs("div",{ref:se,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:oe=>oe.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 agent"}),G&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!G&&Q.filter(oe=>oe.state!=="terminated").map(oe=>t.jsxs("div",{className:`dep-dropdown-item${O===oe.id?" selected":""}`,onMouseDown:_e=>_e.preventDefault(),onClick:()=>{J(oe.id===O?null:oe.id),q(!1),Z(null)},children:[t.jsx(gn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:oe.role}),t.jsx("span",{className:"dep-dropdown-title",children:oe.name})]},oe.id)),!G&&Q.filter(oe=>oe.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),O&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:oe=>oe.preventDefault(),onClick:()=>{J(null),q(!1),Z(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),je),t.jsx("button",{type:"button",className:`btn btn-sm ${vt?"btn-primary":""}`,onClick:()=>gt(oe=>!oe),onMouseDown:oe=>oe.preventDefault(),"aria-pressed":vt,"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:jt,onMouseDown:oe=>oe.preventDefault(),disabled:!g.trim()||f,"data-testid":"quick-entry-save",title:"Create task",children:[t.jsx(Kh,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),C.length>0&&t.jsx("div",{className:"inline-create-previews",children:C.map((oe,_e)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:oe.previewUrl,alt:oe.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>mn(_e),disabled:f,title:"Remove image","data-testid":`quick-entry-preview-remove-${_e}`,children:"×"})]},oe.previewUrl))}),ce&&je&&Te&&Xa.createPortal(t.jsx("div",{ref:Ie,className:"model-nested-menu model-nested-menu--portal",onMouseDown:oe=>oe.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${Te.top}px`,left:`${Te.left}px`,width:`${Te.width}px`,maxHeight:Te.maxHeight?`${Te.maxHeight}px`:void 0,overflowY:Te.maxHeight?"auto":void 0},children:pe===null?t.jsxs("div",{className:"model-menu-items",children:[t.jsxs("button",{type:"button",className:`model-menu-item ${j?"model-menu-item--active":""}`,onClick:()=>U("plan"),"data-testid":"model-menu-plan",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Ys,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),t.jsx("span",{className:"model-menu-item-value",children:j?nt(Ke,Xe):"Using default"}),t.jsx(hn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${ge?"model-menu-item--active":""}`,onClick:()=>U("executor"),"data-testid":"model-menu-executor",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(qn,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),t.jsx("span",{className:"model-menu-item-value",children:ge?nt(Ne,xe):"Using default"}),t.jsx(hn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${te?"model-menu-item--active":""}`,onClick:()=>U("validator"),"data-testid":"model-menu-validator",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(co,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Reviewer"]}),t.jsx("span",{className:"model-menu-item-value",children:te?nt(ve,Ee):"Using default"}),t.jsx(hn,{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:()=>U(null),"data-testid":"model-submenu-back",children:[t.jsx(qt,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),t.jsxs("div",{className:"model-submenu-header",children:[pe==="plan"&&"Plan Model",pe==="executor"&&"Executor Model",pe==="validator"&&"Reviewer Model"]}),t.jsx($n,{models:Je,value:pe==="plan"?B:pe==="executor"?Kt:$t,onChange:pe==="plan"?Rn:pe==="executor"?vn:Y,placeholder:"Using default",disabled:ie,id:`model-${pe}-select`,label:`${pe} model`,favoriteProviders:Ct,onToggleFavorite:Oe,favoriteModels:At,onToggleModelFavorite:Ye}),he&&t.jsxs("div",{className:"model-submenu-error",children:[t.jsx("span",{children:he}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:en,children:"Retry"})]})]})}),je)]}),t.jsx("input",{ref:R,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:oe=>{Rt(oe.target.files),oe.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),t.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function yN(e){const n=e.replace(/\/+$/,"").split("/");return n[n.length-1]||e}function kN(e){const n=new Map(e.map(l=>[l.id,l])),s=[],i=new Set,r=new Set;function o(l){if(i.has(l)||r.has(l))return;r.add(l);const c=n.get(l);if(c)for(const u of c.dependencies||[])n.has(u)&&o(u);r.delete(l),i.add(l),s.push(l)}for(const l of e)o(l.id);return s}function jN(e,n,s){const i=e.filter(f=>f.worktree),r=e.filter(f=>!f.worktree),o=new Map;for(const f of i){const x=f.worktree,v=o.get(x)||[];v.push(f),o.set(x,v)}const l=new Map(n.map(f=>[f.id,f])),u=n.filter(f=>f.column==="todo").filter(f=>!f.paused&&(f.dependencies||[]).every(x=>{const v=l.get(x);return v&&(v.column==="done"||v.column==="in-review"||v.column==="archived")})),m=kN(u).map(f=>l.get(f)).filter(f=>f!==void 0&&u.includes(f)),h=[],g=Array.from(o.keys());for(const f of g)h.push({label:yN(f),activeTasks:o.get(f),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 ju=100,xl=50,wu=25;function wN({column:e,tasks:n,projectId:s,maxConcurrent:i,onMoveTask:r,onPauseTask:o,onOpenDetail:l,addToast:c,onQuickCreate:u,onNewTask:d,autoMerge:m,onToggleAutoMerge:h,globalPaused:g,onUpdateTask:p,onRetryTask:f,onArchiveTask:x,onUnarchiveTask:v,onDeleteTask:b,onArchiveAllDone:y,collapsed:S,onToggleCollapse:k,allTasks:R,availableModels:N,onPlanningMode:M,onSubtaskBreakdown:C,onOpenDetailWithTab:z,favoriteProviders:A,favoriteModels:P,onToggleFavorite:F,onToggleModelFavorite:W,isSearchActive:$,taskStuckTimeoutMs:_,onOpenMission:I,lastFetchTimeMs:O,workflowStepNameLookup:J}){const[Q,E]=a.useState(!1),[D,T]=a.useState(xl),[w,q]=a.useState(!1),[G,me]=a.useState(!1),[ce,ae]=a.useState(!1),[pe,U]=a.useState(!1),Ne=a.useRef(null),ne=hw(n.length),{confirm:xe}=Ds();a.useEffect(()=>{if(!w)return;function Me(lt){Ne.current?.contains(lt.target)||q(!1)}function Be(lt){lt.key==="Escape"&&q(!1)}return document.addEventListener("mousedown",Me),document.addEventListener("keydown",Be),()=>{document.removeEventListener("mousedown",Me),document.removeEventListener("keydown",Be)}},[w]);const le=e==="archived",ve=le&&S,ee=!le&&!$&&e!=="in-progress"&&n.length>ju;a.useEffect(()=>{T(Me=>e==="in-progress"||le||n.length<=ju?xl:Math.min(Math.max(Me,xl),n.length))},[e,le,n.length]);const Ee=a.useCallback(Me=>{le||(Me.preventDefault(),Me.dataTransfer.dropEffect="move",E(!0))},[le]),Fe=a.useCallback(Me=>{Me.currentTarget.contains(Me.relatedTarget)||E(!1)},[]),Ke=a.useCallback(async Me=>{Me.preventDefault(),E(!1);const Be=Me.dataTransfer.getData("text/plain");if(!Be)return;const lt=n.find(je=>je.id===Be);if(!(lt&<.column===e))try{await r(Be,e)}catch(je){c(ke(je),"error")}},[e,r,c,n]),Ze=a.useMemo(()=>e!=="in-progress"?[]:jN(n,n,i),[e,n,i]),Xe=a.useMemo(()=>ee?n.slice(0,D):n,[ee,n,D]),Qe=Math.max(0,n.length-Xe.length),it=a.useCallback(()=>{T(Me=>Math.min(Me+wu,n.length))},[n.length]),Ie=a.useCallback(async()=>{if(q(!1),!(n.length===0||!await xe({title:"Replan All Tasks",message:`Move all ${n.length} todo task${n.length===1?"":"s"} back to planning to be replanned?`}))){me(!0);try{const Be=await Promise.allSettled(n.map(ie=>r(ie.id,"triage"))),lt=Be.filter(ie=>ie.status==="rejected").length,je=Be.length-lt;lt===0?c(`Moved ${je} task${je===1?"":"s"} to planning for replanning`,"success"):c(`Moved ${je} of ${Be.length} tasks; ${lt} failed`,"error")}finally{me(!1)}}},[n,r,c,xe]),Ge=a.useMemo(()=>n.filter(Me=>!Me.paused),[n]),se=Ge.length,ye=e==="todo"||e==="in-progress"||e==="in-review",Z=G||ce||pe,Te=a.useCallback(async()=>{if(!(!o||(q(!1),se===0)||!await xe({title:"Stop All Tasks",message:`Stop all ${se} ${_n[e].toLowerCase()} task${se===1?"":"s"}?`,danger:!0}))){ae(!0);try{const Be=await Promise.allSettled(Ge.map(ie=>o(ie.id))),lt=Be.filter(ie=>ie.status==="rejected").length,je=Be.length-lt;lt===0?c(`Stopped ${je} task${je===1?"":"s"}`,"success"):c(`Stopped ${je} of ${Be.length} tasks; ${lt} failed`,"error")}finally{ae(!1)}}},[o,se,e,Ge,c,xe]),ze=a.useCallback(async()=>{if(q(!1),!(n.length===0||!await xe({title:"Move All to Todo",message:`Move all ${n.length} ${_n[e].toLowerCase()} task${n.length===1?"":"s"} to Todo?`}))){U(!0);try{const Be=await Promise.allSettled(n.map(ie=>r(ie.id,"todo"))),lt=Be.filter(ie=>ie.status==="rejected").length,je=Be.length-lt;lt===0?c(`Moved ${je} task${je===1?"":"s"} to Todo`,"success"):c(`Moved ${je} of ${Be.length} tasks to Todo; ${lt} failed`,"error")}finally{U(!1)}}},[n,e,r,c,xe]),be=a.useCallback(async()=>{if(!(!y||n.length===0||!await xe({title:"Archive All Done",message:`Archive all ${n.length} done tasks?`,danger:!0})))try{const Be=await y();c(`Archived ${Be.length} tasks`,"success")}catch(Be){c(ke(Be)||"Failed to archive tasks","error")}},[y,n.length,c,xe]);return t.jsxs("div",{className:`column${Q?" drag-over":""}${le?" column-archived":""}${ve?" column-collapsed":""}`,"data-column":e,onDragOver:Ee,onDragLeave:Fe,onDrop:Ke,children:[t.jsxs("div",{className:"column-header",children:[t.jsx("div",{className:`column-dot dot-${e}`}),t.jsx("h2",{children:_n[e]}),t.jsx("span",{className:`column-count${ne?" 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"})]}),d&&t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:d,children:"+ New Task"}),e==="done"&&y&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:be,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:t.jsx(Mo,{size:16})}),le&&k&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:k,title:S?"Expand archived tasks":"Collapse archived tasks","aria-label":S?"Expand archived tasks":"Collapse archived tasks",children:S?t.jsx(qt,{size:16}):t.jsx(li,{size:16})}),ye&&t.jsxs("div",{className:"column-menu",ref:Ne,children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>q(Me=>!Me),"aria-haspopup":"menu","aria-expanded":w,"aria-label":`${_n[e]} column actions`,title:"Column actions",disabled:Z,children:t.jsx(ax,{size:16})}),w&&t.jsxs("div",{className:"column-menu-popover",role:"menu",children:[e==="todo"&&t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Ie(),disabled:n.length===0||G,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 Te(),disabled:se===0||ce||!o,children:["Stop All",t.jsx("span",{className:"column-menu-item-hint",children:n.length===0?"No tasks in this column":se===0?"All tasks are already paused":`Pause ${se} active task${se===1?"":"s"}`})]}),t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void ze(),disabled:n.length===0||pe,children:["Move All to Todo",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Todo"]})]})]})]})]})]}),!ve&&t.jsx("p",{className:"column-desc",children:uw[e]}),!ve&&t.jsxs("div",{className:"column-body",children:[e==="triage"&&u&&t.jsx(Sp,{onCreate:u,addToast:c,tasks:R??[],availableModels:N,onPlanningMode:M,onSubtaskBreakdown:C,projectId:s,autoExpand:!1,favoriteProviders:A,favoriteModels:P,onToggleFavorite:F,onToggleModelFavorite:W}),e==="in-progress"?Ze.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):Ze.map(Me=>t.jsx(Np,{label:Me.label,activeTasks:Me.activeTasks,queuedTasks:Me.queuedTasks,projectId:s,onOpenDetail:l,addToast:c,globalPaused:g,onUpdateTask:p,onRetryTask:f,onOpenDetailWithTab:z,taskStuckTimeoutMs:_,onOpenMission:I,lastFetchTimeMs:O,workflowStepNameLookup:J},Me.label)):n.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):t.jsxs(t.Fragment,{children:[Xe.map(Me=>t.jsx(yo,{task:Me,projectId:s,onOpenDetail:l,addToast:c,globalPaused:g,onUpdateTask:p,onRetryTask:f,onArchiveTask:x,onUnarchiveTask:v,onDeleteTask:b,onOpenDetailWithTab:z,taskStuckTimeoutMs:_,onOpenMission:I,onMoveTask:r,lastFetchTimeMs:O,workflowStepNameLookup:J},Me.id)),ee&&Qe>0&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:it,children:["Load ",Math.min(wu,Qe)," more (",Qe," remaining)"]})]}),t.jsx(Oo,{slotId:"board-column-footer",projectId:s})]})]})}const Cp=a.memo(wN);Cp.displayName="Column";function NN(e){return[...e].sort((n,s)=>n.columnMovedAt&&s.columnMovedAt?s.columnMovedAt.localeCompare(n.columnMovedAt):n.columnMovedAt&&!s.columnMovedAt?-1:!n.columnMovedAt&&s.columnMovedAt?1:n.createdAt.localeCompare(s.createdAt))}function SN(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}const Nu=new Map;function CN(e,n){if(e.size!==n.size)return!1;for(const[s,i]of e)if(n.get(s)!==i)return!1;return!0}function EN({tasks:e,projectId:n,maxConcurrent:s,onMoveTask:i,onPauseTask:r,onOpenDetail:o,addToast:l,onQuickCreate:c,onNewTask:u,autoMerge:d,onToggleAutoMerge:m,globalPaused:h,onUpdateTask:g,onRetryTask:p,onArchiveTask:f,onUnarchiveTask:x,onDeleteTask:v,onArchiveAllDone:b,onLoadArchivedTasks:y,searchQuery:S="",availableModels:k,onPlanningMode:R,onSubtaskBreakdown:N,onOpenDetailWithTab:M,favoriteProviders:C,favoriteModels:z,onToggleFavorite:A,onToggleModelFavorite:P,taskStuckTimeoutMs:F,onOpenMission:W,lastFetchTimeMs:$}){const[_,I]=a.useState(!0),O=a.useRef(!1),{fetchBatch:J}=Rw(n),Q=a.useRef(null),[E,D]=a.useState(Nu),T=S.trim()!=="",w=a.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),q=a.useCallback(()=>{I(ce=>{const ae=!ce;return!ae&&!O.current&&y&&(O.current=!0,y()),ae})},[y]),G=a.useMemo(()=>{const ce=Object.fromEntries(zi.map(U=>[U,[]]));for(const U of e)ce[U.column].push(U);const ae=w.current,pe={};for(const U of zi){const Ne=NN(ce[U]);pe[U]=SN(ae[U],Ne)?ae[U]:Ne}return w.current=pe,pe},[e]);a.useEffect(()=>{let ce=!1;return zo(n).then(ae=>{if(ce)return;const pe=new Map(ae.map(U=>[U.id,U.name]));D(U=>CN(U,pe)?U:pe)}).catch(()=>{ce||D(ae=>ae.size===0?ae:Nu)}),()=>{ce=!0}},[n]);const me=a.useMemo(()=>e.filter(ce=>ce.prInfo||ce.issueInfo).map(ce=>ce.id),[e]);return a.useEffect(()=>{if(me.length!==0)return Q.current&&clearTimeout(Q.current),Q.current=setTimeout(()=>{const ce=[];for(let ae=0;ae<me.length;ae+=50)ce.push(me.slice(ae,ae+50));ce.forEach(ae=>{J(ae)})},500),()=>{Q.current&&clearTimeout(Q.current)}},[me,J]),t.jsx(t.Fragment,{children:t.jsx("main",{className:"board",id:"board",children:zi.map(ce=>t.jsx(Cp,{column:ce,tasks:G[ce],projectId:n,maxConcurrent:s,onMoveTask:i,onPauseTask:r,onOpenDetail:o,addToast:l,globalPaused:h,onUpdateTask:g,onRetryTask:p,onArchiveTask:f,onUnarchiveTask:x,onDeleteTask:v,allTasks:e,availableModels:k,onOpenDetailWithTab:M,favoriteProviders:C,favoriteModels:z,onToggleFavorite:A,onToggleModelFavorite:P,isSearchActive:T,taskStuckTimeoutMs:F,onOpenMission:W,lastFetchTimeMs:$,workflowStepNameLookup:E,...ce==="triage"?{onQuickCreate:c,onNewTask:u,onPlanningMode:R,onSubtaskBreakdown:N}:{},...ce==="in-review"?{autoMerge:d,onToggleAutoMerge:m}:{},...ce==="done"?{onArchiveAllDone:b}:{},...ce==="archived"?{collapsed:_,onToggleCollapse:q}:{}},ce))})})}const Da={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},Su=new Set(["planning","researching","executing","finalizing","merging"]),Mc=["id","title","status","column","dependencies","progress"];function _N(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function Cu(e){try{const n=Dn("kb-dashboard-list-columns",e);if(n){const i=JSON.parse(n).filter(r=>Mc.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set(Mc)}function Eu(e){try{const n=Dn("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function _u(e){try{const n=Dn("kb-dashboard-list-collapsed",e);if(n){const i=JSON.parse(n).filter(r=>zi.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set}function Mu(e){try{const n=Dn("kb-dashboard-selected-tasks",e);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function MN(e){return e.status==="executing"||e.column==="in-progress"}function Au(e){const n=jp(e);return n.total===0||!MN(e)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function AN({tasks:e,onMoveTask:n,onOpenDetail:s,addToast:i,globalPaused:r,onNewTask:o,onQuickCreate:l,availableModels:c,favoriteProviders:u=[],favoriteModels:d=[],onToggleFavorite:m,onToggleModelFavorite:h,onPlanningMode:g,onSubtaskBreakdown:p,onTasksUpdated:f,projectId:x,projectName:v,taskStuckTimeoutMs:b,searchQuery:y="",lastFetchTimeMs:S}){const[k,R]=a.useState("id"),[N,M]=a.useState("desc"),[C,z]=a.useState(null),[A,P]=a.useState(null),[F,W]=a.useState(null),_=Cr()==="mobile",[I,O]=a.useState(()=>Cu(x)),[J,Q]=a.useState(()=>Eu(x)),[E,D]=a.useState(()=>_u(x));a.useEffect(()=>{typeof window<"u"&&os("kb-dashboard-list-columns",JSON.stringify([...I]),x)},[x,I]),a.useEffect(()=>{typeof window<"u"&&os("kb-dashboard-hide-done",J.toString(),x)},[J,x]),a.useEffect(()=>{typeof window<"u"&&os("kb-dashboard-list-collapsed",JSON.stringify([...E]),x)},[E,x]);const[T,w]=a.useState(!1),q=a.useRef(null),[G,me]=a.useState(()=>Mu(x));a.useEffect(()=>{O(Cu(x)),Q(Eu(x)),D(_u(x)),me(Mu(x))},[x]),a.useEffect(()=>{typeof window<"u"&&os("kb-dashboard-selected-tasks",JSON.stringify([...G]),x)},[x,G]);const ce=a.useCallback(de=>{me(re=>{const ue=new Set(re);return ue.has(de)?ue.delete(de):ue.add(de),ue})},[]),ae=a.useCallback(()=>{me(new Set)},[]),pe=a.useCallback(de=>{O(re=>{const ue=new Set(re);return ue.has(de)?ue.size>1&&ue.delete(de):ue.add(de),ue})},[]);a.useEffect(()=>{if(!T)return;const de=ue=>{q.current&&!q.current.contains(ue.target)&&w(!1)},re=ue=>{ue.key==="Escape"&&w(!1)};return document.addEventListener("mousedown",de),document.addEventListener("keydown",re),()=>{document.removeEventListener("mousedown",de),document.removeEventListener("keydown",re)}},[T]);const U={id:"ID",title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},Ne=a.useCallback(de=>{k===de?M(re=>re==="asc"?"desc":"asc"):(R(de),M("asc"))},[k]),ne=a.useCallback(de=>{W(re=>re===de?null:de)},[]),xe=a.useCallback(de=>{D(re=>{const ue=new Set(re);return ue.has(de)?ue.delete(de):ue.add(de),ue})},[]),le=a.useCallback(()=>{W(null)},[]),ve=a.useMemo(()=>{let de=y?e.filter(Se=>Se.id.toLowerCase().includes(y.toLowerCase())||Se.title&&Se.title.toLowerCase().includes(y.toLowerCase())||Se.description.toLowerCase().includes(y.toLowerCase())):[...e];J&&!F&&(de=de.filter(Se=>Se.column!=="done"&&Se.column!=="archived"));const ue=[...F?de.filter(Se=>Se.column===F):de].sort((Se,fe)=>{let tt=0;switch(k){case"id":tt=Se.id.localeCompare(fe.id);break;case"title":tt=(Se.title||Se.description).localeCompare(fe.title||fe.description);break;case"status":tt=(Se.status||"").localeCompare(fe.status||"");break;case"column":tt=Se.column.localeCompare(fe.column);break}return N==="asc"?tt:-tt}),Pe={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};return ue.forEach(Se=>Pe[Se.column].push(Se)),Pe},[e,y,k,N,J,F]),ee=a.useMemo(()=>Object.values(ve).reduce((de,re)=>de+re.length,0),[ve]),Ee=a.useMemo(()=>e.filter(de=>de.column==="done"||de.column==="archived").length,[e]),Fe=a.useMemo(()=>J?Ee:0,[J,Ee]),Ke=a.useCallback(()=>{const de=Object.values(ve).flat().filter(re=>re.column!=="archived").map(re=>re.id);me(re=>{if(de.every(Pe=>re.has(Pe))){const Pe=new Set(re);return de.forEach(Se=>Pe.delete(Se)),Pe}else return new Set([...re,...de])})},[ve]),Ze=a.useMemo(()=>{const de=Object.values(ve).flat().filter(re=>re.column!=="archived");return de.length===0?!1:de.every(re=>G.has(re.id))},[ve,G]),Xe=a.useMemo(()=>{const de=Object.values(ve).flat().filter(ue=>ue.column!=="archived");if(de.length===0)return!1;const re=de.filter(ue=>G.has(ue.id)).length;return re>0&&re<de.length},[ve,G]),[Qe,it]=a.useState("__no_change__"),[Ie,Ge]=a.useState("__no_change__"),[se,ye]=a.useState("__no_change__"),[Z,Te]=a.useState([]),[ze,be]=a.useState(!1),[Me,Be]=a.useState(!1);a.useEffect(()=>{if(G.size===0)return;let de=!1;return(async()=>{be(!0);try{const ue=await xo();de||Te(ue)}catch(ue){console.error("Failed to fetch nodes for bulk edit",ue),de||Te([])}finally{de||be(!1)}})(),()=>{de=!0}},[G.size]);const lt=a.useCallback(async()=>{if(G.size===0)return;const de=Array.from(G).filter(ue=>{const Pe=e.find(Se=>Se.id===ue);return Pe&&Pe.column!=="archived"});if(de.length===0){i("No valid tasks to update (archived tasks cannot be modified)","error");return}const re={taskIds:de};if(Qe!=="__no_change__")if(Qe==="")re.modelProvider=null,re.modelId=null;else{const ue=Qe.indexOf("/");ue!==-1&&(re.modelProvider=Qe.slice(0,ue),re.modelId=Qe.slice(ue+1))}if(Ie!=="__no_change__")if(Ie==="")re.validatorModelProvider=null,re.validatorModelId=null;else{const ue=Ie.indexOf("/");ue!==-1&&(re.validatorModelProvider=Ie.slice(0,ue),re.validatorModelId=Ie.slice(ue+1))}if(se!=="__no_change__"&&(se===""?re.nodeId=null:re.nodeId=se),Object.keys(re).length===1){i("No changes to apply","info");return}Be(!0);try{const ue=await Nv(re.taskIds,re.modelProvider,re.modelId,re.validatorModelProvider,re.validatorModelId,void 0,void 0,re.nodeId,x);f&&f(ue.updated),i(`Updated ${de.length} task${de.length===1?"":"s"}`,"success"),ae(),it("__no_change__"),Ge("__no_change__"),ye("__no_change__")}catch(ue){i(ke(ue)||"Failed to update models","error")}finally{Be(!1)}},[G,e,Qe,Ie,se,x,i,ae,f]),je=a.useCallback(de=>{s(de)},[s]),ie=a.useCallback((de,re)=>{if(re.paused){de.preventDefault();return}de.dataTransfer.setData("text/plain",re.id),de.dataTransfer.effectAllowed="move",z(re.id)},[]),Ae=a.useCallback(()=>{z(null),P(null)},[]),he=a.useCallback((de,re)=>{de.preventDefault(),de.dataTransfer.dropEffect="move",P(re)},[]),Re=a.useCallback(()=>{P(null)},[]),Je=a.useCallback(async(de,re)=>{de.preventDefault(),P(null);const ue=de.dataTransfer.getData("text/plain");if(ue){if(re==="archived"){i("Tasks can only be archived via the archive button","error");return}try{await n(ue,re)}catch(Pe){i(ke(Pe),"error")}}},[n,i]),$e=de=>k!==de?t.jsx(Lh,{size:14,className:"sort-icon"}):N==="asc"?t.jsx(Li,{size:14,className:"sort-icon active"}):t.jsx(xr,{size:14,className:"sort-icon active"});return t.jsxs("div",{className:"list-view",children:[t.jsxs("div",{className:"list-toolbar",children:[t.jsxs("div",{className:"list-column-toggle",ref:q,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>w(de=>!de),"aria-expanded":T,"aria-haspopup":"menu",children:[t.jsx(Xg,{size:14}),"Columns"]}),T&&t.jsx("div",{className:"list-column-dropdown",role:"menu",children:Mc.map(de=>{const re=I.has(de),ue=re&&I.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${ue?" disabled":""}`,role:"menuitem",title:ue?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:re,onChange:()=>pe(de),disabled:ue}),t.jsx("span",{children:U[de]})]},de)})})]}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>Q(de=>!de),"aria-pressed":J,title:J?"Show done tasks":"Hide done tasks",children:[J?t.jsx(da,{size:14}):t.jsx(pc,{size:14}),J?"Show Done":"Hide Done"]}),t.jsxs("div",{className:"list-stats",children:[F?`${ee} of ${e.length} tasks in ${_n[F]}`:`${ee} of ${e.length} tasks`,Fe>0&&!F&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",Fe," hidden)"]}),F&&t.jsx("button",{className:"btn btn-sm",onClick:le,"aria-label":"Clear column filter",style:{marginLeft:"8px"},children:"Clear"})]}),G.size>0&&t.jsxs("div",{className:"list-selection-stats",children:[t.jsxs("span",{className:"selection-count",children:[G.size," selected"]}),t.jsx("button",{className:"btn btn-sm btn-link",onClick:ae,children:"Clear"})]}),G.size>0&&c&&c.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($n,{models:c,value:Qe,onChange:it,label:"Executor Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:u,onToggleFavorite:m,favoriteModels:d,onToggleModelFavorite:h})}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx($n,{models:c,value:Ie,onChange:Ge,label:"Reviewer Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:u,onToggleFavorite:m,favoriteModels:d,onToggleModelFavorite:h})}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsxs("select",{className:"select bulk-node-select",value:se,onChange:de=>ye(de.target.value),"aria-label":"Node Override",disabled:ze,children:[t.jsx("option",{value:"__no_change__",children:"No change"}),t.jsx("option",{value:"",children:"Use project default"}),Z.map(de=>t.jsx("option",{value:de.id,children:`${de.name||de.id} (${_N(de.status)})`},de.id))]})}),t.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:lt,disabled:Me||Qe==="__no_change__"&&Ie==="__no_change__"&&se==="__no_change__",children:Me?"Applying...":"Apply"})]}),o?t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:o,children:"+ New Task"}):null]}),t.jsx("div",{className:"list-drop-zones",children:zi.map(de=>{const re=e.filter(fe=>fe.column===de).length,ue=de==="done"||de==="archived",Pe=J&&ue?0:re,Se=J&&ue&&re>0;return t.jsxs("div",{className:`list-drop-zone${A===de?" drag-over":""}${F===de?" active":""}`,onClick:()=>ne(de),onDragOver:fe=>he(fe,de),onDragLeave:Re,onDrop:fe=>Je(fe,de),"data-column":de,children:[t.jsx("span",{className:"drop-zone-dot",style:{background:Da[de]}}),t.jsx("span",{className:"drop-zone-label",children:_n[de]}),t.jsx("span",{className:"drop-zone-count",children:Se?`${Pe} of ${re}`:re})]},de)})}),t.jsxs("div",{className:"list-table-container",children:[t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx(Sp,{onCreate:l??(async()=>i("Task creation not available","error")),addToast:i,tasks:e,availableModels:c,onPlanningMode:g,onSubtaskBreakdown:p,projectId:x,autoExpand:!1,favoriteProviders:u,favoriteModels:d,onToggleFavorite:m,onToggleModelFavorite:h})}),ee===0?t.jsx("div",{className:"list-empty",children:y?"No tasks match your filter":"No tasks yet"}):_?t.jsx("div",{className:"list-cards",children:zi.map(de=>{if(F&&de!==F||J&&(de==="done"||de==="archived")&&!F)return null;const re=ve[de],ue=re.length===0;if(y&&ue)return null;const Pe=E.has(de);return t.jsxs(a.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${Pe?" list-section-header--collapsed":""}`,onClick:()=>xe(de),"aria-expanded":!Pe,role:"button",tabIndex:0,onKeyDown:Se=>{(Se.key==="Enter"||Se.key===" ")&&(Se.preventDefault(),xe(de))},children:[t.jsx(hn,{size:14,className:`list-section-chevron${Pe?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${de}`}),t.jsx("span",{className:"list-section-title",children:_n[de]}),t.jsx("span",{className:"list-section-count",children:re.length})]}),!Pe&&t.jsx(t.Fragment,{children:ue?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):re.map(Se=>{const fe=Se.status==="failed",tt=Se.paused===!0,ut=vo(Se,b,S),vt=!r&&!fe&&!tt&&!ut&&(Se.column==="in-progress"||Su.has(Se.status)),gt=typeof Se.status=="string"&&Se.status.trim().length>0,dt=!!(Se.dependencies&&Se.dependencies.length>0),wt=Au(Se),Mt=wt.hasProgress,yt=G.size>0;return t.jsxs("div",{className:`list-card${vt?" agent-active":""}${yt?" list-card--selectable":""}`,onClick:()=>je(Se),"data-id":Se.id,children:[yt&&t.jsx("label",{className:"list-card-checkbox",onClick:Et=>Et.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:G.has(Se.id),onChange:Et=>{Et.stopPropagation(),ce(Se.id)},onClick:Et=>Et.stopPropagation(),disabled:Se.column==="archived","aria-label":`Select ${Se.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:Se.id}),Se.executionMode==="fast"&&t.jsx("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",children:"Fast"}),t.jsx("span",{className:"list-card-spacer"}),ut?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):gt?t.jsx("span",{className:`list-status-badge list-status-badge--${Se.column}${fe?" failed":""}${vt?" pulsing":""}`,children:Se.status}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:Se.title||Se.description})}),(dt||Mt)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[dt&&t.jsxs("span",{className:"list-dep-badge",title:Se.dependencies.join(", "),children:[t.jsx(ua,{size:12})," ",Se.dependencies.length]}),Mt&&t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${wt.percent}%`,backgroundColor:Da[Se.column]}})}),t.jsx("span",{className:"list-progress-label",children:wt.label})]})]})]},Se.id)})})]},de)})}):t.jsxs("table",{className:"list-table",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{className:"list-header-cell list-header-checkbox",children:t.jsx("input",{type:"checkbox",checked:Ze,ref:de=>{de&&(de.indeterminate=Xe)},onChange:Ke,"aria-label":"Select all visible tasks"})}),I.has("id")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Ne("id"),children:["ID ",$e("id")]}),I.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Ne("title"),children:["Title ",$e("title")]}),I.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Ne("status"),children:["Status ",$e("status")]}),I.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Ne("column"),children:["Column ",$e("column")]}),I.has("dependencies")&&t.jsx("th",{className:"list-header-cell",children:"Dependencies"}),I.has("progress")&&t.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),t.jsx("tbody",{children:zi.map(de=>{if(F&&de!==F||J&&(de==="done"||de==="archived")&&!F)return null;const re=ve[de],ue=re.length===0;if(y&&ue)return null;const Pe=E.has(de);return t.jsxs(a.Fragment,{children:[t.jsx("tr",{className:`list-section-header${Pe?" list-section-header--collapsed":""}`,onClick:()=>xe(de),"aria-expanded":!Pe,children:t.jsxs("th",{colSpan:I.size+1,className:"list-section-cell",children:[t.jsx(hn,{size:14,className:`list-section-chevron${Pe?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${de}`}),t.jsx("span",{className:"list-section-title",children:_n[de]}),t.jsx("span",{className:"list-section-count",children:re.length})]})}),!Pe&&t.jsx(t.Fragment,{children:ue?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:I.size+1,className:"list-empty-cell",children:"No tasks"})}):re.map(Se=>{const fe=Se.status==="failed",tt=Se.paused===!0,ut=vo(Se,b,S),vt=!r&&!fe&&!tt&&!ut&&(Se.column==="in-progress"||Su.has(Se.status)),gt=C===Se.id;return t.jsxs("tr",{className:`list-row${fe?" failed":""}${tt?" paused":""}${ut?" stuck":""}${vt?" agent-active":""}${gt?" dragging":""}`,onClick:()=>je(Se),draggable:!tt,onDragStart:dt=>ie(dt,Se),onDragEnd:Ae,"data-id":Se.id,children:[t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:G.has(Se.id),onChange:dt=>{dt.stopPropagation(),ce(Se.id)},onClick:dt=>dt.stopPropagation(),disabled:Se.column==="archived","aria-label":`Select ${Se.id}`})}),I.has("id")&&t.jsx("td",{className:"list-cell list-cell-id",children:Se.id}),I.has("title")&&t.jsx("td",{className:"list-cell list-cell-title",children:t.jsxs("div",{className:"list-title-content",children:[Se.executionMode==="fast"&&t.jsx("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",children:"Fast"}),t.jsx("span",{className:"list-title-text",children:Se.title||Se.description})]})}),I.has("status")&&t.jsx("td",{className:"list-cell",children:ut?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):Se.status?t.jsx("span",{className:`list-status-badge list-status-badge--${Se.column}${fe?" failed":""}${vt?" pulsing":""}`,children:Se.status}):t.jsx("span",{className:"list-status-badge",children:"-"})}),I.has("column")&&t.jsx("td",{className:"list-cell",children:t.jsx("span",{className:"list-column-badge",style:{background:`${Da[Se.column]}20`,color:Da[Se.column]},children:_n[Se.column]})}),I.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:Se.dependencies&&Se.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:Se.dependencies.join(", "),children:[t.jsx(ua,{size:12})," ",Se.dependencies.length]}):"-"}),I.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const dt=Au(Se);return dt.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:`${dt.percent}%`,backgroundColor:Da[Se.column]}})}),t.jsx("span",{className:"list-progress-label",children:dt.label})]}):"-"})()})]},Se.id)})})]},de)})})]})]})]})}const RN={active:{label:"Active",color:"var(--success)",icon:xn},paused:{label:"Paused",color:"var(--warning)",icon:Gs},errored:{label:"Error",color:"var(--color-error)",icon:Xn},initializing:{label:"Initializing",color:"var(--info)",icon:ot}};function TN(e){if(!e)return"Never";const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),o=Math.floor(i/36e5),l=Math.floor(i/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString()}function PN(e,n=40){if(e.length<=n)return e;const s=e.slice(0,Math.floor(n/2)-2),i=e.slice(-Math.floor(n/2)+2);return`${s}...${i}`}function IN(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,i=n.health;if(!s&&!i)return!0;if(!s||!i||s.activeTaskCount!==i.activeTaskCount||s.inFlightAgentCount!==i.inFlightAgentCount||s.totalTasksCompleted!==i.totalTasksCompleted||s.totalTasksFailed!==i.totalTasksFailed||s.status!==i.status)return!1;const r=e.node,o=n.node;return!r&&!o?e.nodeNameFallback===n.nodeNameFallback:!r||!o?!1:r.id===o.id&&r.name===o.name&&r.status===o.status&&r.type===o.type}function $N({project:e,health:n,onSelect:s,onPause:i,onResume:r,onRemove:o,node:l,nodeNameFallback:c,isLoading:u=!1}){const[d,m]=a.useState(!1),h=RN[e.status],g=h.icon,p=a.useCallback(()=>{s(e)},[s,e]),f=a.useCallback(k=>{k.stopPropagation(),i(e)},[i,e]),x=a.useCallback(k=>{k.stopPropagation(),r(e)},[r,e]),v=a.useCallback(k=>{if(k.stopPropagation(),!d){m(!0);return}o(e),m(!1)},[d,o,e]),b=e.status==="paused",y=e.status==="errored",S=e.status==="initializing";return t.jsxs("div",{className:`project-card ${u?"project-card-loading":""} ${y?"project-card-errored":""}`,onClick:p,"data-project-id":e.id,role:"button",tabIndex:0,onKeyDown:k=>{(k.key==="Enter"||k.key===" ")&&(k.preventDefault(),p())},children:[t.jsxs("div",{className:"project-card-header",children:[t.jsx("div",{className:"project-card-icon",children:t.jsx(In,{size:20})}),t.jsxs("div",{className:"project-card-title-section",children:[t.jsx("h3",{className:"project-card-name",title:e.name,children:e.name}),(l||c)&&t.jsxs("span",{className:"node-badge",title:`Assigned node: ${l?.name??c}`,children:["on: ",l?.name??c]}),t.jsx("span",{className:"project-card-path",title:e.path,children:PN(e.path)})]}),t.jsxs("div",{className:"project-card-status-badge",style:{color:h.color,borderColor:h.color},children:[t.jsx(g,{size:12,className:S?"animate-spin":""}),t.jsx("span",{children:h.label})]})]}),t.jsxs("div",{className:"project-card-health",children:[n&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.activeTaskCount}),t.jsx("span",{className:"project-card-metric-label",children:"Active Tasks"})]}),t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.inFlightAgentCount}),t.jsx("span",{className:"project-card-metric-label",children:"Agents"})]}),t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.totalTasksCompleted}),t.jsx("span",{className:"project-card-metric-label",children:"Completed"})]})]}),!n&&t.jsx("div",{className:"project-card-metric project-card-metric-empty",children:t.jsx("span",{className:"project-card-metric-label",children:"No health data available"})})]}),t.jsxs("div",{className:"project-card-footer",children:[t.jsxs("div",{className:"project-card-activity",children:[t.jsx("span",{className:"project-card-activity-label",children:"Last activity:"}),t.jsx("span",{className:"project-card-activity-time",children:TN(e.lastActivityAt||n?.lastActivityAt)})]}),t.jsxs("div",{className:"project-card-actions",children:[b?t.jsxs("button",{className:"project-card-action project-card-action-resume",onClick:x,disabled:u,title:"Resume project","aria-label":"Resume project",children:[t.jsx(xn,{size:14}),t.jsx("span",{children:"Resume"})]}):t.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:f,disabled:u||S,title:S?"Cannot pause while initializing":"Pause project","aria-label":"Pause project",children:[t.jsx(Gs,{size:14}),t.jsx("span",{children:"Pause"})]}),t.jsxs("button",{className:"project-card-action project-card-action-open",onClick:p,disabled:u,title:"Open project","aria-label":"Open project",children:[t.jsx(br,{size:14}),t.jsx("span",{children:"Open"})]}),t.jsxs("button",{className:`project-card-action project-card-action-remove ${d?"is-armed":""}`,onClick:v,disabled:u,title:d?"Confirm remove":"Remove project","aria-label":d?"Confirm remove project":"Remove project",children:[t.jsx(Xt,{size:14}),t.jsx("span",{children:d?"Confirm":""})]})]})]})]})}const DN=a.memo($N,IN);function LN(){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(In,{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(Cs,{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(dn,{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__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 zN=1e4,Ru=5;function FN(e){const[n,s]=a.useState({}),[i,r]=a.useState(!0),[o,l]=a.useState(null),c=a.useRef(null),u=a.useRef(null),d=a.useRef(!1),m=a.useCallback(async()=>{if(e.length===0){s({}),d.current||(d.current=!0),r(!1);return}u.current&&u.current.abort(),u.current=new AbortController,!d.current&&r(!0),l(null);try{const p={};for(let f=0;f<e.length;f+=Ru){const x=e.slice(f,f+Ru),v=await Promise.allSettled(x.map(async b=>{try{return await Gd(b)}catch{return null}}));if(x.forEach((b,y)=>{const S=v[y];p[b]=S.status==="fulfilled"?S.value:null}),u.current?.signal.aborted)return}s(p),d.current=!0}catch(p){if(p instanceof Error&&p.name==="AbortError")return;l(p instanceof Error?p.message:"Failed to fetch health data"),d.current=!0}finally{r(!1)}},[e]),h=a.useCallback(async g=>{try{const p=await Gd(g);s(f=>({...f,[g]:p}))}catch(p){console.error(`Failed to fetch health for project ${g}:`,p)}},[]);return a.useEffect(()=>(d.current=!1,m(),()=>{u.current&&u.current.abort()}),[m]),a.useEffect(()=>{if(e.length!==0)return c.current&&clearInterval(c.current),c.current=setInterval(()=>{m()},zN),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[m,e.length]),{healthMap:n,loading:i,error:o,refresh:m,refreshProject:h}}function ON({projects:e,loading:n=!1,onSelectProject:s,onAddProject:i,onPauseProject:r,onResumeProject:o,onRemoveProject:l,nodes:c=[]}){const[u,d]=a.useState("all"),[m,h]=a.useState(null),[g,p]=a.useState("activity"),[f,x]=a.useState("desc");a.useEffect(()=>{if(typeof window>"u")return;const W=localStorage.getItem("kb-dashboard-recent-projects");if(W)try{const $=JSON.parse(W);b($)}catch{}},[]);const[v,b]=a.useState([]),y=a.useMemo(()=>e.map(W=>W.id),[e]),{healthMap:S,loading:k}=FN(y),R=a.useMemo(()=>e.map(W=>({project:W,health:S[W.id]||null})),[e,S]),N=a.useMemo(()=>{let W=[...R];return u!=="all"&&(W=W.filter(({project:$})=>$.status===u)),m!==null&&(W=W.filter(({project:$})=>$.nodeId===m)),W},[R,u,m]),M=a.useMemo(()=>{const W=[...N];return W.sort(($,_)=>{let I=0;switch(g){case"name":I=$.project.name.localeCompare(_.project.name);break;case"activity":{const O=$.project.lastActivityAt||$.health?.lastActivityAt||$.project.updatedAt,J=_.project.lastActivityAt||_.health?.lastActivityAt||_.project.updatedAt;I=new Date(J).getTime()-new Date(O).getTime();break}case"status":{const O={errored:0,initializing:1,paused:2,active:3};I=O[$.project.status]-O[_.project.status];break}}return f==="asc"?I:-I}),W},[N,g,f]),C=a.useMemo(()=>{const W=e.length,$=e.filter(D=>D.status==="active").length,_=e.filter(D=>D.status==="errored").length,I=new Set;e.forEach(D=>{D.nodeId&&I.add(D.nodeId)});const O=I.size||(W>0?1:0);let J=0,Q=0,E=0;return Object.values(S).forEach(D=>{D&&(J+=D.activeTaskCount,Q+=D.totalTasksCompleted,E+=D.inFlightAgentCount)}),{totalProjects:W,activeProjects:$,erroredProjects:_,totalNodes:O,totalActiveTasks:J,totalCompletedTasks:Q,totalInFlightAgents:E}},[e,S]),z=a.useMemo(()=>({all:e.length,active:e.filter(W=>W.status==="active").length,paused:e.filter(W=>W.status==="paused").length,errored:e.filter(W=>W.status==="errored").length}),[e]),A=a.useMemo(()=>{const W=new Map;return e.forEach($=>{const _=$.nodeId,I=W.get(_);if(I)I.count++;else{const J=c.find(Q=>Q.id===_)?.name??$._sourceNodeName??"Local";W.set(_,{name:J,count:1})}}),Array.from(W.entries()).map(([$,{name:_,count:I}])=>({nodeId:$??null,name:_,count:I}))},[e,c]),P=a.useCallback(W=>{const $=[W.id,...v.filter(_=>_!==W.id)].slice(0,3);b($),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify($)),s(W)},[s,v]);return n||k&&e.length>0&&Object.keys(S).length===0?t.jsx(LN,{}):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(Za,{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:i,children:[t.jsx(Zt,{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(Bi,{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(In,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:C.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(Cs,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:C.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(dn,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:C.totalCompletedTasks}),t.jsx("span",{className:"project-stat__label",children:"Completed"})]})]}),C.erroredProjects>0&&t.jsxs("div",{className:"project-stat project-stat--error",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:C.erroredProjects}),t.jsx("span",{className:"project-stat__label",children:"Errored"})]})]}),C.totalNodes>1&&t.jsxs("div",{className:"project-stat project-stat--nodes",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(mo,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:C.totalNodes}),t.jsx("span",{className:"project-stat__label",children:"Nodes"})]})]})]}),t.jsxs("button",{className:"btn btn-primary project-overview__add-btn",onClick:i,children:[t.jsx(Zt,{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 ${u==="all"?"active":""}`,onClick:()=>d("all"),children:["All",t.jsx("span",{className:"project-filter-count",children:z.all})]}),t.jsxs("button",{className:`project-filter-tab ${u==="active"?"active":""}`,onClick:()=>d("active"),children:["Active",t.jsx("span",{className:"project-filter-count",children:z.active})]}),t.jsxs("button",{className:`project-filter-tab ${u==="paused"?"active":""}`,onClick:()=>d("paused"),children:["Paused",t.jsx("span",{className:"project-filter-count",children:z.paused})]}),t.jsxs("button",{className:`project-filter-tab ${u==="errored"?"active":""} ${z.errored>0?"has-errors":""}`,onClick:()=>d("errored"),children:["Errored",t.jsx("span",{className:"project-filter-count",children:z.errored})]})]}),A.length>1&&t.jsxs("div",{className:"project-node-filter",children:[t.jsx(mo,{size:14}),t.jsxs("select",{value:m??"",onChange:W=>{h(W.target.value||null)},className:"project-node-filter-select","aria-label":"Filter by node",children:[t.jsx("option",{value:"",children:"All Nodes"}),A.map(({nodeId:W,name:$,count:_})=>t.jsxs("option",{value:W??"",children:[$," (",_,")"]},W??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(uo,{size:14}),t.jsxs("select",{value:`${g}-${f}`,onChange:W=>{const[$,_]=W.target.value.split("-");p($),x(_)},className:"project-sort-select","aria-label":"Sort projects",children:[t.jsx("option",{value:"activity-desc",children:"Last Activity (Newest)"}),t.jsx("option",{value:"activity-asc",children:"Last Activity (Oldest)"}),t.jsx("option",{value:"name-asc",children:"Name (A-Z)"}),t.jsx("option",{value:"name-desc",children:"Name (Z-A)"}),t.jsx("option",{value:"status-asc",children:"Status (Error → Active)"}),t.jsx("option",{value:"status-desc",children:"Status (Active → Error)"})]}),t.jsx(Lh,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:M.map(({project:W,health:$})=>{const _=c.find(O=>O.id===W.nodeId),I=_?void 0:W._sourceNodeName;return t.jsx(DN,{project:W,health:$,node:_,nodeNameFallback:I,onSelect:P,onPause:r,onResume:o,onRemove:l},W.id)})}),M.length===0&&t.jsxs("div",{className:"project-overview__no-results",children:[t.jsx(uo,{size:32}),t.jsx("p",{children:"No projects match the current filter"}),t.jsx("button",{className:"btn btn-secondary",onClick:()=>d("all"),children:"Show All Projects"})]})]})}const UN=45e3,BN=3e3,HN=2e3,qN=1500,Tu="fusion:sse-client-id";let Zi=null;const vi=new Map;function Pu(){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 Ep(){if(!(typeof window>"u")){if(Zi)return Zi;try{const e=window.sessionStorage.getItem(Tu);if(e)return Zi=e,e;const n=Pu();return window.sessionStorage.setItem(Tu,n),Zi=n,n}catch{return Zi=Pu(),Zi}}}function _p(e){if(!(typeof window>"u"))try{return{parsed:new URL(e,window.location.origin),preserveRelativePath:e.startsWith("/")}}catch{return}}function Mp(e){return e.origin===window.location.origin&&e.pathname==="/api/events"}function VN(e){const n=Ep();if(!n)return e;const s=_p(e);return!s||!Mp(s.parsed)?e:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function nd(e,n){const s=Ep();if(!s)return;const i=_p(e);if(!i||!Mp(i.parsed))return;const r=new URL(`/api/events/${n}`,window.location.origin);r.searchParams.set("clientId",s);const o=i.parsed.searchParams.get("projectId");return o&&r.searchParams.set("projectId",o),Qs(`${r.pathname}${r.search}${r.hash}`)}function WN(e){if(typeof window>"u")return;const n=nd(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 Ho(e){e.keepaliveTimer&&(clearInterval(e.keepaliveTimer),e.keepaliveTimer=null)}function Iu(e){if(typeof window>"u"||typeof window.fetch!="function")return;const n=nd(e.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,i=s?window.setTimeout(()=>s.abort(),qN):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{i!==null&&window.clearTimeout(i)})}function KN(e){Ho(e),nd(e.url,"keepalive")&&(Iu(e),e.keepaliveTimer=window.setInterval(()=>{Iu(e)},HN))}if(typeof window<"u"){const e=()=>{for(const s of Array.from(vi.values()))if(!s.closed){if(Ho(s),WN(s),s.es){try{s.es.close()}catch{}s.es=null}s.closed=!0}},n=s=>{if(s.persisted)for(const i of Array.from(vi.values()))i.subscribers.size!==0&&(i.closed=!1,sd(i))};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("pageshow",n)}function er(e){e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),e.heartbeatTimer=setTimeout(()=>{Ap(e)},UN)}function Ap(e){if(e.heartbeatTimer&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=null),e.es&&(e.es.close(),e.es=null),Ho(e),e.nativeListeners.clear(),e.closed||e.subscribers.size===0||e.reconnectTimer)return;const n=vi.get(e.url);if(!(!n||n!==e)){for(const s of e.subscribers)s.onReconnect?.();e.reconnectTimer=setTimeout(()=>{if(e.reconnectTimer=null,e.closed)return;const s=vi.get(e.url);s&&s===e&&e.subscribers.size>0&&sd(e)},BN)}}function sd(e){if(e.es||e.closed)return;e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);const n=new EventSource(Qs(VN(e.url)));e.es=n,KN(e),n.addEventListener("open",()=>{er(e);const s=e.hasOpenedOnce;e.hasOpenedOnce=!0;for(const i of e.subscribers)i.onOpen?.(),s&&i.onReconnect?.()}),n.addEventListener("error",s=>{for(const i of e.subscribers)i.onError?.(s);Ap(e)}),n.addEventListener("message",()=>er(e)),n.addEventListener("heartbeat",()=>er(e)),Rp(e),er(e)}function Rp(e){if(!e.es)return;const n=new Set;for(const s of e.subscribers)for(const i of s.events.keys())n.add(i);for(const s of n){if(e.nativeListeners.has(s))continue;const i=r=>{er(e);const o=r;for(const l of e.subscribers){const c=l.events.get(s);if(c)for(const u of c)u(o)}};e.nativeListeners.set(s,i),e.es.addEventListener(s,i)}}function GN(e){e.closed=!0,e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),Ho(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.es&&e.es.close(),e.es=null,e.nativeListeners.clear(),vi.delete(e.url)}function Ls(e,n={}){let s=vi.get(e);s||(s={url:e,es:null,subscribers:new Set,nativeListeners:new Map,heartbeatTimer:null,keepaliveTimer:null,reconnectTimer:null,hasOpenedOnce:!1,closed:!1},vi.set(e,s));const i={events:new Map,onOpen:n.onOpen,onReconnect:n.onReconnect,onError:n.onError};if(n.events)for(const[o,l]of Object.entries(n.events)){let c=i.events.get(o);c||(c=new Set,i.events.set(o,c)),c.add(l)}s.subscribers.add(i),sd(s),Rp(s);let r=!0;return()=>{if(!r)return;r=!1;const o=vi.get(e);o&&(o.subscribers.delete(i),o.subscribers.size===0&&GN(o))}}const id="kb-planning-last-description",ad="kb-subtask-last-description",rd="kb-mission-last-goal";function JN(e,n){os(id,e,n)}function YN(e){return Dn(id,e)||""}function ea(e){pr(id,e)}function QN(e,n){os(ad,e,n)}function XN(e){return Dn(ad,e)||""}function bl(e){pr(ad,e)}function ZN(e,n){os(rd,e,n)}function e1(e){return Dn(rd,e)||""}function fi(e){pr(rd,e)}function t1(e){const{question:n,response:s}=e;if(!n)return s;if(s&&typeof s=="object"&&!Array.isArray(s)){const i=s;if(n.id in i)return i[n.id]}return s}function n1(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(i=>i.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 s1(e){let n=0;const s=[];for(const i of e){if(i.question){n+=1,s.push({...i,questionNumber:n});continue}i.thinkingOutput&&s.push({...i,questionNumber:null})}return s}function Es({entries:e,defaultShowThinking:n=!1}){const[s,i]=a.useState({}),r=s1(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,u=!!o.thinkingOutput,d=s[l]??n,m=c?t1(o):void 0,h=o.question&&m!==void 0?n1(o.question,m):"";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||"—"})]}),u&&t.jsxs("div",{className:"conversation-entry-thinking",children:[t.jsxs("button",{type:"button",className:"conversation-thinking-toggle",onClick:()=>{i(g=>({...g,[l]:!d}))},"aria-expanded":d,children:[t.jsx("span",{"aria-hidden":"true",children:d?"▾":"▸"}),d?`Hide ${c?"AI thinking":"AI reasoning"}`:`Show ${c?"AI thinking":"AI reasoning"}`]}),d&&t.jsx("pre",{children:o.thinkingOutput})]})]},`${o.question?.id??"thinking"}-${l}`)})})}const $u="fusion-tab-id";function i1(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Wi(){if(typeof window>"u")return"server-tab";const e=window.sessionStorage.getItem($u);if(e)return e;const n=i1();return window.sessionStorage.setItem($u,n),n}function qo(e){const n=a.useMemo(()=>Wi(),[]),[s,i]=a.useState(!1),[r,o]=a.useState(null),[l,c]=a.useState(!1);a.useEffect(()=>{if(!e){i(!1),o(null),c(!1);return}let d=!0;return c(!0),Promise.resolve(Pj(e,n)).then(m=>{if(d){if(m.acquired){i(!1),o(null);return}i(!0),o(m.currentHolder)}}).catch(()=>{d&&(i(!1),o(null))}).finally(()=>{d&&c(!1)}),()=>{d=!1;try{const m=Ij(e,n);m&&typeof m.catch=="function"&&m.catch(()=>{})}catch{}}},[e,n]),a.useEffect(()=>{if(!e||typeof window>"u")return;const d=()=>{if(typeof navigator.sendBeacon!="function")return;const m=Qs(`/api/ai-sessions/${encodeURIComponent(e)}/lock/beacon?tabId=${encodeURIComponent(n)}`);navigator.sendBeacon(m)};return window.addEventListener("beforeunload",d),()=>{window.removeEventListener("beforeunload",d)}},[e,n]),a.useEffect(()=>!e||typeof EventSource>"u"?void 0:Ls("/api/events",{events:{"ai_session:updated":m=>{try{const h=JSON.parse(m.data);if(h.id!==e)return;const g=h.lockedByTab??null;o(g),i(!!(g&&g!==n))}catch{}}}}),[e,n]);const u=a.useCallback(async()=>{if(e){c(!0);try{await Promise.resolve($j(e,n)),i(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:u,isLoading:l}}const a1="fusion:ai-session-sync",Du="fusion:ai-session-sync",r1=3e4,o1=6e4;function Hs(){return Date.now()}function l1(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Lu(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 c1{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=l1(),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:Hs()})}broadcastUpdate(n){const s=n.timestamp??Hs();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",i=n.timestamp??Hs();this.applySessionUpdate({sessionId:n.sessionId,status:s,needsInput:!1,owningTabId:null},i),this.ownershipBySession.delete(n.sessionId),this.ownedSessions.delete(n.sessionId),this.emit(),this.publish({type:"session:completed",sessionId:n.sessionId,status:s,timestamp:i})}broadcastLock(n,s){const i=Hs();this.applyTabOwnership(n,s,i),this.ownedSessions.set(n,s),this.publish({type:"tab:active",tabId:s,sessionId:n,timestamp:i})}broadcastUnlock(n,s){const i=Hs();this.releaseTabOwnership(n,s,i),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:i})}broadcastHeartbeat(n){const s=Hs();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(a1),this.channel.onmessage=s=>{const i=Lu(s.data);i&&this.handleIncomingMessage(i)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==Du||!s.newValue))try{const i=JSON.parse(s.newValue),r=Lu(i.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=Hs();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},r1)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,i]of this.ownedSessions.entries()){const r=Hs();this.publish({type:"tab:inactive",tabId:i,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 i={id:`${s.type}-${s.timestamp}-${Math.random().toString(36).slice(2,8)}`,message:s};window.localStorage.setItem(Du,JSON.stringify(i))}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}}),i=[...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:i,heartbeats:r,timestamp:Hs()});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,i=!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)),i&&this.emit()}applyTabOwnership(n,s,i,r=!0){const o=this.ownershipBySession.get(n);if(o&&i<o.timestamp)return;this.ownershipBySession.set(n,{tabId:s,timestamp:i}),this.updateHeartbeat(s,i,!1);const l=this.sessionStates.get(n);l&&i>=l.lastEventTimestamp&&this.sessionStates.set(n,{...l,owningTabId:s,lastEventTimestamp:i}),r&&this.emit()}releaseTabOwnership(n,s,i,r=!0){const o=this.ownershipBySession.get(n);if(!o||o.tabId!==s||i<o.timestamp)return;this.ownershipBySession.delete(n);const l=this.sessionStates.get(n);l&&i>=l.lastEventTimestamp&&this.sessionStates.set(n,{...l,owningTabId:null,lastEventTimestamp:i}),r&&this.emit()}updateHeartbeat(n,s,i=!0){const r=this.heartbeatByTab.get(n);r!==void 0&&s<r||(this.heartbeatByTab.set(n,s),i&&this.emit())}emit(){const n=Hs(),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 i=new Map;for(const[r,o]of this.ownershipBySession.entries()){const l=this.heartbeatByTab.get(o.tabId)??o.timestamp,c=n-l>o1;i.set(r,{sessionId:r,tabId:o.tabId,lastHeartbeatTimestamp:l,lastLockTimestamp:o.timestamp,stale:c})}this.snapshot={tabId:this.tabId,sessions:s,activeTabMap:i};for(const r of this.listeners)r()}}const qs=new c1;function Sa(){const e=a.useSyncExternalStore(c=>qs.subscribe(c),()=>qs.getSnapshot(),()=>qs.getSnapshot());a.useEffect(()=>{qs.requestSync()},[]);const n=a.useCallback(c=>{qs.broadcastUpdate(c)},[]),s=a.useCallback(c=>{qs.broadcastCompleted(c)},[]),i=a.useCallback((c,u)=>{qs.broadcastLock(c,u)},[]),r=a.useCallback((c,u)=>{qs.broadcastUnlock(c,u)},[]),o=a.useCallback(c=>{qs.broadcastHeartbeat(c)},[]),l=a.useCallback(()=>{qs.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:i,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function d1(e,n){return e&&n?`${e}/${n}`:""}function u1(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 m1=["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 h1({isOpen:e,onClose:n,onMissionCreated:s,projectId:i,initialGoal:r,resumeSessionId:o}){const[l,c]=a.useState(""),[u,d]=a.useState({type:"initial"}),[m,h]=a.useState(null),[g,p]=a.useState([]),[f,x]=a.useState([]),[v,b]=a.useState(null),[y,S]=a.useState(!1),k=a.useRef(!1),[R,N]=a.useState(""),[M,C]=a.useState(!0),[z,A]=a.useState(!1),[P,F]=a.useState(!1),[W,$]=a.useState(!1),_=a.useRef(null),I=a.useRef(null),O=a.useRef(null),J=a.useRef(null),[Q,E]=a.useState(o??null),D=a.useMemo(()=>Wi(),[]),{isLockedByOther:T,takeControl:w,isLoading:q}=qo(e?Q:null),{activeTabMap:G,broadcastUpdate:me,broadcastCompleted:ce,broadcastLock:ae,broadcastUnlock:pe,broadcastHeartbeat:U}=Sa(),{confirm:Ne}=Ds(),[ne,xe]=a.useState(void 0),[le,ve]=a.useState(void 0),[ee,Ee]=a.useState([]),[Fe,Ke]=a.useState(!0),[Ze,Xe]=a.useState(null),[Qe,it]=a.useState([]),[Ie,Ge]=a.useState([]),se=d1(ne,le);a.useEffect(()=>{(async()=>{try{Ke(!0);const ue=await cs();Ee(ue.models),it(ue.favoriteProviders),Ge(ue.favoriteModels)}catch(ue){Xe(ke(ue)||"Failed to load models")}finally{Ke(!1)}})()},[]);const ye=a.useCallback(re=>{it(ue=>{const Pe=ue,fe=Pe.includes(re)?Pe.filter(tt=>tt!==re):[re,...Pe];return sn({favoriteProviders:fe,favoriteModels:Ie}).catch(()=>{it(Pe)}),fe})},[Ie]),Z=a.useCallback(re=>{Ge(ue=>{const Pe=ue,fe=Pe.includes(re)?Pe.filter(tt=>tt!==re):[re,...Pe];return sn({favoriteProviders:Qe,favoriteModels:fe}).catch(()=>{Ge(Pe)}),fe})},[Qe]),Te=a.useCallback((re,ue)=>{if(!re||!ue)return"Using default";const Pe=ee.find(Se=>Se.provider===re&&Se.id===ue);return Pe?`${Pe.provider}/${Pe.id}`:`${re}/${ue}`},[ee]),ze=a.useCallback(re=>{I.current?.close();const ue=kj(re,i,{onThinking:Pe=>{N(Se=>Se+Pe),me({sessionId:re,status:"generating",needsInput:!1,owningTabId:D,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onQuestion:Pe=>{A(!1),F(!1),fi(i),d({type:"question",sessionId:re,question:Pe}),N(""),S(!0),me({sessionId:re,status:"awaiting_input",needsInput:!0,owningTabId:D,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onSummary:Pe=>{A(!1),F(!1),fi(i),d({type:"summary",sessionId:re,summary:Pe}),b(Pe),N(""),S(!0),me({sessionId:re,status:"complete",needsInput:!1,owningTabId:D,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onError:Pe=>{const Se=Pe||"Session failed while contacting the AI.";A(!1),F(!1),h(null),d({type:"error",sessionId:re,errorMessage:Se}),N(""),S(!0),O.current=re,me({sessionId:re,status:"error",needsInput:!1,owningTabId:D,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null}),ce({sessionId:re,status:"error"})},onComplete:()=>{A(!1),F(!1),O.current=null,ce({sessionId:re,status:"complete"})},onConnectionStateChange:Pe=>{A(Pe==="reconnecting")}});I.current=ue},[ce,me,l,i,D]),be=a.useCallback(async re=>{const ue=re??l;if(ue.trim()){h(null),N(""),p([]),x([]),A(!1),d({type:"loading"});try{const{sessionId:Pe}=await xj(ue.trim(),i,ne&&le?{modelProvider:ne,modelId:le}:void 0);O.current=Pe,E(Pe),fi(i),ze(Pe),p([])}catch(Pe){A(!1),h(ke(Pe)||"Failed to start interview session"),d({type:"initial"}),O.current=null,E(null)}}},[ze,l,ne,le,i]);a.useEffect(()=>{e&&u.type==="initial"&&_.current?.focus()},[e,u.type]),a.useEffect(()=>{if(e&&r&&!k.current&&u.type==="initial"){c(r);const re=setTimeout(()=>{k.current=!0,be(r)},0);return()=>clearTimeout(re)}else if(e&&!r&&!k.current&&u.type==="initial"){const re=e1(i);re&&c(re)}},[e,r,u.type,be]),a.useEffect(()=>{e||(k.current=!1,A(!1),F(!1),E(null))},[e]),a.useEffect(()=>{if(!e||!o||u.type!=="initial")return;let re=!1;return oi(o).then(ue=>{if(re||!ue)return;const Pe=fa(ue.conversationHistory);if(x(Pe),E(ue.id),p(Pe.map(Se=>Se.response).filter(Se=>!!(Se&&typeof Se=="object"&&!Array.isArray(Se)))),ue.status==="awaiting_input"&&ue.currentQuestion)try{fi(i);const Se=JSON.parse(ue.currentQuestion);O.current=ue.id,S(!0),d({type:"question",sessionId:ue.id,question:Se})}catch{h("Failed to restore session question.")}else if(ue.status==="complete"&&ue.result)try{fi(i);const Se=JSON.parse(ue.result);O.current=ue.id,S(!0),b(Se),d({type:"summary",sessionId:ue.id,summary:Se})}catch{h("Failed to restore session result.")}else ue.status==="generating"?(O.current=ue.id,S(!0),ue.thinkingOutput&&N(ue.thinkingOutput),d({type:"loading"}),ze(ue.id)):ue.status==="error"&&(O.current=ue.id,S(!0),h(null),d({type:"error",sessionId:ue.id,errorMessage:ue.error??"The session encountered an error."}))}).catch(()=>{re||h("Failed to resume session.")}),()=>{re=!0}},[ze,e,o,u.type,i]),a.useEffect(()=>{if(!e){J.current&&(pe(J.current,D),J.current=null);return}if(Q&&J.current!==Q){J.current&&pe(J.current,D),ae(Q,D),J.current=Q;return}!Q&&J.current&&(pe(J.current,D),J.current=null)},[ae,pe,e,Q,D]),a.useEffect(()=>{if(!e||!Q||J.current!==Q)return;U(D);const re=setInterval(()=>{U(D)},3e4);return()=>{clearInterval(re)}},[U,e,Q,D]),a.useEffect(()=>()=>{I.current?.close(),I.current=null,J.current&&(pe(J.current,D),J.current=null)},[pe,D]),a.useEffect(()=>{if(!e)return;const re=ue=>{(u.type==="question"||u.type==="summary")&&(ue.preventDefault(),ue.returnValue=""),I.current?.close()};return window.addEventListener("beforeunload",re),()=>window.removeEventListener("beforeunload",re)},[e,u]);const Me=a.useCallback(()=>{I.current?.close(),I.current=null,n()},[n]),Be=a.useCallback(async()=>{if(l&&ZN(l,i),!(y&&!await Ne({title:"Close Interview",message:"Are you sure you want to close? Your interview progress will be lost.",danger:!0}))){if(I.current?.close(),I.current=null,u.type==="question"||u.type==="summary"||u.type==="error")try{await dp(u.sessionId,i,D)}catch{}c(""),d({type:"initial"}),h(null),p([]),x([]),b(null),N(""),A(!1),F(!1),S(!1),$(!1),xe(void 0),ve(void 0),O.current=null,E(null),n()}},[l,y,u,n,i,D,Ne]);a.useEffect(()=>{if(!e)return;const re=ue=>{ue.key==="Escape"&&Be()};return document.addEventListener("keydown",re),()=>document.removeEventListener("keydown",re)},[e,Be]);const lt=a.useCallback(async re=>{if(u.type!=="question")return;const{sessionId:ue}=u;h(null),p(Pe=>[...Pe,re]),x(Pe=>[...Pe,{question:u.question,response:re}]),d({type:"loading"}),N("");try{ze(ue),await bj(ue,re,i,D),S(!0)}catch(Pe){I.current?.close(),I.current=null,h(ke(Pe)||"Failed to submit response"),d({type:"question",sessionId:ue,question:u.question})}},[u,i,D,ze]),je=a.useCallback(async()=>{if(u.type!=="error")return;const re=u.sessionId;h(null),F(!0),N(""),d({type:"loading"}),ze(re);try{O.current=re,E(re),await vj(re,i,D)}catch(ue){let Pe=ue;if((ke(ue)||"").includes("not in an error state"))try{const fe=await oi(re);if(!fe)throw new Error("Failed to refresh interview session.");const tt=fa(fe.conversationHistory);if(x(tt),p(tt.map(ut=>ut.response).filter(ut=>!!(ut&&typeof ut=="object"&&!Array.isArray(ut)))),O.current=fe.id,E(fe.id),S(!0),fe.status==="generating")N(fe.thinkingOutput??""),d({type:"loading"}),I.current?.isConnected()||ze(fe.id);else if(fe.status==="awaiting_input"){if(!fe.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");fi(i);const ut=JSON.parse(fe.currentQuestion);d({type:"question",sessionId:fe.id,question:ut}),I.current?.isConnected()||ze(fe.id)}else if(fe.status==="complete"){if(!fe.result)throw new Error("Interview session is complete but has no result.");fi(i);const ut=JSON.parse(fe.result);b(ut),d({type:"summary",sessionId:fe.id,summary:ut})}else fe.status==="error"&&d({type:"error",sessionId:fe.id,errorMessage:fe.error??"Retry failed. Please try again."});A(!1);return}catch(fe){Pe=fe}I.current?.close(),I.current=null,d({type:"error",sessionId:re,errorMessage:ke(Pe)||"Retry failed. Please try again."}),A(!1)}finally{F(!1)}},[ze,i,D,u]),ie=a.useCallback(async()=>{if(u.type==="summary"){h(null),$(!0);try{const re=await yj(u.sessionId,v||void 0,i);s(re),fi(i),I.current?.close(),I.current=null,c(""),d({type:"initial"}),h(null),p([]),x([]),b(null),N(""),A(!1),F(!1),S(!1),$(!1),O.current=null,E(null),n()}catch(re){h(ke(re)||"Failed to create mission"),$(!1)}}},[u,v,s,n,i]),Ae=()=>u.type==="question"?Math.min(g.length+1,6):6,he=u.type==="loading"||u.type==="question"||u.type==="summary"||u.type==="error",Re=Q?G.get(Q):null,Je=Re&&Re.tabId!==D,$e=!!(Je&&!Re.stale),de=T&&(!Je||Re.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:re=>re.target===re.currentTarget&&Be(),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(ls,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Plan Mission with AI"})]}),t.jsxs("div",{className:"modal-header-actions",children:[he&&t.jsx("button",{className:"modal-send-to-background",onClick:Me,title:"Send to background","aria-label":"Send to background",children:t.jsx(yr,{size:16})}),t.jsx("button",{className:"modal-close",onClick:Be,"aria-label":"Close",children:t.jsx(Ot,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[m&&t.jsx("div",{className:"form-error planning-error",children:m}),z&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),$e&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),u.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(qn,{size:32,className:"icon-triage-lg"}),t.jsx("h4",{children:"Transform your vision into a structured mission"}),t.jsx("p",{className:"text-muted",children:"Describe what you want to build. The AI will interview you to understand scope, constraints, and requirements, then produce a structured plan with milestones, slices, and features."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"mission-goal",children:"What do you want to build?"}),t.jsx("textarea",{ref:_,id:"mission-goal",rows:4,className:"planning-textarea",placeholder:"e.g., Build a real-time collaborative document editor with presence, comments, and version history...",value:l,onChange:re=>c(re.target.value),onKeyDown:re=>{re.key==="Enter"&&!re.shiftKey&&l.trim()&&(re.preventDefault(),be())}})]}),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:m1.map((re,ue)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c(re),children:re.length>45?re.slice(0,45)+"...":re},ue))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",Fe&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx($n,{id:"mission-interview-modal-model",label:"Planning Model",value:se,onChange:re=>{const{provider:ue,modelId:Pe}=u1(re);xe(ue),ve(Pe)},models:ee,disabled:Fe,favoriteProviders:Qe,onToggleFavorite:ye,favoriteModels:Ie,onToggleModelFavorite:Z}),Ze&&t.jsxs("div",{className:"form-hint form-hint-error",children:[Ze," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{Ke(!0);const re=await cs();Ee(re.models),it(re.favoriteProviders),Ge(re.favoriteModels),Xe(null)}catch(re){Xe(ke(re)||"Failed to load models")}finally{Ke(!1)}})()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${ne&&le?"model-badge-custom":"model-badge-default"}`,children:Te(ne,le)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>be(),disabled:!l.trim(),children:[t.jsx(ls,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),u.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(ot,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:R?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>C(!M),type:"button",children:M?"Hide thinking":"Show thinking"}),M&&R&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:R})})]})]}),u.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[f.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Es,{entries:f}),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:u.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void je(),disabled:P,children:[P?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Nn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:P?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Be,disabled:P,children:"Cancel"})]})]})]})}),u.type==="question"&&t.jsx(p1,{question:u.question,progress:Ae(),historyEntries:f,onSubmit:lt}),u.type==="summary"&&v&&t.jsx(f1,{summary:v,historyEntries:f,onSummaryChange:b,onApprove:ie,onStartOver:()=>{d({type:"initial"}),S(!1),b(null),p([]),x([]),E(null),I.current?.close(),I.current=null},isCreating:W}),T&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Io,{size:16}),t.jsx("span",{children:de?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),de&&t.jsx("button",{type:"button",onClick:()=>{w()},disabled:q,className:"btn btn-primary session-lock-take-control",children:q?"Taking control...":"Take Control"})]})})]})]})}):null}function p1({question:e,progress:n,historyEntries:s,onSubmit:i}){const[r,o]=a.useState({}),[l,c]=a.useState(""),u=a.useCallback(()=>{e.type==="text"?i({[e.id]:l}):e.type==="confirm"?i({[e.id]:r[e.id]===!0}):i(r)},[e,r,l,i]);a.useEffect(()=>{o({}),c("")},[e.id]);const d=()=>{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(Es,{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(m=>t.jsx("div",{className:`planning-progress-step ${m<=n?"active":""}`},m))}),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:m=>c(m.target.value),onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&l.trim()&&(m.preventDefault(),u())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(m=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:m.id,checked:r[e.id]===m.id,onChange:()=>o({[e.id]:m.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(m=>{const h=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:m.id,checked:h.includes(m.id),onChange:g=>{const p=g.target.checked?[...h,m.id]:h.filter(f=>f!==m.id);o({[e.id]:p})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.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(dn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Ot,{size:18}),"No"]})]})]})]})]})]}),t.jsx("div",{className:"planning-actions",children:t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:u,disabled:!d(),children:["Continue",t.jsx(br,{size:16,className:"icon-ml-4"})]})})]})}function f1({summary:e,historyEntries:n,onSummaryChange:s,onApprove:i,onStartOver:r,isCreating:o}){const[l,c]=a.useState(()=>new Set(e.milestones.map((k,R)=>R))),[u,d]=a.useState(()=>{const k=new Set;return e.milestones.forEach((R,N)=>{R.slices.forEach((M,C)=>k.add(`${N}-${C}`))}),k}),m=k=>{c(R=>{const N=new Set(R);return N.has(k)?N.delete(k):N.add(k),N})},h=k=>{d(R=>{const N=new Set(R);return N.has(k)?N.delete(k):N.add(k),N})},g=(k,R)=>{const N=[...e.milestones];N[k]={...N[k],...R},s({...e,milestones:N})},p=(k,R,N)=>{const M=[...e.milestones],C=[...M[k].slices];C[R]={...C[R],...N},M[k]={...M[k],slices:C},s({...e,milestones:M})},f=(k,R,N,M)=>{const C=[...e.milestones],z=[...C[k].slices],A=[...z[R].features];A[N]={...A[N],...M},z[R]={...z[R],features:A},C[k]={...C[k],slices:z},s({...e,milestones:C})},x=k=>{const R=e.milestones.filter((N,M)=>M!==k);s({...e,milestones:R})},v=(k,R)=>{const N=[...e.milestones];N[k]={...N[k],slices:N[k].slices.filter((M,C)=>C!==R)},s({...e,milestones:N})},b=(k,R,N)=>{const M=[...e.milestones],C=[...M[k].slices];C[R]={...C[R],features:C[R].features.filter((z,A)=>A!==N)},M[k]={...M[k],slices:C},s({...e,milestones:M})},y=(k,R)=>{const N=[...e.milestones],M=[...N[k].slices];M[R]={...M[R],features:[...M[R].features,{title:"New feature",description:""}]},N[k]={...N[k],slices:M},s({...e,milestones:N})},S=e.milestones.reduce((k,R)=>k+R.slices.reduce((N,M)=>N+M.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(Es,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(dn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Mission Plan Ready"}),t.jsxs("p",{className:"text-muted",children:[e.milestones.length," milestones, ",S," features. Review and edit before approving."]})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Title"}),t.jsx("input",{type:"text",className:"form-input",value:e.missionTitle||"",onChange:k=>s({...e,missionTitle:k.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Description"}),t.jsx("textarea",{className:"planning-textarea",rows:3,value:e.missionDescription||"",onChange:k=>s({...e,missionDescription:k.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Roadmap"}),t.jsx("div",{className:"roadmap-list",children:e.milestones.map((k,R)=>t.jsxs("div",{className:"roadmap-card",children:[t.jsxs("div",{className:"roadmap-card-header",onClick:()=>m(R),children:[l.has(R)?t.jsx(qt,{size:16,className:"icon-text-secondary"}):t.jsx(hn,{size:16,className:"icon-text-secondary"}),t.jsx(Ui,{size:16,className:"icon-milestone"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:k.title,onChange:N=>g(R,{title:N.target.value}),onClick:N=>N.stopPropagation()}),e.milestones.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:N=>{N.stopPropagation(),x(R)},title:"Remove milestone",children:t.jsx(Xt,{size:14,className:"icon-text-secondary"})})]}),l.has(R)&&t.jsxs("div",{className:"roadmap-card-body",children:[t.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:k.description||"",onChange:N=>g(R,{description:N.target.value})}),t.jsxs("div",{className:"roadmap-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Verification Criteria"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-sm",rows:2,placeholder:"How to confirm this milestone is complete...",value:k.verification||"",onChange:N=>g(R,{verification:N.target.value})})]}),k.slices.map((N,M)=>{const C=`${R}-${M}`;return t.jsxs("div",{className:"roadmap-slice-card",children:[t.jsxs("div",{className:"roadmap-slice-header",onClick:()=>h(C),children:[u.has(C)?t.jsx(qt,{size:14,className:"icon-text-secondary"}):t.jsx(hn,{size:14,className:"icon-text-secondary"}),t.jsx(bc,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:N.title,onChange:z=>p(R,M,{title:z.target.value}),onClick:z=>z.stopPropagation()}),k.slices.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:z=>{z.stopPropagation(),v(R,M)},title:"Remove slice",children:t.jsx(Xt,{size:12,className:"icon-text-secondary"})})]}),u.has(C)&&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:N.verification||"",onChange:z=>p(R,M,{verification:z.target.value})})]}),N.features.map((z,A)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(uc,{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:z.title,onChange:P=>f(R,M,A,{title:P.target.value})}),z.description&&t.jsx("p",{className:"roadmap-feature-text",children:z.description}),z.acceptanceCriteria&&t.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",z.acceptanceCriteria]})]}),t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>b(R,M,A),title:"Remove feature",children:t.jsx(Xt,{size:12,className:"icon-text-secondary"})})]},A)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>y(R,M),children:[t.jsx(Zt,{size:12}),"Add Feature"]})]})]},M)})]})]},R))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:o,children:[t.jsx(wa,{size:16,className:"icon-mr-4"}),"Start Over"]}),t.jsx("button",{className:"btn btn-primary",onClick:i,disabled:o||e.milestones.length===0,children:o?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):t.jsxs(t.Fragment,{children:[t.jsx(dn,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}function g1({isOpen:e,onClose:n,onApplied:s,targetType:i,targetId:r,targetTitle:o,missionContext:l,projectId:c,resumeSessionId:u}){const[d,m]=a.useState({type:"initial"}),[h,g]=a.useState(null),[p,f]=a.useState([]),[x,v]=a.useState([]),[b,y]=a.useState(null),[S,k]=a.useState(""),[R,N]=a.useState(!0),[M,C]=a.useState(!1),[z,A]=a.useState(!1),P=a.useRef(null),F=a.useRef(null),W=a.useRef(null),$=a.useRef(null),[_,I]=a.useState(null),O=a.useMemo(()=>Wi(),[]);qo(e?_:null);const{activeTabMap:J,broadcastUpdate:Q,broadcastCompleted:E,broadcastLock:D,broadcastUnlock:T,broadcastHeartbeat:w}=Sa(),q=i==="milestone"?jj:Ej,G=i==="milestone"?wj:_j,me=i==="milestone"?Nj:Mj,ce=i==="milestone"?Sj:Aj,ae=i==="milestone"?Cj:Rj,pe=i==="milestone"?"Milestone":"Slice",U=i==="milestone"?"milestone_interview":"slice_interview",Ne=a.useCallback(Ie=>{F.current?.close();const Ge=me(Ie,c,{onThinking:se=>{k(ye=>ye+se),Q({sessionId:Ie,status:"generating",needsInput:!1,owningTabId:O,type:U,title:o,projectId:c??null})},onQuestion:se=>{C(!1),ne(),m({type:"question",sessionId:Ie,question:se}),k(""),Q({sessionId:Ie,status:"awaiting_input",needsInput:!0,owningTabId:O,type:U,title:o,projectId:c??null})},onSummary:se=>{C(!1),ne(),m({type:"summary",sessionId:Ie,summary:se}),y(se),k(""),Q({sessionId:Ie,status:"complete",needsInput:!1,owningTabId:O,type:U,title:o,projectId:c??null})},onError:se=>{const ye=se||"Session failed while contacting the AI.";C(!1),g(null),m({type:"error",sessionId:Ie,errorMessage:ye}),k(""),W.current=Ie,Q({sessionId:Ie,status:"error",needsInput:!1,owningTabId:O,type:U,title:o,projectId:c??null}),E({sessionId:Ie,status:"error"})},onComplete:()=>{C(!1),W.current=null,E({sessionId:Ie,status:"complete"})},onConnectionStateChange:se=>{C(se==="reconnecting")}});F.current=Ge},[E,Q,me,U,c,O,o]),ne=()=>{y(null),f([]),v([]),k("")},xe=a.useCallback(async()=>{g(null),ne(),C(!1),m({type:"loading"});try{const{sessionId:Ie}=await q(r,c);W.current=Ie,I(Ie),Ne(Ie)}catch(Ie){C(!1),g(ke(Ie)||`Failed to start ${pe.toLowerCase()} interview`),m({type:"initial"}),W.current=null,I(null)}},[Ne,c,q,r,pe]),le=a.useCallback(async()=>{g(null),A(!0);try{await ae(r,c),s(),m({type:"applied"})}catch(Ie){g(ke(Ie)||`Failed to skip ${pe.toLowerCase()} interview`),A(!1)}},[s,c,ae,r,pe]);a.useEffect(()=>{e&&d.type==="initial"&&P.current?.focus()},[e,d.type]),a.useEffect(()=>{if(!e||!u||d.type!=="initial")return;let Ie=!1;return oi(u).then(Ge=>{if(Ie||!Ge)return;const se=fa(Ge.conversationHistory);if(v(se),I(Ge.id),f(se.map(ye=>ye.response).filter(ye=>!!(ye&&typeof ye=="object"&&!Array.isArray(ye)))),Ge.status==="awaiting_input"&&Ge.currentQuestion)try{const ye=JSON.parse(Ge.currentQuestion);W.current=Ge.id,m({type:"question",sessionId:Ge.id,question:ye})}catch{g("Failed to restore session question.")}else if(Ge.status==="complete"&&Ge.result)try{const ye=JSON.parse(Ge.result);W.current=Ge.id,y(ye),m({type:"summary",sessionId:Ge.id,summary:ye})}catch{g("Failed to restore session result.")}else Ge.status==="generating"?(W.current=Ge.id,Ge.thinkingOutput&&k(Ge.thinkingOutput),m({type:"loading"}),Ne(Ge.id)):Ge.status==="error"&&(W.current=Ge.id,g(null),m({type:"error",sessionId:Ge.id,errorMessage:Ge.error??"The session encountered an error."}))}).catch(()=>{Ie||g("Failed to resume session.")}),()=>{Ie=!0}},[Ne,e,u,d.type]),a.useEffect(()=>{e||(C(!1),I(null))},[e]),a.useEffect(()=>{if(!(!e||!_)){if($.current!==_){$.current&&T($.current,O),D(_,O),$.current=_;return}!_&&$.current&&(T($.current,O),$.current=null)}},[D,T,e,_,O]),a.useEffect(()=>{if(!e||!_||$.current!==_)return;w(O);const Ie=setInterval(()=>{w(O)},3e4);return()=>{clearInterval(Ie)}},[w,e,_,O]),a.useEffect(()=>()=>{F.current?.close(),F.current=null,$.current&&(T($.current,O),$.current=null)},[T,O]);const ve=a.useCallback(()=>{F.current?.close(),F.current=null,n()},[n]),ee=a.useCallback(async()=>{F.current?.close(),F.current=null,ne(),m({type:"initial"}),g(null),W.current=null,I(null),n()},[n]),Ee=a.useCallback(async Ie=>{if(d.type!=="question")return;const{sessionId:Ge}=d;g(null),f(se=>[...se,Ie]),v(se=>[...se,{question:d.question,response:Ie}]),m({type:"loading"}),k("");try{Ne(Ge),await G(Ge,Ie,c,O)}catch(se){F.current?.close(),F.current=null,g(ke(se)||"Failed to submit response"),m({type:"question",sessionId:Ge,question:d.question})}},[Ne,c,G,O,d]),Fe=a.useCallback(async()=>{if(d.type==="summary"){g(null),A(!0);try{await ce(d.sessionId,b||void 0,c),s(),m({type:"applied"})}catch(Ie){g(ke(Ie)||"Failed to apply interview results"),A(!1)}}},[ce,b,s,c,d]),Ke=()=>d.type==="question"?Math.min(p.length+1,6):6,Ze=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",Xe=_?J.get(_):null,it=!!(Xe&&Xe.tabId!==O&&!Xe.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Ie=>Ie.target===Ie.currentTarget&&ee(),role:"dialog","aria-modal":"true","data-testid":"milestone-slice-interview-modal",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(qn,{size:20,className:"icon-triage"}),t.jsxs("h3",{children:["Plan ",pe,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[Ze&&t.jsx("button",{className:"modal-send-to-background",onClick:ve,title:"Send to background","aria-label":"Send to background",children:t.jsx(yr,{size:16})}),t.jsx("button",{className:"modal-close",onClick:ee,"aria-label":"Close",children:t.jsx(Ot,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[h&&t.jsx("div",{className:"form-error planning-error",children:h}),M&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),it&&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.jsx("div",{className:"planning-view-scroll",children:t.jsxs("div",{className:"planning-intro",children:[t.jsx(qn,{size:32,className:"icon-triage-lg"}),t.jsxs("h4",{children:["Refine ",pe," scope with AI"]}),t.jsxs("p",{className:"text-muted",children:["The AI will interview you to refine the ",i,"'s scope, acceptance criteria, and verification methods. Each ",i," 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 xe(),children:[t.jsx(qn,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void le(),disabled:z,children:[z?t.jsx(ot,{size:16,className:"spin"}):null,"Use Mission Context"]}),t.jsx("button",{className:"btn",onClick:ee,children:"Cancel"})]})]}),d.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(ot,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:S?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>N(!R),type:"button",children:R?"Hide thinking":"Show thinking"}),R&&S&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:S})})]})]}),d.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[x.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Es,{entries:x}),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.jsx("div",{className:"ai-error-actions",children:t.jsx("button",{className:"btn",onClick:ee,children:"Cancel"})})]})]})}),d.type==="question"&&t.jsx(x1,{question:d.question,progress:Ke(),historyEntries:x,onSubmit:Ee}),d.type==="summary"&&b&&t.jsx(b1,{summary:b,historyEntries:x,onSummaryChange:y,onApply:Fe,onCancel:ee,isApplying:z}),d.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(dn,{size:48,className:"icon-success"}),t.jsxs("h4",{children:[pe," Updated"]}),t.jsxs("p",{className:"text-muted",children:["The ",i,"'s scope and verification have been ",d.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 x1({question:e,progress:n,historyEntries:s,onSubmit:i}){const[r,o]=a.useState({}),[l,c]=a.useState(""),u=a.useCallback(()=>{e.type==="text"?i({[e.id]:l}):e.type==="confirm"?i({[e.id]:r[e.id]===!0}):i(r)},[e,r,l,i]);a.useEffect(()=>{o({}),c("")},[e.id]);const d=()=>{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(Es,{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(m=>t.jsx("div",{className:`planning-progress-step ${m<=n?"active":""}`},m))}),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:m=>c(m.target.value),onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&l.trim()&&(m.preventDefault(),u())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(m=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:m.id,checked:r[e.id]===m.id,onChange:()=>o({[e.id]:m.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(m=>{const h=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:m.id,checked:h.includes(m.id),onChange:g=>{const p=g.target.checked?[...h,m.id]:h.filter(f=>f!==m.id);o({[e.id]:p})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.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(dn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Ot,{size:18}),"No"]})]})]})]})]})]}),t.jsx("div",{className:"planning-actions",children:t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:u,disabled:!d(),children:["Continue",t.jsx(br,{size:16,className:"icon-ml-4"})]})})]})}function b1({summary:e,historyEntries:n,onSummaryChange:s,onApply:i,onCancel:r,isApplying:o}){const[l,c]=a.useState(e),[u,d]=a.useState(!0),m=(h,g)=>{const p={...l,[h]:g};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(Es,{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:()=>d(!u),"aria-expanded":u,children:[u?t.jsx(qt,{size:16}):t.jsx(hn,{size:16}),t.jsx("span",{children:"Refined Scope"})]})}),u&&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:i,disabled:o,children:[o?t.jsx(ot,{size:16,className:"spin"}):null,"Apply"]}),t.jsx("button",{className:"btn",onClick:r,disabled:o,children:"Cancel"})]})]})}const La={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)"}},zu={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)"}},Fu={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)"}},Hr={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)"}},qr={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)"}},Vr={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)"}},Ou={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)"}},v1=3;function y1(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function Uu({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 Bu(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const vl={title:"",description:"",status:"planning",autopilotEnabled:!1},yl={title:"",description:"",status:"planning",dependencies:[]},kl={title:"",description:"",status:"pending"},jl={title:"",description:"",acceptanceCriteria:"",status:"defined"},k1=3600*1e3;function ko(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 i=Math.floor(s/(60*1e3));if(i<1)return"just now";if(i<60)return`${i}m ago`;const r=Math.floor(i/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function j1(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=k1,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 w1(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 N1(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 wl(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 Tp=["feature_triaged","feature_completed"],Pp=["slice_activated","slice_completed","milestone_completed"],Ip=["mission_started","mission_paused","mission_resumed","mission_completed"],$p=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function Hu(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return Ip.includes(e);case"tasks":return Tp.includes(e);case"slices":return Pp.includes(e);case"autopilot":return $p.includes(e);default:return!0}}function S1(e){return e==="error"||e==="warning"?"mission-event__type--error":Ip.includes(e)?"mission-event__type--state":Tp.includes(e)?"mission-event__type--task":Pp.includes(e)?"mission-event__type--slice":$p.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function C1(e){return e.replace(/_/g," ")}function E1(e,n){return n?e==="watching"?`Watching since ${ko(n)}`:`Last activation ${ko(n)}`:null}function _1({isOpen:e,isInline:n=!1,onClose:s,addToast:i,projectId:r,onSelectTask:o,availableTasks:l=[],resumeSessionId:c,targetMissionId:u,milestoneSliceResumeSessionId:d,onMilestoneSliceResumeFetchError:m}){const h=n||e,[g,p]=a.useState([]),[f,x]=a.useState(null),[v,b]=a.useState(!0),[y,S]=a.useState(!1),[k,R]=a.useState(!1),[N,M]=a.useState(null),[C,z]=a.useState(vl),[A,P]=a.useState(!1),[F,W]=a.useState(new Set),[$,_]=a.useState(new Set),[I,O]=a.useState(null),[J,Q]=a.useState(yl),[E,D]=a.useState(!1),[T,w]=a.useState(null),[q,G]=a.useState(kl),[me,ce]=a.useState(!1),[ae,pe]=a.useState(null),[U,Ne]=a.useState(null),[ne,xe]=a.useState(jl),[le,ve]=a.useState(!1),[ee,Ee]=a.useState(null),[Fe,Ke]=a.useState(null),[Ze,Xe]=a.useState(""),[Qe,it]=a.useState(!1),[Ie,Ge]=a.useState([]),[se,ye]=a.useState(void 0),Z=se??c,[Te,ze]=a.useState(null),[be,Me]=a.useState(null),[Be,lt]=a.useState(null);a.useEffect(()=>{h&&Z&&it(!0)},[h,Z]),a.useEffect(()=>{if(!h||Z)return;let H=!1;return Zc(r).then(Ce=>{if(H)return;const Le=Ce.filter(ht=>ht.type==="mission_interview"&&(ht.status==="awaiting_input"||ht.status==="error"));Ge(Le)}).catch(Ce=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",Ce)}),()=>{H=!0}},[h,r,Z]),a.useEffect(()=>{if(!h||!d)return;let H=!1;return oi(d).then(Ce=>{if(!(H||!Ce))try{const Le=JSON.parse(Ce.inputPayload||"{}");Le.targetId&&Le.targetType&&ze({type:Le.targetType,id:Le.targetId,title:Le.targetTitle||Ce.title,resumeSessionId:d})}catch{ze({type:"milestone",id:"",title:Ce.title,resumeSessionId:d})}}).catch(Ce=>{H||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",Ce),m?.())}),()=>{H=!0}},[h,d,m]);const[je,ie]=a.useState(null),[Ae,he]=a.useState(new Map),[Re,Je]=a.useState(null),[$e,de]=a.useState({title:"",assertion:"",status:"pending"}),[re,ue]=a.useState(!1),[Pe,Se]=a.useState(null),[fe,tt]=a.useState(new Map),[ut,vt]=a.useState(new Set),[gt,dt]=a.useState(new Set),[wt,Mt]=a.useState(null),[yt,Et]=a.useState(new Map),[Nt,Tt]=a.useState(null),[Ht,Ut]=a.useState(null),[Vt,zt]=a.useState(!0),[Ct,At]=a.useState(new Set),[kt,Kt]=a.useState(new Map),[$t,B]=a.useState(null),[ge,te]=a.useState(new Map),[j,V]=a.useState(null),[De,nt]=a.useState(new Map),[St,Pt]=a.useState(new Map),[Rt,un]=a.useState("structure"),[mn,wn]=a.useState([]),Gt=a.useRef([]),es=a.useRef([]),we=a.useRef(null),rt=a.useRef(null),Jt=a.useRef("structure"),Sn=a.useRef("all"),[Cn,pn]=a.useState(!1),[bn,Rn]=a.useState(0),[vn,Y]=a.useState("all"),[Oe,Ye]=a.useState(new Set),st=a.useRef(null),pt=a.useRef(null);es.current=g,we.current=f,rt.current=Nt,Jt.current=Rt,Sn.current=vn;const jt=a.useCallback((H="auto")=>{const Ce=pt.current;if(Ce&&typeof Ce.scrollIntoView=="function"){Ce.scrollIntoView({block:"end",behavior:H});return}const Le=st.current;Le&&(Le.scrollTop=Le.scrollHeight)},[]),_t=a.useCallback(()=>{const H=st.current;return H?H.scrollHeight-H.scrollTop-H.clientHeight<=100:!0},[]),yn=a.useCallback(async H=>{if(H.length===0){Pt(new Map);return}const Ce=await qk(r);Pt(Le=>{const ht=new Map(Le);for(const[on,Dt]of Object.entries(Ce))w1(Dt)&&ht.set(on,Dt);return ht})},[r]),en=a.useCallback(async()=>{try{b(!0);const H=await Fk(r);p(H),yn(H)}catch(H){i(ke(H)||"Failed to load missions","error")}finally{b(!1)}},[i,r,yn]),xt=a.useCallback(async H=>{try{S(!0);const Ce=await cp(H,r);if(x(Ce),Ce.milestones.length>0){const Le=Ce.milestones[0].id;Tt(Le),zt(!0),W(new Set([Le])),ol(Le,r).then(ht=>{he(on=>{const Dt=new Map(on);return Dt.set(Le,ht),Dt})}).catch(()=>{}),ll(Le,r).then(ht=>{Et(on=>{const Dt=new Map(on);return Dt.set(Le,ht),Dt})}).catch(()=>{}),Ce.milestones[0].slices.length>0&&_(new Set([Ce.milestones[0].slices[0].id]))}else Tt(null),Ut(null)}catch(Ce){i(ke(Ce)||"Failed to load mission details","error")}finally{S(!1)}},[i,r]);a.useEffect(()=>{if(!h||!Nt){Ut(null);return}let H=!1;return Ut(null),Yd(Nt,r).then(Ce=>{if(!H){if(!wl(Ce)){Ut(null);return}Ut(Ce),Et(Le=>{const ht=new Map(Le);return ht.set(Nt,Ce.rollup),ht})}}).catch(()=>{H||Ut(null)}),()=>{H=!0}},[h,Nt,r]),a.useEffect(()=>{zt(!0)},[Nt]);const ts=a.useCallback(H=>{!H||H!==rt.current||Yd(H,r).then(Ce=>{rt.current!==H||!wl(Ce)||(Ut(Ce),Et(Le=>{const ht=new Map(Le);return ht.set(H,Ce.rollup),ht}))}).catch(()=>{})},[r]),ns=a.useCallback(async(H,Ce)=>{const Le=Ce?.append??!1,ht=Le?Gt.current.length:0;Le||(pn(!0),Ye(new Set));try{const on=await Hk(H,{limit:50,offset:ht,eventType:void 0},r),Dt=on.events.filter(Qt=>Hu(Qt.eventType,vn));wn(Qt=>{if(!Le)return Dt;const qe=new Set(Qt.map(ft=>ft.id)),Ve=[...Qt];for(const ft of Dt)qe.has(ft.id)||Ve.push(ft);return Ve}),Rn(on.total),Le||requestAnimationFrame(()=>{jt("auto")})}catch(on){i(ke(on)||"Failed to load mission activity","error")}finally{Le||pn(!1)}},[i,vn,r,jt]);a.useEffect(()=>{Gt.current=mn},[mn]),a.useEffect(()=>{h&&(en(),x(null),Tt(null),Ut(null),wn([]),Rn(0),un("structure"),Y("all"),Ye(new Set))},[h,en]);const ss=a.useRef(null);a.useEffect(()=>{h&&u&&ss.current!==u&&g.length>0&&(ss.current=u,xt(u))},[h,u,g,xt]),a.useEffect(()=>{h||(ss.current=null)},[h]),a.useEffect(()=>{!h||!f||Rt!=="activity"||ns(f.id)},[Rt,h,ns,f,vn]),a.useEffect(()=>{if(!h||typeof EventSource>"u")return;const H=new URLSearchParams;r&&H.set("projectId",r);const Ce=`/api/events${H.size>0?`?${H.toString()}`:""}`,Le=()=>{yn(es.current)},ht=Fn=>{Le();const jn=Fn;if(jn.data)try{const Ft=JSON.parse(jn.data);Ft?.id&&p(Ri=>Ri.map(ks=>ks.id===Ft.id?{...ks,...Ft}:ks))}catch{}we.current&&xt(we.current.id)},on=Fn=>{Le(),we.current&&xt(we.current.id)},Dt=()=>{Le(),we.current&&xt(we.current.id)},Qt=Fn=>{Le(),we.current&&xt(we.current.id)},qe=Fn=>{const jn=Fn;if(jn.data)try{const Ft=JSON.parse(jn.data);Ft&&Ft.featureId&&(Os(Ft.featureId),ti(Ft.featureId),Ft.milestoneId&&ts(Ft.milestoneId))}catch{}},Ve=Fn=>{const jn=Fn;if(jn.data)try{const Ft=JSON.parse(jn.data);Ft&&Ft.featureId&&(Os(Ft.featureId),ti(Ft.featureId),Ft.milestoneId&&ts(Ft.milestoneId),we.current&&xt(we.current.id))}catch{}},ft=Fn=>{const jn=Fn;if(jn.data)try{const Ft=JSON.parse(jn.data);Ft&&Ft.milestoneId&&(mi(Ft.milestoneId),ts(Ft.milestoneId))}catch{}},ln=Fn=>{const jn=Fn;if(jn.data)try{const Ft=JSON.parse(jn.data);Ft&&Ft.milestoneId&&(_i(Ft.milestoneId),mi(Ft.milestoneId),ts(Ft.milestoneId))}catch{}};return Ls(Ce,{events:{"mission:updated":ht,"slice:updated":on,"feature:updated":Dt,"milestone:updated":Qt,"mission:event":Fn=>{Le();const jn=we.current;if(!jn||Jt.current!=="activity")return;const Ft=_t(),Ri=Fn;if(Ri.data)try{const ks=JSON.parse(Ri.data);if(!N1(ks)||ks.missionId!==jn.id||!Hu(ks.eventType,Sn.current))return;wn(ii=>{const nl=ii.filter(sl=>sl.id!==ks.id);return[ks,...nl].slice(0,100)}),Rn(ii=>ii+1),Ft&&requestAnimationFrame(()=>{const ii=st.current;ii&&(ii.scrollTop=0)})}catch{}},"validator-run:started":qe,"validator-run:completed":Ve,"milestone:validation:updated":ft,"assertion:created":ln,"assertion:updated":ln,"assertion:deleted":ln,"assertion:linked":ln,"assertion:unlinked":ln,"fix-feature:created":Fn=>{const jn=Fn;if(jn.data)try{const Ft=JSON.parse(jn.data);if(Ft&&Ft.sourceFeatureId){Os(Ft.sourceFeatureId);const Ri=Ft?.feature?.sliceId,ks=we.current;if(Ri&&ks){const ii=ks.milestones.find(nl=>nl.slices.some(sl=>sl.id===Ri));ii&&ts(ii.id)}we.current&&xt(we.current.id)}}catch{}}}})},[h,_t,xt,yn,r,ts]);const Si=a.useCallback(()=>{R(!0),M(null),z(vl)},[]),oe=a.useCallback(H=>{M(H.id),R(!1),z({title:H.title,description:H.description||"",status:H.status,autopilotEnabled:H.autopilotEnabled??!1})},[]),_e=a.useCallback(()=>{M(null),R(!1),z(vl)},[]),at=a.useCallback(async()=>{if(!C.title.trim()){i("Mission title is required","error");return}try{if(P(!0),k)await Ok({title:C.title.trim(),description:C.description.trim()||void 0,autopilotEnabled:C.autopilotEnabled},r),i("Mission created","success");else if(N){const H={title:C.title.trim(),description:C.description.trim()||void 0,status:C.status,autopilotEnabled:C.autopilotEnabled};C.autopilotEnabled&&(H.autoAdvance=!0),await Uk(N,H,r),i("Mission updated","success"),f?.id===N&&await xt(N)}await en(),_e()}catch(H){i(ke(H)||"Failed to save mission","error")}finally{P(!1)}},[C,k,N,i,en,xt,f,_e,r]),We=a.useCallback(async H=>{try{await Bk(H,r),i("Mission deleted","success"),f?.id===H&&x(null),await en(),ie(null)}catch(Ce){i(ke(Ce)||"Failed to delete mission","error")}},[i,en,f,r]),mt=a.useCallback(()=>{D(!0),O(null),Q(yl)},[]),fn=a.useCallback(H=>{O(H.id),D(!1),Q({title:H.title,description:H.description||"",status:H.status,dependencies:H.dependencies})},[]),Yt=a.useCallback(()=>{O(null),D(!1),Q(yl)},[]),tn=a.useCallback(async()=>{if(!J.title.trim()){i("Milestone title is required","error");return}try{P(!0),E&&f?(await Vk(f.id,{title:J.title.trim(),description:J.description.trim()||void 0,dependencies:J.dependencies},r),i("Milestone created","success")):I&&(await Wk(I,{title:J.title.trim(),description:J.description.trim()||void 0,status:J.status,dependencies:J.dependencies},r),i("Milestone updated","success")),await xt(f.id),Yt()}catch(H){i(ke(H)||"Failed to save milestone","error")}finally{P(!1)}},[J,E,I,f,i,xt,Yt,C.title,r]),rn=a.useCallback(async H=>{try{await Kk(H,r),i("Milestone deleted","success"),await xt(f.id),ie(null)}catch(Ce){i(ke(Ce)||"Failed to delete milestone","error")}},[i,xt,f,r]),On=a.useCallback(H=>{Tt(H),zt(!0),W(Ce=>{const Le=new Set(Ce);return!Le.has(H)?(Le.add(H),ol(H,r).then(on=>{he(Dt=>{const Qt=new Map(Dt);return Qt.set(H,on),Qt})}).catch(()=>{}),ll(H,r).then(on=>{Et(Dt=>{const Qt=new Map(Dt);return Qt.set(H,on),Qt})}).catch(()=>{})):Le.delete(H),Le})},[r]),Un=a.useCallback(H=>{pe(H),ce(!0),w(null),G(kl)},[]),xs=a.useCallback(H=>{w(H.id),ce(!1),G({title:H.title,description:H.description||"",status:H.status})},[]),kn=a.useCallback(()=>{w(null),ce(!1),pe(null),G(kl)},[]),Ln=a.useCallback(async()=>{if(!q.title.trim()){i("Slice title is required","error");return}try{P(!0),me&&ae?(await Gk(ae,{title:q.title.trim(),description:q.description.trim()||void 0},r),i("Slice created","success")):T&&(await Jk(T,{title:q.title.trim(),description:q.description.trim()||void 0,status:q.status},r),i("Slice updated","success")),await xt(f.id),kn()}catch(H){i(ke(H)||"Failed to save slice","error")}finally{P(!1)}},[q,me,T,ae,f,i,xt,kn,r]),Wn=a.useCallback(async H=>{try{await Yk(H,r),i("Slice deleted","success"),await xt(f.id),ie(null)}catch(Ce){i(ke(Ce)||"Failed to delete slice","error")}},[i,xt,f,r]),_s=a.useCallback(async H=>{try{await Qk(H,r),i("Slice activated","success"),await xt(f.id)}catch(Ce){i(ke(Ce)||"Failed to activate slice","error")}},[i,xt,f,r]),zn=a.useCallback(H=>{_(Ce=>{const Le=new Set(Ce);return Le.has(H)?Le.delete(H):Le.add(H),Le})},[]),is=a.useCallback(H=>{Ee(H),ve(!0),Ne(null),xe(jl)},[]),Ms=a.useCallback(H=>{Ne(H.id),ve(!1),xe({title:H.title,description:H.description||"",acceptanceCriteria:H.acceptanceCriteria||"",status:H.status})},[]),bs=a.useCallback(()=>{Ne(null),ve(!1),Ee(null),xe(jl)},[]),Kn=a.useCallback(async()=>{if(!ne.title.trim()){i("Feature title is required","error");return}try{P(!0),le&&ee?(await Xk(ee,{title:ne.title.trim(),description:ne.description.trim()||void 0,acceptanceCriteria:ne.acceptanceCriteria.trim()||void 0},r),i("Feature created","success")):U&&(await Zk(U,{title:ne.title.trim(),description:ne.description.trim()||void 0,acceptanceCriteria:ne.acceptanceCriteria.trim()||void 0,status:ne.status},r),i("Feature updated","success")),await xt(f.id),bs()}catch(H){i(ke(H)||"Failed to save feature","error")}finally{P(!1)}},[ne,le,U,ee,f,i,xt,bs,r]),Gn=a.useCallback(async H=>{try{await ej(H,r),i("Feature deleted","success"),await xt(f.id),ie(null)}catch(Ce){i(ke(Ce)||"Failed to delete feature","error")}},[i,xt,f,r]),ei=a.useCallback(async()=>{if(!Fe||!Ze.trim()){i("Task ID is required","error");return}try{await tj(Fe,Ze.trim(),r),i("Feature linked to task","success"),await xt(f.id),Ke(null),Xe("")}catch(H){i(ke(H)||"Failed to link feature to task","error")}},[Fe,Ze,i,xt,f,r]),zs=a.useCallback(async H=>{try{await nj(H,r),i("Feature unlinked from task","success"),await xt(f.id)}catch(Ce){i(ke(Ce)||"Failed to unlink feature","error")}},[i,xt,f,r]),Ci=a.useCallback(async H=>{try{P(!0),await sj(H,void 0,void 0,r),i("Feature triaged — task created","success"),await xt(f.id)}catch(Ce){i(ke(Ce)||"Failed to triage feature","error")}finally{P(!1)}},[i,xt,f,r]),Ar=a.useCallback(async H=>{lt(H);try{const Ce=await Tj(H,r);Me({featureId:H,enrichedDescription:Ce.description})}catch{await Ci(H)}finally{lt(null)}},[Ci,r]),Yo=a.useCallback(async()=>{be&&(Me(null),await Ci(be.featureId))},[Ci,be]),Ei=a.useCallback(()=>{Me(null)},[]),_a=a.useCallback(async H=>{try{P(!0);const Ce=await ij(H,r);i(`Triaged ${Ce.count} feature${Ce.count!==1?"s":""}`,"success"),await xt(f.id)}catch(Ce){i(ke(Ce)||"Failed to triage slice features","error")}finally{P(!1)}},[i,xt,f,r]),_i=a.useCallback(async H=>{try{const Ce=await ol(H,r);he(Le=>{const ht=new Map(Le);return ht.set(H,Ce),ht})}catch{}},[r]),mi=a.useCallback(async H=>{try{const Ce=await ll(H,r);Et(Le=>{const ht=new Map(Le);return ht.set(H,Ce),ht})}catch{}},[r]),Rr=a.useCallback(async H=>{if(!$e.title.trim()||!$e.assertion.trim()){i("Title and assertion text are required","error");return}try{P(!0),await aj(H,{title:$e.title.trim(),assertion:$e.assertion.trim(),status:$e.status},r),i("Assertion created","success"),await _i(H),await mi(H),ue(!1),de({title:"",assertion:"",status:"pending"})}catch(Ce){i(ke(Ce)||"Failed to create assertion","error")}finally{P(!1)}},[$e,i,_i,mi,r]),Tr=a.useCallback(H=>{Je(H.id),de({title:H.title,assertion:H.assertion,status:H.status})},[]),Mi=a.useCallback(()=>{Je(null),ue(!1),de({title:"",assertion:"",status:"pending"})},[]),Qo=a.useCallback(async(H,Ce)=>{if(!$e.title.trim()||!$e.assertion.trim()){i("Title and assertion text are required","error");return}try{P(!0),await rj(H,{title:$e.title.trim(),assertion:$e.assertion.trim(),status:$e.status},r),i("Assertion updated","success"),await _i(Ce),await mi(Ce),Mi()}catch(Le){i(ke(Le)||"Failed to update assertion","error")}finally{P(!1)}},[$e,i,_i,mi,Mi,r]),Fs=a.useCallback(async H=>{try{const Ce=await cj(H,r);tt(Le=>{const ht=new Map(Le);return ht.set(H,Ce),ht})}catch{}},[r]),Ma=a.useCallback(async H=>{const Ce=Pe!==H;Se(Le=>Le===H?null:H),Ce&&await Fs(H)},[Pe,Fs]),Tn=a.useCallback(H=>{Se(H),Fs(H),requestAnimationFrame(()=>{const Ce=document.querySelector(`[data-mission-assertion-id="${H}"]`);Ce instanceof HTMLElement&&typeof Ce.scrollIntoView=="function"&&Ce.scrollIntoView({behavior:"smooth",block:"center"})})},[Fs]),Aa=a.useCallback(async(H,Ce)=>{try{vt(Le=>new Set(Le).add(Ce)),await oj(H,Ce,r),i("Feature linked to assertion","success"),await Fs(Ce),Mt(null)}catch(Le){i(ke(Le)||"Failed to link feature","error")}finally{vt(Le=>{const ht=new Set(Le);return ht.delete(Ce),ht})}},[i,Fs,r]),as=a.useCallback(async(H,Ce)=>{const Le=`${H}-${Ce}`;try{dt(ht=>new Set(ht).add(Le)),await lj(H,Ce,r),i("Feature unlinked from assertion","success"),await Fs(Ce)}catch(ht){i(ke(ht)||"Failed to unlink feature","error")}finally{dt(ht=>{const on=new Set(ht);return on.delete(Le),on})}},[i,Fs,r]),Pr=a.useCallback(async H=>{try{At(Le=>new Set(Le).add(H)),await dj(H,r),i("Validation triggered","success");const Ce=await Qd(H,r);Kt(Le=>{const ht=new Map(Le);return ht.set(H,Ce),ht})}catch(Ce){i(ke(Ce)||"Failed to trigger validation","error")}finally{At(Ce=>{const Le=new Set(Ce);return Le.delete(H),Le})}},[i,r]),Os=a.useCallback(async H=>{try{const Ce=await Qd(H,r);Kt(Le=>{const ht=new Map(Le);return ht.set(H,Ce),ht})}catch{}},[r]),ti=a.useCallback(async H=>{try{const Ce=await uj(H,{limit:10},r);te(Le=>{const ht=new Map(Le);return ht.set(H,Ce),ht})}catch{}},[r]),ni=a.useCallback(H=>{const Ce=we.current;if(Ce){for(const Le of Ce.milestones)for(const ht of Le.slices)if(ht.features.find(Dt=>Dt.id===H)){W(Dt=>{const Qt=new Set(Dt);return Qt.add(Le.id),Qt}),_(Dt=>{const Qt=new Set(Dt);return Qt.add(ht.id),Qt}),B(H),Tt(Le.id),Os(H),ti(H),requestAnimationFrame(()=>{const Dt=document.querySelector(`[data-mission-feature-id="${H}"]`);Dt instanceof HTMLElement&&typeof Dt.scrollIntoView=="function"&&Dt.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[Os,ti]),Ir=a.useCallback(async H=>{try{const Ce=await mj(H,r);nt(Le=>{const ht=new Map(Le);return ht.set(H,Ce),ht})}catch{}},[r]),$r=a.useCallback(async H=>{$t===H?B(null):(B(H),await Os(H),await ti(H))},[$t,Os,ti]),X=a.useCallback(async H=>{j===H?V(null):(V(H),await Ir(H))},[j,Ir]),He=a.useCallback(async H=>{try{await hj(H,r),i("Mission resumed","success"),await xt(H),en()}catch(Ce){i(ke(Ce)||"Failed to resume mission","error")}},[i,xt,en,r]),ct=a.useCallback(async H=>{try{const Le=(await pj(H,r)).pausedTaskIds?.length??0;i(`Mission stopped (${Le} task${Le!==1?"s":""} paused)`,"success"),await xt(H),en()}catch(Ce){i(ke(Ce)||"Failed to stop mission","error")}},[i,xt,en,r]),It=a.useCallback(async H=>{try{await fj(H,r),i("Mission started — first slice activated","success"),await xt(H),en()}catch(Ce){i(ke(Ce)||"Failed to start mission","error")}},[i,xt,en,r]),Us=a.useCallback(async(H,Ce)=>{try{await gj(H,{enabled:Ce},r),i(Ce?"Autopilot enabled":"Autopilot disabled","success"),await xt(H),en()}catch(Le){i(ke(Le)||"Failed to update autopilot","error")}},[i,xt,en,r]),vs=a.useCallback(H=>{un("structure"),Tt(null),Ut(null),wn([]),Rn(0),Y("all"),Ye(new Set),xt(H.id)},[xt]),Xo=a.useCallback(()=>{x(null),Tt(null),Ut(null),un("structure"),wn([]),Rn(0),Y("all"),Ye(new Set),en()},[en]),Gi=mn.length<bn,hi=f?.autopilotState??"inactive",Dr=hi==="watching"||hi==="activating",Lr=E1(hi,f?.lastAutopilotActivityAt),Ji=a.useMemo(()=>!Ht||!Nt||!wl(Ht)?null:Ht.rollup.milestoneId===Nt?Ht:null,[Nt,Ht]),Zo=a.useMemo(()=>{const H=new Map;for(const Ce of Ji?.validationTelemetry.validationRounds??[]){const Le=H.get(Ce.featureId);(!Le||Ce.startedAt>Le.startedAt)&&H.set(Ce.featureId,Ce)}return H},[Ji]),Ra=a.useCallback(()=>{!f||Cn||!Gi||ns(f.id,{append:!0})},[Cn,Gi,ns,f]),Ta=a.useCallback(H=>{Ye(Ce=>{const Le=new Set(Ce);return Le.has(H)?Le.delete(H):Le.add(H),Le})},[]),pi=a.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),at())},[at]),Yi=a.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),tn())},[tn]),el=a.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),Ln())},[Ln]),tl=a.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),Kn())},[Kn]),As=a.useRef(null);if(a.useEffect(()=>{if(!h)return;const H=Ce=>{Ce.key==="Escape"&&s()};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[h,s]),!h)return null;const si=t.jsxs("div",{ref:As,className:`mission-manager${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:[f?t.jsx("button",{className:"mission-manager__back-btn",onClick:Xo,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(Ao,{size:18})}):null,t.jsx(ls,{size:18,className:"mission-manager__header-icon"}),t.jsx("h2",{className:"mission-manager__title",children:f?f.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(Ot,{size:18})})]}),t.jsx("div",{className:"mission-manager__body",children:v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(ot,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(ot,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):f?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:[Dr&&t.jsx("span",{className:"mission-detail__autopilot-dot",title:"Autopilot watching"}),t.jsx("h3",{className:"mission-detail__title",children:f.title})]}),t.jsx("span",{className:"mission-status-badge",style:{backgroundColor:(La[f.status]||La.planning).bg,color:(La[f.status]||La.planning).text},children:f.status})]}),f.description&&t.jsx("p",{className:"mission-detail__description",children:f.description}),t.jsx("div",{className:"mission-detail__meta",children:t.jsxs("span",{className:"mission-detail__meta-info",children:[f.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:f.autopilotEnabled??!1,onChange:H=>Us(f.id,H.target.checked),"aria-label":"Autopilot"}),t.jsx("span",{className:"mission-toggle__track","aria-hidden":"true",children:t.jsx("span",{className:"mission-toggle__thumb"})}),t.jsxs("span",{className:"mission-toggle__label",children:[t.jsx(Pn,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),t.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(qr[hi]||qr.inactive).bg,color:(qr[hi]||qr.inactive).text},"data-testid":"autopilot-state-badge",children:[Dr&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),hi]})]}),Lr&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:Lr})]}),t.jsxs("div",{className:"mission-detail__actions",children:[f.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ct(f.id),title:"Stop mission","aria-label":"Stop mission",children:t.jsx(ms,{size:14})}),f.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>He(f.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(xn,{size:14})}),f.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>It(f.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(xn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>oe(f),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(Yn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ie({type:"mission",id:f.id}),title:"Delete mission","aria-label":"Delete mission",children:t.jsx(Xt,{size:14})})]})]}),N===f.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:C.title,onChange:H=>z({...C,title:H.target.value}),onKeyDown:pi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:C.description,onChange:H=>z({...C,description:H.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:C.status,onChange:H=>z({...C,status:H.target.value}),children:[t.jsx("option",{value:"planning",children:"Planning"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"blocked",children:"Blocked"}),t.jsx("option",{value:"complete",children:"Complete"}),t.jsx("option",{value:"archived",children:"Archived"})]}),t.jsxs("label",{className:"mission-checkbox",children:[t.jsx("input",{type:"checkbox",checked:C.autopilotEnabled,onChange:H=>z({...C,autopilotEnabled:H.target.checked})}),t.jsx(Pn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:at,disabled:A,children:[A?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Mn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:_e,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[t.jsx("button",{className:`mission-btn ${Rt==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>un("structure"),role:"tab","aria-selected":Rt==="structure","data-testid":"mission-tab-structure",children:"Structure"}),t.jsxs("button",{className:`mission-btn ${Rt==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>un("activity"),role:"tab","aria-selected":Rt==="activity","data-testid":"mission-tab-activity",children:["Activity (",bn,")"]})]}),Rt==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[f.milestones.map(H=>{const Ce=Ji?.rollup.milestoneId===H.id?Ji:null,Le=Ce?.rollup??yt.get(H.id),ht=Ce?.validationTelemetry.validationRounds??[],on=Ce?.fixFeatures??[],Dt=Ou[Le?.state??"not_started"]??Ou.not_started,Qt=Le&&(Le.state==="blocked"||Le.state==="failed")?Ce?.validationTelemetry.validationRounds.find(qe=>qe.blockedReason)?.blockedReason:void 0;return t.jsxs("div",{className:"mission-milestone",children:[t.jsxs("div",{className:"mission-milestone__header",onClick:()=>On(H.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:F.has(H.id)?t.jsx(qt,{size:16}):t.jsx(hn,{size:16})}),t.jsx(Ui,{size:16,className:"mission-milestone__icon"}),t.jsx("span",{className:"mission-milestone__title",children:H.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:zu[H.status].bg,color:zu[H.status].text},children:H.status}),t.jsxs("span",{className:"mission-milestone__count",children:[H.slices.length," slices"]}),t.jsx(Uu,{state:y1(H.interviewState)}),Le&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Dt.bg,color:Dt.text},title:"Validation state",children:Bu(Le.state)}),Le.totalAssertions>0&&t.jsx("div",{className:"mission-milestone__coverage-bar",title:`${Le.passedAssertions??0} of ${Le.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${(Le.passedAssertions??0)/Le.totalAssertions*100}%`,backgroundColor:(Le.passedAssertions??0)===Le.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),H.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>ze({type:"milestone",id:H.id,title:H.title}),title:"Plan milestone","aria-label":"Plan milestone",children:t.jsx(Oi,{size:14})}),t.jsxs("div",{className:"mission-milestone__actions",onClick:qe=>qe.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>Un(H.id),title:"Add slice",children:t.jsx(Zt,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>fn(H),title:"Edit milestone",children:t.jsx(Yn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ie({type:"milestone",id:H.id}),title:"Delete milestone",children:t.jsx(Xt,{size:14})})]})]}),F.has(H.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(E||I===H.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:J.title,onChange:qe=>Q({...J,title:qe.target.value}),onKeyDown:Yi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:J.description,onChange:qe=>Q({...J,description:qe.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:tn,disabled:A,children:[A?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Mn,{size:14}),I?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Yt,children:"Cancel"})]})]}),Ce&&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:[Ce.validationTelemetry.totalRuns," rounds",Ce.validationTelemetry.lastValidatorStatus?` · Last ${Ce.validationTelemetry.lastValidatorStatus}`:""]})]}),Qt&&t.jsxs("div",{className:"mission-blocked-reason",children:[t.jsx("strong",{children:"Blocked reason:"})," ",Qt]}),ht.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:()=>zt(qe=>!qe),title:Vt?"Hide validation rounds":"Show validation rounds",children:[Vt?t.jsx(qt,{size:12}):t.jsx(hn,{size:12}),"Validation rounds (",ht.length,")"]}),Vt&&t.jsx("div",{className:"mission-validation-rounds__list",children:ht.map(qe=>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--${qe.validatorStatus}`,children:qe.validatorStatus}),t.jsx("span",{className:"mission-validation-round__feature",children:qe.featureTitle}),t.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",qe.implementationAttempt," · reviewer #",qe.validatorAttempt]})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),qe.failedAssertionIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:qe.failedAssertionIds.map(Ve=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Tn(Ve),title:`Jump to assertion ${Ve}`,children:Ve},`${qe.roundId}-${Ve}`))}):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:"}),qe.generatedFixFeatureIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:qe.generatedFixFeatureIds.map(Ve=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ni(Ve),title:`Jump to fix feature ${Ve}`,children:Ve},`${qe.roundId}-${Ve}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),qe.blockedReason&&t.jsx("div",{className:"mission-validation-round__blocked-reason",children:qe.blockedReason})]},qe.roundId))})]}),on.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:on.map(qe=>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:()=>ni(qe.id),title:`Jump to feature ${qe.id}`,children:qe.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Hr[qe.status].bg,color:Hr[qe.status].text},children:qe.status}),qe.loopState&&t.jsx("span",{className:`mission-loop-state mission-loop-state--${qe.loopState}`,children:qe.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:()=>ni(qe.sourceFeatureId),title:`Jump to source feature ${qe.sourceFeatureId}`,children:qe.sourceFeatureId}),t.jsx("span",{children:"Run:"}),t.jsx("span",{className:"mission-fix-feature__run",children:qe.runId})]}),qe.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:qe.failedAssertionIds.map(Ve=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Tn(Ve),title:`Jump to assertion ${Ve}`,children:Ve},`${qe.id}-${Ve}`))})]})]},qe.id))})]})]}),t.jsxs("div",{className:"mission-slices",children:[H.slices.map(qe=>t.jsxs("div",{className:"mission-slice",children:[t.jsxs("div",{className:"mission-slice__header",onClick:()=>zn(qe.id),children:[t.jsx("button",{className:"mission-slice__expand",children:$.has(qe.id)?t.jsx(qt,{size:16}):t.jsx(hn,{size:16})}),t.jsx(bc,{size:16,className:"mission-slice__icon"}),t.jsx("span",{className:"mission-slice__title",children:qe.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Fu[qe.status].bg,color:Fu[qe.status].text},children:qe.status}),t.jsxs("span",{className:"mission-slice__count",children:[qe.features?.length||0," features"]}),t.jsx(Uu,{state:qe.planState??"not_started"}),qe.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>ze({type:"slice",id:qe.id,title:qe.title}),title:"Plan slice","aria-label":"Plan slice",children:t.jsx(Oi,{size:14})}),t.jsxs("div",{className:"mission-slice__actions",onClick:Ve=>Ve.stopPropagation(),children:[qe.status==="pending"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>_s(qe.id),title:"Activate slice",children:t.jsx(xn,{size:14})}),qe.status==="active"&&qe.features?.some(Ve=>Ve.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>_a(qe.id),title:"Triage all features",disabled:A,children:A?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Pn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>is(qe.id),title:"Add feature",children:t.jsx(Zt,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>xs(qe),title:"Edit slice",children:t.jsx(Yn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ie({type:"slice",id:qe.id}),title:"Delete slice",children:t.jsx(Xt,{size:14})})]})]}),$.has(qe.id)&&t.jsxs("div",{className:"mission-slice__body",children:[me&&ae===H.id&&!T&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:q.title,onChange:Ve=>G({...q,title:Ve.target.value}),onKeyDown:el,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:q.description,onChange:Ve=>G({...q,description:Ve.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Ln,disabled:A,children:[A?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Mn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:kn,children:"Cancel"})]})]}),T===qe.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:q.title,onChange:Ve=>G({...q,title:Ve.target.value}),onKeyDown:el,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:q.description,onChange:Ve=>G({...q,description:Ve.target.value}),rows:2}),t.jsxs("select",{value:q.status,onChange:Ve=>G({...q,status:Ve.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:Ln,disabled:A,children:[A?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Mn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:kn,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-features",children:[qe.features?.map(Ve=>t.jsxs("div",{className:"mission-feature","data-mission-feature-id":Ve.id,children:[t.jsxs("div",{className:"mission-feature__header",children:[t.jsx("button",{className:"mission-feature__expand",onClick:()=>$r(Ve.id),title:$t===Ve.id?"Collapse details":"Expand to show run history",children:$t===Ve.id?t.jsx(qt,{size:14}):t.jsx(hn,{size:14})}),t.jsx(uc,{size:14,className:"mission-feature__icon"}),t.jsx("span",{className:"mission-feature__title",children:Ve.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Hr[Ve.status].bg,color:Hr[Ve.status].text},children:Ve.status}),Ve.loopState&&Ve.loopState!=="idle"&&t.jsxs("span",{className:`mission-loop-state mission-loop-state--${Ve.loopState}`,title:`Loop state: ${Ve.loopState}`,children:[Ve.loopState==="implementing"&&"⏳",Ve.loopState==="validating"&&"🔄",Ve.loopState==="needs_fix"&&"🔧",Ve.loopState==="passed"&&"✅",Ve.loopState==="blocked"&&"🚫"]}),Ve.generatedFromFeatureId&&t.jsx("button",{className:"mission-feature__lineage",onClick:()=>ni(Ve.generatedFromFeatureId),title:`Generated from feature: ${Ve.generatedFromFeatureId}`,children:"🔗 Fix"}),(Ve.loopState==="validating"||Ve.loopState==="needs_fix")&&(()=>{const ft=kt.get(Ve.id),ln=Zo.get(Ve.id),ys=ft?.implementationAttemptCount??ln?.implementationAttempt??Ve.implementationAttemptCount??0,Ai=ft?.retryBudgetRemaining??Math.max(0,v1-ys);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",ys," · ",Ai," ",Ai===1?"retry":"retries"," left"]})})(),Ve.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>Pr(Ve.id),title:"Validate feature",disabled:Ct.has(Ve.id),children:Ct.has(Ve.id)?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(qn,{size:14})}),Ve.taskId&&t.jsx("span",{className:"mission-feature__task-link",onClick:()=>o?.(Ve.taskId),title:"Click to view task",children:Ve.taskId}),t.jsxs("div",{className:"mission-feature__actions",children:[Ve.status==="defined"&&!Ve.taskId&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ar(Ve.id),title:"Triage — create task",disabled:A||Be===Ve.id,children:Be===Ve.id?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Pn,{size:14})}),Ve.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>zs(Ve.id),title:"Unlink task",children:t.jsx(Md,{size:14})}):Ve.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ke(Ve.id),title:"Link to task",children:t.jsx(ua,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ms(Ve),title:"Edit feature",children:t.jsx(Yn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ie({type:"feature",id:Ve.id}),title:"Delete feature",children:t.jsx(Xt,{size:14})})]})]}),Ve.description&&t.jsx("p",{className:"mission-feature__description",children:Ve.description}),Ve.acceptanceCriteria&&t.jsxs("p",{className:"mission-feature__criteria",children:[t.jsx("strong",{children:"Acceptance:"})," ",Ve.acceptanceCriteria]}),be?.featureId===Ve.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:be.enrichedDescription}),t.jsxs("div",{className:"mission-triage-preview__actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:Yo,disabled:A,children:[A?t.jsx(ot,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:Ei,disabled:A,children:"Cancel"})]})]}),U===Ve.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:ne.title,onChange:ft=>xe({...ne,title:ft.target.value}),onKeyDown:tl,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:ne.description,onChange:ft=>xe({...ne,description:ft.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:ne.acceptanceCriteria,onChange:ft=>xe({...ne,acceptanceCriteria:ft.target.value}),rows:2}),t.jsxs("select",{value:ne.status,onChange:ft=>xe({...ne,status:ft.target.value}),children:[t.jsx("option",{value:"defined",children:"Defined"}),t.jsx("option",{value:"triaged",children:"Triaged"}),t.jsx("option",{value:"in-progress",children:"In Progress"}),t.jsx("option",{value:"done",children:"Done"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Kn,disabled:A,children:[A?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Mn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bs,children:"Cancel"})]})]}),$t===Ve.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"})}),(ge.get(Ve.id)??[]).map(ft=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>X(ft.id),children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${ft.status}`,title:ft.status,children:ft.status}),t.jsx("span",{className:"mission-run__time",children:new Date(ft.startedAt).toLocaleString()}),ft.completedAt&&t.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(ft.completedAt).getTime()-new Date(ft.startedAt).getTime())/1e3),"s"]}),ft.triggerType&&t.jsx("span",{className:"mission-run__trigger",children:ft.triggerType}),t.jsx("button",{className:"mission-icon-btn",title:j===ft.id?"Hide details":"Show details",children:j===ft.id?t.jsx(qt,{size:12}):t.jsx(hn,{size:12})})]}),j===ft.id&&De.get(ft.id)&&t.jsxs("div",{className:"mission-run__details",children:[ft.summary&&t.jsx("p",{className:"mission-run__summary",children:ft.summary}),ft.blockedReason&&t.jsxs("p",{className:"mission-run__blocked-reason",children:[t.jsx("strong",{children:"Blocked:"})," ",ft.blockedReason]}),De.get(ft.id)?.failures&&De.get(ft.id).failures.length>0&&t.jsxs("div",{className:"mission-run__failures",children:[t.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),De.get(ft.id).failures.map(ln=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:ln.message}),ln.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",ln.expected]}),ln.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",ln.actual]})]},ln.id))]}),(!De.get(ft.id)?.failures||De.get(ft.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},ft.id)),(!ge.get(Ve.id)||ge.get(Ve.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},Ve.id)),le&&ee===qe.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:ne.title,onChange:Ve=>xe({...ne,title:Ve.target.value}),onKeyDown:tl,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:ne.description,onChange:Ve=>xe({...ne,description:Ve.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:ne.acceptanceCriteria,onChange:Ve=>xe({...ne,acceptanceCriteria:Ve.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Kn,disabled:A,children:[A?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Mn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bs,children:"Cancel"})]})]}),!le&&(!qe.features||qe.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(uc,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},qe.id)),H.slices.length===0&&!me&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(bc,{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"}),Le&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Dt.bg,color:Dt.text},children:Bu(Le.state)}),Le&&Le.totalAssertions>0&&t.jsx("div",{className:"mission-assertions__coverage-bar",title:`${Le.passedAssertions??0} of ${Le.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${(Le.passedAssertions??0)/Le.totalAssertions*100}%`,backgroundColor:(Le.passedAssertions??0)===Le.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>{ue(!0),Je(null),de({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx(Zt,{size:14})})]}),re&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:$e.title,onChange:qe=>de({...$e,title:qe.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:$e.assertion,onChange:qe=>de({...$e,assertion:qe.target.value}),rows:2}),t.jsxs("select",{value:$e.status,onChange:qe=>de({...$e,status:qe.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:()=>Rr(H.id),disabled:A,children:[A?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Mn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Mi,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(Ae.get(H.id))?Ae.get(H.id):[]).map(qe=>t.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":qe.id,children:[t.jsx("div",{className:"mission-assertion__header",children:Re===qe.id?t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:$e.title,onChange:Ve=>de({...$e,title:Ve.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:$e.assertion,onChange:Ve=>de({...$e,assertion:Ve.target.value}),rows:2}),t.jsxs("select",{value:$e.status,onChange:Ve=>de({...$e,status:Ve.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:()=>Qo(qe.id,H.id),disabled:A,children:[A?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Mn,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Mi,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(Vr[qe.status]??Vr.pending).bg,color:(Vr[qe.status]??Vr.pending).text},children:qe.status}),t.jsx("span",{className:"mission-assertion__title",children:qe.title}),(()=>{const ft=fe.get(qe.id)?.length??0;return ft>0?t.jsxs("span",{className:"mission-assertion__linked-count",title:`${ft} linked feature${ft!==1?"s":""}`,children:["(",ft," linked)"]}):null})(),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ma(qe.id),title:"Toggle details",children:Pe===qe.id?t.jsx(qt,{size:14}):t.jsx(hn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Tr(qe),title:"Edit assertion",children:t.jsx(Yn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ie({type:"assertion",id:qe.id}),title:"Delete assertion",children:t.jsx(Xt,{size:14})})]})}),Pe===qe.id&&t.jsxs("div",{className:"mission-assertion__body",children:[t.jsx("p",{className:"mission-assertion__text",children:qe.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()=>{Pe!==qe.id&&await Ma(qe.id),Mt(wt===qe.id?null:qe.id)},title:"Link a feature",children:[t.jsx(ua,{size:12}),"Link Feature"]})]}),wt===qe.id&&t.jsx("div",{className:"mission-assertion__feature-picker",children:t.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const Ve=new Set((fe.get(qe.id)??[]).map(ln=>ln.id)),ft=[];return f?.milestones.forEach(ln=>ln.slices.forEach(ys=>ft.push(...ys.features.filter(Ai=>!Ve.has(Ai.id))))),ft.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):ft.map(ln=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>Aa(ln.id,qe.id),disabled:ut.has(qe.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:ln.title}),ut.has(qe.id)&&t.jsx(ot,{size:12,className:"spinner"})]},ln.id))})()})}),(()=>{const Ve=fe.get(qe.id)??[];return Ve.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):Ve.map(ft=>{const ln=`${ft.id}-${qe.id}`,ys=gt.has(ln);return t.jsxs("div",{className:"mission-assertion__linked-feature",children:[t.jsx("span",{className:"mission-assertion__linked-feature-title",children:ft.title}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>as(ft.id,qe.id),disabled:ys,title:"Unlink feature",children:ys?t.jsx(ot,{size:12,className:"spinner"}):t.jsx(Md,{size:12})})]},ft.id)})})()]})]})]},qe.id)),(!Ae.get(H.id)||Ae.get(H.id)?.length===0)&&!re&&t.jsx("div",{className:"mission-manager__empty mission-assertions__empty",children:t.jsx("span",{children:"No assertions defined. Add one to define completion criteria."})})]})]})]})]})]},H.id)}),f&&!E&&I===null&&t.jsxs("button",{className:"mission-add-btn",onClick:mt,children:[t.jsx(Zt,{size:16}),"Add Milestone"]}),E&&I===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:J.title,onChange:H=>Q({...J,title:H.target.value}),onKeyDown:Yi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:J.description,onChange:H=>Q({...J,description:H.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:tn,disabled:A,children:[A?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Mn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Yt,children:"Cancel"})]})]}),f.milestones.length===0&&!E&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Ui,{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:vn,onChange:H=>Y(H.target.value),"data-testid":"mission-activity-filter",children:[t.jsx("option",{value:"all",children:"All events"}),t.jsx("option",{value:"errors",children:"Errors & warnings"}),t.jsx("option",{value:"state_changes",children:"State changes"}),t.jsx("option",{value:"tasks",children:"Task events"}),t.jsx("option",{value:"slices",children:"Slice & milestone events"}),t.jsx("option",{value:"autopilot",children:"Autopilot events"})]})]}),t.jsxs("span",{className:"mission-detail__activity-count",children:[mn.length," of ",bn]})]}),!Cn&&Gi&&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:Ra,"data-testid":"mission-activity-load-more",children:"Load more"})}),Cn?t.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[t.jsx(ot,{size:18,className:"spinner"}),t.jsx("span",{children:"Loading mission activity..."})]}):mn.length===0?t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Cs,{size:18}),t.jsx("span",{children:"No events yet."})]}):t.jsxs("div",{ref:st,className:"mission-events","data-testid":"mission-activity-events",children:[mn.map(H=>{const Ce=!!(H.metadata&&Object.keys(H.metadata).length>0),Le=Oe.has(H.id);return t.jsxs("div",{className:"mission-event",children:[t.jsxs("div",{className:"mission-event__header",children:[t.jsx("span",{className:`mission-event__type ${S1(H.eventType)}`,children:C1(H.eventType)}),t.jsx("span",{className:"mission-event__time",children:ko(H.timestamp)})]}),t.jsx("p",{className:"mission-event__description",children:H.description}),t.jsx("span",{className:"mission-event__timestamp",children:new Date(H.timestamp).toLocaleString()}),Ce&&t.jsxs("div",{className:"mission-event__metadata",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>Ta(H.id),"data-testid":`mission-event-metadata-${H.id}`,children:[Le?"Hide":"Show"," metadata"]}),Le&&t.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(H.metadata,null,2)})]})]},H.id)}),t.jsx("div",{ref:pt})]})]})]}):t.jsxs("div",{className:"mission-list",children:[k&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:C.title,onChange:H=>z({...C,title:H.target.value}),onKeyDown:pi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:C.description,onChange:H=>z({...C,description:H.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:at,disabled:A,children:[A?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Mn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:_e,children:"Cancel"})]})]}),g.map(H=>{const Ce=H,Le=f,ht=Le&&Le.id===Ce.id,on=La[Ce.status]||{bg:"",text:""},Dt=Ce.summary,Qt=St.get(Ce.id),qe=j1(Qt),Ve=!!(Dt&&(Dt.totalMilestones>0||Dt.totalFeatures>0)),ft=Qt?.totalTasks??0,ln=Qt?.tasksCompleted??0,ys=Qt?.tasksFailed??0,Ai=Qt?.estimatedCompletionPercent??Dt?.progressPercent??0,Fn=Ve||ft>0||ys>0||!!Qt?.lastActivityAt,jn=Ce.status==="active"&&(Qt?.currentMilestoneId||Qt?.currentSliceId)?"Current milestone/slice in progress":null;return t.jsxs("div",{className:`mission-list__item ${ht?"mission-list__item--selected":""}`,onClick:()=>vs(H),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(ls,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:Ce.title}),H.autopilotEnabled&&t.jsx("span",{title:"Autopilot enabled",children:t.jsx(Pn,{size:12,className:"mission-list__item-autopilot-icon"})}),t.jsx("span",{className:`mission-health-badge mission-health-badge--${qe}`,"data-testid":`mission-health-badge-${Ce.id}`,"aria-label":`Mission health: ${qe}`}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:on.bg,color:on.text},children:Ce.status})]}),Ce.description&&t.jsx("p",{className:"mission-list__item-description",children:Ce.description}),jn&&t.jsxs("p",{className:"mission-list__item-active-slice",children:["Active: ",jn]}),Fn&&t.jsxs("div",{className:"mission-list__item-summary",children:[Ve&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[Dt.completedMilestones,"/",Dt.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[Dt.completedFeatures,"/",Dt.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${Ce.id}`,children:[ln,"/",ft," tasks"]}),ys>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:Ft=>{Ft.stopPropagation(),vs(H)},"data-testid":`mission-failed-${Ce.id}`,title:"View mission failures",children:[ys," failed"]}),t.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${Ce.id}`,children:["Activity ",ko(Qt?.lastActivityAt)]}),t.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${qe}`,children:t.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${Ai}%`}})})]})]}),t.jsxs("div",{className:"mission-list__item-actions",onClick:Ft=>Ft.stopPropagation(),children:[Ce.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ct(Ce.id),title:"Stop mission",children:t.jsx(ms,{size:14})}),Ce.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>He(Ce.id),title:"Resume mission",children:t.jsx(xn,{size:14})}),Ce.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>It(Ce.id),title:"Start mission",children:t.jsx(xn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>oe(H),title:"Edit mission",children:t.jsx(Yn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ie({type:"mission",id:Ce.id}),title:"Delete mission",children:t.jsx(Xt,{size:14})})]})]},Ce.id)}),N&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:C.title,onChange:H=>z({...C,title:H.target.value}),onKeyDown:pi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:C.description,onChange:H=>z({...C,description:H.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:C.status,onChange:H=>z({...C,status:H.target.value}),children:[t.jsx("option",{value:"planning",children:"Planning"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"blocked",children:"Blocked"}),t.jsx("option",{value:"complete",children:"Complete"}),t.jsx("option",{value:"archived",children:"Archived"})]}),t.jsxs("label",{className:"mission-checkbox",children:[t.jsx("input",{type:"checkbox",checked:C.autopilotEnabled,onChange:H=>z({...C,autopilotEnabled:H.target.checked})}),t.jsx(Pn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:at,disabled:A,children:[A?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Mn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:_e,children:"Cancel"})]})]}),g.length===0&&!k&&t.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large",children:[t.jsx(ls,{size:32}),t.jsx("span",{children:"No missions yet. Create one to start planning."})]}),!k&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[Ie.length>0&&t.jsxs("div",{className:"mission-resume-prompt",children:[t.jsx(Xn,{size:16}),t.jsx("span",{children:Ie.length===1?`Resume "${Ie[0].title}"?`:`${Ie.length} interview sessions pending`}),t.jsx("div",{style:{display:"flex",gap:"4px",marginLeft:"auto"},children:Ie.map(H=>t.jsxs("button",{className:"mission-add-btn",onClick:()=>{ye(H.id),it(!0),Ge([])},children:[H.status==="error"?t.jsx(Nn,{size:14}):t.jsx(qn,{size:14}),H.status==="error"?"Retry":"Resume"]},H.id))})]}),t.jsxs("div",{style:{display:"flex",gap:"8px"},children:[t.jsxs("button",{className:"mission-add-btn",onClick:()=>it(!0),children:[t.jsx(qn,{size:16}),"Plan with AI"]}),t.jsxs("button",{className:"mission-add-btn",onClick:Si,children:[t.jsx(Zt,{size:16}),"New Mission"]})]})]})]})}),je&&t.jsx("div",{className:"mission-confirm-panel mission-confirm-panel--danger",children:t.jsxs("div",{className:"mission-confirm-panel__content",children:[t.jsxs("p",{children:["Delete this ",je.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()=>{je.type==="mission"?await We(je.id):je.type==="milestone"?await rn(je.id):je.type==="slice"?await Wn(je.id):je.type==="feature"&&await Gn(je.id)},children:"Delete"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>ie(null),children:"Cancel"})]})]})}),Fe&&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:Ze,onChange:H=>Xe(H.target.value),autoFocus:!0}),l.length>0&&t.jsxs("div",{className:"mission-task-suggestions",children:[t.jsx("small",{children:"Or select:"}),t.jsx("div",{className:"mission-task-suggestions__list",children:l.slice(0,5).map(H=>t.jsxs("button",{className:"mission-task-suggestions__item",onClick:()=>Xe(H.id),children:[H.id,": ",H.title||"Untitled"]},H.id))})]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--primary",onClick:ei,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{Ke(null),Xe("")},children:"Cancel"})]})]})})]}),Rs=t.jsx(h1,{isOpen:Qe,onClose:()=>it(!1),onMissionCreated:()=>{en(),i("Mission created from AI interview","success")},projectId:r,resumeSessionId:Z}),Ts=Te?t.jsx(g1,{isOpen:!0,onClose:()=>ze(null),onApplied:()=>{ze(null),f&&xt(f.id)},targetType:Te.type,targetId:Te.id,targetTitle:Te.title,missionContext:f?.title,projectId:r,resumeSessionId:Te.resumeSessionId}):null;return n?t.jsxs(t.Fragment,{children:[si,Rs,Ts]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mission-manager-overlay open",onClick:H=>H.target===H.currentTarget&&s(),"data-testid":"mission-manager-overlay",role:"dialog","aria-modal":"true",children:si}),Rs,Ts]})}const Wr=2e3;function qu({recipient:e,replyContext:n,agents:s=[],projectId:i,onSend:r,onCancel:o,addToast:l,isLoadingAgents:c=!1}){const[u,d]=a.useState(e?.id??""),[m,h]=a.useState(e?.type??"agent"),[g,p]=a.useState(""),[f,x]=a.useState(!1),[v,b]=a.useState(null),y=u.trim()!==""&&g.trim().length>0&&g.length<=Wr,S=a.useCallback(async()=>{if(!(!y||f)){x(!0),b(null);try{const R=m==="agent"?"user-to-agent":"system";await Fj({toId:u.trim(),toType:m,content:g.trim(),type:R,...n?{metadata:{replyTo:{messageId:n.messageId}}}:{}},i),r()}catch(R){const N=ke(R)||"Failed to send message";b(N),l?.(N,"error")}finally{x(!1)}}},[y,f,u,m,g,n,i,r,l]),k=a.useCallback(R=>{d(R),h("agent")},[]);return t.jsxs("div",{className:"message-composer","data-testid":"message-composer",children:[t.jsxs("div",{className:"message-composer-header",children:[t.jsx("span",{children:n?"Reply":"New Message"}),t.jsx("button",{className:"btn-icon",onClick:o,"aria-label":"Cancel","data-testid":"message-composer-cancel",children:t.jsx(Ot,{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:u,onChange:R=>k(R.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(R=>t.jsx("option",{value:R.id,children:R.name||R.id},R.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(gn,{size:14}),e.id]})]}),n&&t.jsxs("div",{className:"message-composer-field","data-testid":"message-composer-reply-context",children:[t.jsx("span",{className:"message-composer-label",children:"Replying to:"}),t.jsx("span",{className:"message-composer-recipient-fixed",children:n.preview?.trim()?n.preview:`Message ${n.messageId}`})]}),t.jsxs("div",{className:"message-composer-field message-composer-field--content",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-content",children:"Message:"}),t.jsx("textarea",{id:"message-content",className:"message-composer-textarea",placeholder:"Type your message…",value:g,onChange:R=>p(R.target.value),maxLength:Wr,rows:4,"data-testid":"message-composer-content"}),t.jsx("div",{className:"message-composer-charcount","data-testid":"message-composer-charcount",children:t.jsxs("span",{className:g.length>Wr?"over-limit":"",children:[g.length,"/",Wr]})})]}),v&&t.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[t.jsx(Xn,{size:14}),t.jsx("span",{children:v})]})]}),t.jsxs("div",{className:"message-composer-footer",children:[t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:o,"data-testid":"message-composer-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:S,disabled:!y||f,"data-testid":"message-composer-send",children:f?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:14,className:"spin"}),t.jsx("span",{children:"Sending…"})]}):t.jsxs(t.Fragment,{children:[t.jsx(Di,{size:14}),t.jsx("span",{children:"Send"})]})})]})]})}function ta(e){const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),o=Math.floor(i/36e5),l=Math.floor(i/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 M1(e,n,s){if(n==="user")return e==="dashboard"?"You":`User: ${e}`;if(n==="agent"){const i=s?.get(e)?.trim();return i?i===e?`Agent: ${e}`:`Agent: ${i} (${e})`:`Agent: ${e}`}return"System"}function A1(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 Vu(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function R1(e){const n=new Map;for(const s of e){const i=`${s.fromType}:${s.fromId}`,r=n.get(i);r?(r.messages.push(s),new Date(s.createdAt)>new Date(r.latestMessage.createdAt)&&(r.latestMessage=s),s.read||r.unreadCount++):n.set(i,{key:i,fromId:s.fromId,fromType:s.fromType,latestMessage:s,messages:[s],unreadCount:s.read?0:1})}return Array.from(n.values()).sort((s,i)=>new Date(i.latestMessage.createdAt).getTime()-new Date(s.latestMessage.createdAt).getTime())}function T1({projectId:e,addToast:n,onUnreadCountChange:s}){const[i,r]=a.useState("inbox"),[o,l]=a.useState(null),[c,u]=a.useState(null),[d,m]=a.useState(0),[h,g]=a.useState(!1),[p,f]=a.useState(null),[x,v]=a.useState([]),[b,y]=a.useState(!1),[S,k]=a.useState(null),[R,N]=a.useState(null),[M,C]=a.useState(null),[z,A]=a.useState("inbox"),[P,F]=a.useState(null),[W,$]=a.useState([]),_=a.useMemo(()=>new Map(W.map(ee=>[ee.id,ee.name??""])),[W]),I=a.useCallback((ee,Ee)=>M1(ee,Ee,_),[_]),J=Cr()==="mobile",Q=!J,E=a.useCallback(async()=>{g(!0);try{const ee=await Lj({limit:50},e);l(ee),m(ee.unreadCount),s?.(ee.unreadCount)}catch{}finally{g(!1)}},[e,s]),D=a.useCallback(async()=>{g(!0);try{const ee=await zj({limit:50},e);u(ee)}catch{}finally{g(!1)}},[e]),T=a.useCallback(async ee=>{g(!0);try{const Ee=await qj(ee,e);F(Ee)}catch{}finally{g(!1)}},[e]),w=a.useCallback(async()=>{try{const ee=await Na(void 0,e);$(ee)}catch{}},[e]),q=a.useCallback(async()=>{try{const ee=await mp(e);m(ee.unreadCount),s?.(ee.unreadCount)}catch{}},[e,s]);a.useEffect(()=>{i==="inbox"?E():i==="outbox"?D():i==="agents"&&w()},[i,E,D,w]),a.useEffect(()=>{M&&T(M)},[M,T]),a.useEffect(()=>{q()},[q]),a.useEffect(()=>{w()},[w]),a.useEffect(()=>{if(typeof EventSource>"u")return;const ee=e?`?projectId=${encodeURIComponent(e)}`:"",Ee=()=>{q(),i==="inbox"?E():i==="outbox"&&D(),M&&T(M)};return Ls(`/api/events${ee}`,{events:{"message:sent":Ee,"message:received":Ee,"message:read":Ee,"message:deleted":Ee}})},[e,i,M,q,E,D,T]);const G=a.useCallback(async ee=>{if(f(ee),!ee.read)try{const Ee=await Oj(ee.id,e);Ee&&l(Ke=>Ke&&{...Ke,messages:Ke.messages.map(Ze=>Ze.id===Ee.id?Ee:Ze),unreadCount:Math.max(0,Ke.unreadCount-1)});const Fe=Math.max(0,d-1);m(Fe),s?.(Fe)}catch{}try{const Ee=await Hj(ee.fromId,ee.fromType,e);v(Ee)}catch{v([ee])}},[e,d,s]),me=a.useCallback(()=>{f(null),v([])},[]),ce=a.useCallback(async()=>{try{const ee=await Uj(e);m(0),s?.(0),l(Ee=>Ee&&{...Ee,messages:Ee.messages.map(Fe=>({...Fe,read:!0})),unreadCount:0}),n?.(`Marked ${ee.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[e,n,s]),ae=a.useCallback(async ee=>{try{await Bj(ee,e),f(null),v([]),i==="inbox"?E():i==="outbox"?D():M&&T(M),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,i,M,E,D,T,n]),pe=a.useCallback(ee=>{k({id:ee.fromId,type:ee.fromType}),N({messageId:ee.id,preview:Vu(ee.content,120)}),y(!0)},[]),U=a.useCallback(()=>{y(!1),k(null),N(null),n?.("Message sent","success"),i==="outbox"?D():i==="agents"&&M&&T(M),q()},[i,D,M,T,n,q]),Ne=a.useCallback(()=>{k(i==="agents"&&M?{id:M,type:"agent"}:null),N(null),y(!0)},[i,M]),ne=a.useCallback(()=>{y(!1),k(null),N(null)},[]),xe=()=>!p||b?null:t.jsxs("div",{className:"mailbox-message-detail","data-testid":"mailbox-message-detail",children:[t.jsxs("div",{className:"mailbox-message-detail-header",children:[J&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:me,"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:A1(p.type)}),t.jsx("span",{className:"mailbox-message-time",children:ta(p.createdAt)})]}),t.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>pe(p),"data-testid":"mailbox-reply",children:[t.jsx(bi,{size:14}),t.jsx("span",{children:"Reply"})]}),t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>ae(p.id),"data-testid":"mailbox-delete",children:[t.jsx(Xt,{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(gn,{size:14}):t.jsx(Qi,{size:14}),I(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(gn,{size:14}):t.jsx(Qi,{size:14}),I(p.toId,p.toType)]})]})]}),x.length>1&&t.jsxs("div",{className:"mailbox-conversation","data-testid":"mailbox-conversation",children:[t.jsx("div",{className:"mailbox-conversation-label",children:"Conversation"}),x.map(ee=>{const Ee=ee.metadata?.replyTo?.messageId,Fe=Ee?x.find(Ke=>Ke.id===Ee):void 0;return t.jsxs("div",{className:`mailbox-conversation-msg ${ee.id===p.id?"current":""}`,children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:I(ee.fromId,ee.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:ta(ee.createdAt)})]}),Ee&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":`mailbox-reply-context-${ee.id}`,children:["↪ Replying to ",Fe?Vu(Fe.content,60):`message ${Ee}`]}),t.jsx("div",{className:"mailbox-conversation-msg-body",children:ee.content})]},ee.id)})]}),x.length<=1&&t.jsxs(t.Fragment,{children:[p.metadata?.replyTo?.messageId&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":"mailbox-selected-reply-context",children:["↪ Replying to message ",p.metadata.replyTo.messageId]}),t.jsx("div",{className:"mailbox-message-body","data-testid":"mailbox-message-body",children:p.content})]})]}),le=()=>t.jsxs(t.Fragment,{children:[i==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!o&&t.jsx(Nl,{}),o&&o.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[t.jsx(Za,{size:32}),t.jsx("p",{children:"No messages in your inbox"})]}),o&&o.messages.length>0&&t.jsx("div",{className:"mailbox-conversations","data-testid":"mailbox-conversations",children:R1(o.messages).map(ee=>t.jsxs("div",{className:`mailbox-conversation-group ${ee.unreadCount>0?"unread":""}`,onClick:()=>G(ee.latestMessage),"data-testid":`mailbox-conversation-${ee.key}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ee.fromType==="agent"?t.jsx(gn,{size:16}):t.jsx(Qi,{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:I(ee.fromId,ee.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:ta(ee.latestMessage.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ee.latestMessage.content.slice(0,80),ee.latestMessage.content.length>80?"…":""]})]}),ee.unreadCount>0&&t.jsx("div",{className:"mailbox-group-unread-badge","data-testid":`mailbox-unread-badge-${ee.key}`,children:ee.unreadCount>9?"9+":ee.unreadCount})]},ee.key))})]}),i==="outbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!c&&t.jsx(Nl,{}),c&&c.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[t.jsx(Di,{size:32}),t.jsx("p",{children:"No sent messages"})]}),c?.messages.map(ee=>t.jsxs("div",{className:"mailbox-item",onClick:()=>G(ee),"data-testid":`mailbox-item-${ee.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ee.toType==="agent"?t.jsx(gn,{size:16}):t.jsx(Qi,{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: ",I(ee.toId,ee.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:ta(ee.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ee.content.slice(0,80),ee.content.length>80?"…":""]})]})]},ee.id))]}),i==="agents"&&t.jsx("div",{className:"mailbox-agents","data-testid":"mailbox-agents",children:W.length===0?t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(gn,{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:M??"",onChange:ee=>{C(ee.target.value||null),A("inbox")},"data-testid":"mailbox-agent-select",children:[t.jsx("option",{value:"",children:"Select an agent…"}),W.map(ee=>t.jsx("option",{value:ee.id,children:ee.name||ee.id},ee.id))]})}),t.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:Ne,"data-testid":"mailbox-compose-btn",children:[t.jsx(bi,{size:14}),t.jsx("span",{children:"Compose"})]})]}),M&&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 ${z==="inbox"?"active":""}`,onClick:()=>A("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[t.jsx(Za,{size:12}),t.jsx("span",{children:"Inbox"}),P&&P.unreadCount>0&&t.jsx("span",{className:"mailbox-tab-badge",children:P.unreadCount})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${z==="outbox"?"active":""}`,onClick:()=>A("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[t.jsx(Di,{size:12}),t.jsx("span",{children:"Outbox"})]})]}),t.jsxs("div",{className:"mailbox-agents-content",children:[!M&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(gn,{size:32}),t.jsx("p",{children:"Select an agent to view their mailbox"})]}),M&&h&&!P&&t.jsx(Nl,{}),M&&P&&z==="inbox"&&P.inbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Za,{size:32}),t.jsx("p",{children:"No received messages for this agent"})]}),M&&P&&z==="outbox"&&P.outbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Di,{size:32}),t.jsx("p",{children:"No sent messages for this agent"})]}),M&&P&&z==="inbox"&&P.inbox.map(ee=>t.jsxs("div",{className:`mailbox-item ${ee.read?"":"unread"}`,onClick:()=>G(ee),"data-testid":`mailbox-item-${ee.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ee.fromType==="agent"?t.jsx(gn,{size:16}):t.jsx(Qi,{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:I(ee.fromId,ee.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:ta(ee.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ee.content.slice(0,80),ee.content.length>80?"…":""]})]})]},ee.id)),M&&P&&z==="outbox"&&P.outbox.map(ee=>t.jsxs("div",{className:"mailbox-item",onClick:()=>G(ee),"data-testid":`mailbox-item-${ee.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ee.toType==="agent"?t.jsx(gn,{size:16}):t.jsx(Qi,{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: ",I(ee.toId,ee.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:ta(ee.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ee.content.slice(0,80),ee.content.length>80?"…":""]})]})]},ee.id))]})]})})]}),ve=()=>b?t.jsx(qu,{recipient:S,replyContext:R,agents:W,projectId:e,onSend:U,onCancel:ne,addToast:n}):p?xe():t.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[t.jsx(ma,{size:24}),t.jsx("p",{children:"Select a conversation to read messages"})]});return t.jsxs("div",{className:"mailbox-view","data-testid":"mailbox-view",children:[t.jsxs("div",{className:"mailbox-header",children:[t.jsxs("div",{className:"mailbox-title",children:[t.jsx(ma,{size:18}),t.jsx("span",{children:"Mailbox"}),d>0&&t.jsx("span",{className:"mailbox-unread-badge","data-testid":"mailbox-unread-badge",children:d})]}),t.jsxs("div",{className:"mailbox-header-actions",children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:Ne,title:"Compose message","data-testid":"mailbox-header-compose",children:[t.jsx(bi,{size:14}),t.jsx("span",{children:"Compose"})]}),i==="inbox"&&d>0&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:ce,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[t.jsx(Ig,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{i==="inbox"?E():i==="outbox"?D():M&&T(M)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Nn,{size:14})})]})]}),t.jsxs("div",{className:"mailbox-tabs","data-testid":"mailbox-tabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="inbox"?"active":""}`,onClick:()=>{r("inbox"),f(null)},"data-testid":"mailbox-tab-inbox",children:[t.jsx(Za,{size:14}),t.jsx("span",{children:"Inbox"}),d>0&&t.jsx("span",{className:"mailbox-tab-badge",children:d})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="outbox"?"active":""}`,onClick:()=>{r("outbox"),f(null)},"data-testid":"mailbox-tab-outbox",children:[t.jsx(Di,{size:14}),t.jsx("span",{children:"Outbox"})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="agents"?"active":""}`,onClick:()=>{r("agents"),f(null)},"data-testid":"mailbox-tab-agents",children:[t.jsx(gn,{size:14}),t.jsx("span",{children:"Agents"})]})]}),t.jsx("div",{className:"mailbox-content","data-testid":"mailbox-content",children:Q?t.jsxs("div",{className:"mailbox-split-layout","data-testid":"mailbox-split-layout",children:[t.jsx("div",{className:"mailbox-split-list-pane","data-testid":"mailbox-split-list-pane",children:le()}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:ve()})]}):t.jsxs(t.Fragment,{children:[xe(),b&&t.jsx(qu,{recipient:S,replyContext:R,agents:W,projectId:e,onSend:U,onCancel:ne,addToast:n}),!p&&!b&&le()]})})]})}function Nl(){return t.jsx("div",{className:"mailbox-skeleton","data-testid":"mailbox-skeleton",children:Array.from({length:5}).map((e,n)=>t.jsxs("div",{className:"mailbox-skeleton-item",children:[t.jsx("div",{className:"mailbox-skeleton-avatar"}),t.jsxs("div",{className:"mailbox-skeleton-content",children:[t.jsx("div",{className:"mailbox-skeleton-line mailbox-skeleton-line--short"}),t.jsx("div",{className:"mailbox-skeleton-line mailbox-skeleton-line--long"})]})]},n))})}function Xs(e,n,s){a.useEffect(()=>{if(!n)return;const i=e.current;if(!i)return;try{const u=localStorage.getItem(s);if(u){const{width:d,height:m}=JSON.parse(u);typeof d=="number"&&d>0&&(i.style.width=`${d}px`),typeof m=="number"&&m>0&&(i.style.height=`${m}px`)}}catch{}if(typeof ResizeObserver>"u")return;let r=i.offsetWidth,o=i.offsetHeight,l=null;const c=new ResizeObserver(()=>{const u=i.offsetWidth,d=i.offsetHeight;u===r&&d===o||(r=u,o=d,l&&clearTimeout(l),l=setTimeout(()=>{try{localStorage.setItem(s,JSON.stringify({width:u,height:d}))}catch{}},200))});return c.observe(i),()=>{c.disconnect(),l&&clearTimeout(l)}},[e,n,s])}function wi(e){const n=a.useRef(!1),s=a.useCallback(r=>{n.current=r.target===r.currentTarget},[]),i=a.useCallback(r=>{const o=n.current&&r.target===r.currentTarget;n.current=!1,o&&e()},[e]);return{onMouseDown:s,onMouseUp:i}}function P1(e,n){const s={};return(e[e.length-1]===""?[...e,""]:e).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const I1=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,$1=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,D1={};function Wu(e,n){return(D1.jsx?$1:I1).test(e)}const L1=/[ \t\n\f\r]/g;function z1(e){return typeof e=="object"?e.type==="text"?Ku(e.value):!1:Ku(e)}function Ku(e){return e.replace(L1,"")===""}class Er{constructor(n,s,i){this.normal=s,this.property=n,i&&(this.space=i)}}Er.prototype.normal={};Er.prototype.property={};Er.prototype.space=void 0;function Dp(e,n){const s={},i={};for(const r of e)Object.assign(s,r.property),Object.assign(i,r.normal);return new Er(s,i,n)}function Ac(e){return e.toLowerCase()}class ds{constructor(n,s){this.attribute=s,this.property=n}}ds.prototype.attribute="";ds.prototype.booleanish=!1;ds.prototype.boolean=!1;ds.prototype.commaOrSpaceSeparated=!1;ds.prototype.commaSeparated=!1;ds.prototype.defined=!1;ds.prototype.mustUseProperty=!1;ds.prototype.number=!1;ds.prototype.overloadedBoolean=!1;ds.prototype.property="";ds.prototype.spaceSeparated=!1;ds.prototype.space=void 0;let F1=0;const Lt=Ki(),En=Ki(),Rc=Ki(),et=Ki(),cn=Ki(),ca=Ki(),us=Ki();function Ki(){return 2**++F1}const Tc=Object.freeze(Object.defineProperty({__proto__:null,boolean:Lt,booleanish:En,commaOrSpaceSeparated:us,commaSeparated:ca,number:et,overloadedBoolean:Rc,spaceSeparated:cn},Symbol.toStringTag,{value:"Module"})),Sl=Object.keys(Tc);class od extends ds{constructor(n,s,i,r){let o=-1;if(super(n,s),Gu(this,"space",r),typeof i=="number")for(;++o<Sl.length;){const l=Sl[o];Gu(this,Sl[o],(i&Tc[l])===Tc[l])}}}od.prototype.defined=!0;function Gu(e,n,s){s&&(e[n]=s)}function Ca(e){const n={},s={};for(const[i,r]of Object.entries(e.properties)){const o=new od(i,e.transform(e.attributes||{},i),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(i)&&(o.mustUseProperty=!0),n[i]=o,s[Ac(i)]=i,s[Ac(o.attribute)]=i}return new Er(n,s,e.space)}const Lp=Ca({properties:{ariaActiveDescendant:null,ariaAtomic:En,ariaAutoComplete:null,ariaBusy:En,ariaChecked:En,ariaColCount:et,ariaColIndex:et,ariaColSpan:et,ariaControls:cn,ariaCurrent:null,ariaDescribedBy:cn,ariaDetails:null,ariaDisabled:En,ariaDropEffect:cn,ariaErrorMessage:null,ariaExpanded:En,ariaFlowTo:cn,ariaGrabbed:En,ariaHasPopup:null,ariaHidden:En,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:cn,ariaLevel:et,ariaLive:null,ariaModal:En,ariaMultiLine:En,ariaMultiSelectable:En,ariaOrientation:null,ariaOwns:cn,ariaPlaceholder:null,ariaPosInSet:et,ariaPressed:En,ariaReadOnly:En,ariaRelevant:null,ariaRequired:En,ariaRoleDescription:cn,ariaRowCount:et,ariaRowIndex:et,ariaRowSpan:et,ariaSelected:En,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 zp(e,n){return n in e?e[n]:n}function Fp(e,n){return zp(e,n.toLowerCase())}const O1=Ca({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:ca,acceptCharset:cn,accessKey:cn,action:null,allow:null,allowFullScreen:Lt,allowPaymentRequest:Lt,allowUserMedia:Lt,alt:null,as:null,async:Lt,autoCapitalize:null,autoComplete:cn,autoFocus:Lt,autoPlay:Lt,blocking:cn,capture:null,charSet:null,checked:Lt,cite:null,className:cn,cols:et,colSpan:null,content:null,contentEditable:En,controls:Lt,controlsList:cn,coords:et|ca,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Lt,defer:Lt,dir:null,dirName:null,disabled:Lt,download:Rc,draggable:En,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Lt,formTarget:null,headers:cn,height:et,hidden:Rc,high:et,href:null,hrefLang:null,htmlFor:cn,httpEquiv:cn,id:null,imageSizes:null,imageSrcSet:null,inert:Lt,inputMode:null,integrity:null,is:null,isMap:Lt,itemId:null,itemProp:cn,itemRef:cn,itemScope:Lt,itemType:cn,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Lt,low:et,manifest:null,max:null,maxLength:et,media:null,method:null,min:null,minLength:et,multiple:Lt,muted:Lt,name:null,nonce:null,noModule:Lt,noValidate:Lt,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:Lt,optimum:et,pattern:null,ping:cn,placeholder:null,playsInline:Lt,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Lt,referrerPolicy:null,rel:cn,required:Lt,reversed:Lt,rows:et,rowSpan:et,sandbox:cn,scope:null,scoped:Lt,seamless:Lt,selected:Lt,shadowRootClonable:Lt,shadowRootDelegatesFocus:Lt,shadowRootMode:null,shape:null,size:et,sizes:null,slot:null,span:et,spellCheck:En,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:Lt,useMap:null,value:En,width:et,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:cn,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:Lt,declare:Lt,event:null,face:null,frame:null,frameBorder:null,hSpace:et,leftMargin:et,link:null,longDesc:null,lowSrc:null,marginHeight:et,marginWidth:et,noResize:Lt,noHref:Lt,noShade:Lt,noWrap:Lt,object:null,profile:null,prompt:null,rev:null,rightMargin:et,rules:null,scheme:null,scrolling:En,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:Lt,disableRemotePlayback:Lt,prefix:null,property:null,results:et,security:null,unselectable:null},space:"html",transform:Fp}),U1=Ca({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:us,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:cn,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:Lt,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:ca,g2:ca,glyphName:ca,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:us,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:cn,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:et,pointsAtY:et,pointsAtZ:et,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:us,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:us,rev:us,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:us,requiredFeatures:us,requiredFonts:us,requiredFormats:us,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:us,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:us,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:us,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:zp}),Op=Ca({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()}}),Up=Ca({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Fp}),Bp=Ca({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),B1={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"},H1=/[A-Z]/g,Ju=/-[a-z]/g,q1=/^data[-\w.:]+$/i;function V1(e,n){const s=Ac(n);let i=n,r=ds;if(s in e.normal)return e.property[e.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&q1.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(Ju,K1);i="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!Ju.test(o)){let l=o.replace(H1,W1);l.charAt(0)!=="-"&&(l="-"+l),n="data"+l}}r=od}return new r(i,n)}function W1(e){return"-"+e.toLowerCase()}function K1(e){return e.charAt(1).toUpperCase()}const G1=Dp([Lp,O1,Op,Up,Bp],"html"),ld=Dp([Lp,U1,Op,Up,Bp],"svg");function J1(e){return e.join(" ").trim()}var na={},Cl,Yu;function Y1(){if(Yu)return Cl;Yu=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,n=/\n/g,s=/^\s*/,i=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,r=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,l=/^[;\s]*/,c=/^\s+|\s+$/g,u=`
|
|
619
|
+
`,d="/",m="*",h="",g="comment",p="declaration";function f(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 k($){var _=$.match(n);_&&(y+=_.length);var I=$.lastIndexOf(u);S=~I?$.length-I:S+$.length}function R(){var $={line:y,column:S};return function(_){return _.position=new N($),z(),_}}function N($){this.start=$,this.end={line:y,column:S},this.source=b.source}N.prototype.content=v;function M($){var _=new Error(b.source+":"+y+":"+S+": "+$);if(_.reason=$,_.filename=b.source,_.line=y,_.column=S,_.source=v,!b.silent)throw _}function C($){var _=$.exec(v);if(_){var I=_[0];return k(I),v=v.slice(I.length),_}}function z(){C(s)}function A($){var _;for($=$||[];_=P();)_!==!1&&$.push(_);return $}function P(){var $=R();if(!(d!=v.charAt(0)||m!=v.charAt(1))){for(var _=2;h!=v.charAt(_)&&(m!=v.charAt(_)||d!=v.charAt(_+1));)++_;if(_+=2,h===v.charAt(_-1))return M("End of comment missing");var I=v.slice(2,_-2);return S+=2,k(I),v=v.slice(_),S+=2,$({type:g,comment:I})}}function F(){var $=R(),_=C(i);if(_){if(P(),!C(r))return M("property missing ':'");var I=C(o),O=$({type:p,property:x(_[0].replace(e,h)),value:I?x(I[0].replace(e,h)):h});return C(l),O}}function W(){var $=[];A($);for(var _;_=F();)_!==!1&&($.push(_),A($));return $}return z(),W()}function x(v){return v?v.replace(c,h):h}return Cl=f,Cl}var Qu;function Q1(){if(Qu)return na;Qu=1;var e=na&&na.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(na,"__esModule",{value:!0}),na.default=s;const n=e(Y1());function s(i,r){let o=null;if(!i||typeof i!="string")return o;const l=(0,n.default)(i),c=typeof r=="function";return l.forEach(u=>{if(u.type!=="declaration")return;const{property:d,value:m}=u;c?r(d,m,u):m&&(o=o||{},o[d]=m)}),o}return na}var za={},Xu;function X1(){if(Xu)return za;Xu=1,Object.defineProperty(za,"__esModule",{value:!0}),za.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,n=/-([a-z])/g,s=/^[^-]+$/,i=/^-(webkit|moz|ms|o|khtml)-/,r=/^-(ms)-/,o=function(d){return!d||s.test(d)||e.test(d)},l=function(d,m){return m.toUpperCase()},c=function(d,m){return"".concat(m,"-")},u=function(d,m){return m===void 0&&(m={}),o(d)?d:(d=d.toLowerCase(),m.reactCompat?d=d.replace(r,c):d=d.replace(i,c),d.replace(n,l))};return za.camelCase=u,za}var Fa,Zu;function Z1(){if(Zu)return Fa;Zu=1;var e=Fa&&Fa.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=e(Q1()),s=X1();function i(r,o){var l={};return!r||typeof r!="string"||(0,n.default)(r,function(c,u){c&&u&&(l[(0,s.camelCase)(c,o)]=u)}),l}return i.default=i,Fa=i,Fa}var e0=Z1();const t0=$h(e0),Hp=qp("end"),cd=qp("start");function qp(e){return n;function n(s){const i=s&&s.position&&s.position[e]||{};if(typeof i.line=="number"&&i.line>0&&typeof i.column=="number"&&i.column>0)return{line:i.line,column:i.column,offset:typeof i.offset=="number"&&i.offset>-1?i.offset:void 0}}}function n0(e){const n=cd(e),s=Hp(e);if(n&&s)return{start:n,end:s}}function ar(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?em(e.position):"start"in e||"end"in e?em(e):"line"in e||"column"in e?Pc(e):""}function Pc(e){return tm(e&&e.line)+":"+tm(e&&e.column)}function em(e){return Pc(e&&e.start)+"-"+Pc(e&&e.end)}function tm(e){return e&&typeof e=="number"?e:1}class Vn extends Error{constructor(n,s,i){super(),typeof s=="string"&&(i=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 i=="string"){const u=i.indexOf(":");u===-1?o.ruleId=i:(o.source=i.slice(0,u),o.ruleId=i.slice(u+1))}if(!o.place&&o.ancestors&&o.ancestors){const u=o.ancestors[o.ancestors.length-1];u&&(o.place=u.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=ar(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}}Vn.prototype.file="";Vn.prototype.name="";Vn.prototype.reason="";Vn.prototype.message="";Vn.prototype.stack="";Vn.prototype.column=void 0;Vn.prototype.line=void 0;Vn.prototype.ancestors=void 0;Vn.prototype.cause=void 0;Vn.prototype.fatal=void 0;Vn.prototype.place=void 0;Vn.prototype.ruleId=void 0;Vn.prototype.source=void 0;const dd={}.hasOwnProperty,s0=new Map,i0=/[A-Z]/g,a0=new Set(["table","tbody","thead","tfoot","tr"]),r0=new Set(["td","th"]),Vp="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function o0(e,n){if(!n||n.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const s=n.filePath||void 0;let i;if(n.development){if(typeof n.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");i=f0(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");i=p0(s,n.jsx,n.jsxs)}const r={Fragment:n.Fragment,ancestors:[],components:n.components||{},create:i,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"?ld:G1,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=Wp(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function Wp(e,n,s){if(n.type==="element")return l0(e,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return c0(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return u0(e,n,s);if(n.type==="mdxjsEsm")return d0(e,n);if(n.type==="root")return m0(e,n,s);if(n.type==="text")return h0(e,n)}function l0(e,n,s){const i=e.schema;let r=i;n.tagName.toLowerCase()==="svg"&&i.space==="html"&&(r=ld,e.schema=r),e.ancestors.push(n);const o=Gp(e,n.tagName,!1),l=g0(e,n);let c=md(e,n);return a0.has(n.tagName)&&(c=c.filter(function(u){return typeof u=="string"?!z1(u):!0})),Kp(e,l,o,n),ud(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function c0(e,n){if(n.data&&n.data.estree&&e.evaluater){const i=n.data.estree.body[0];return i.type,e.evaluater.evaluateExpression(i.expression)}fr(e,n.position)}function d0(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);fr(e,n.position)}function u0(e,n,s){const i=e.schema;let r=i;n.name==="svg"&&i.space==="html"&&(r=ld,e.schema=r),e.ancestors.push(n);const o=n.name===null?e.Fragment:Gp(e,n.name,!0),l=x0(e,n),c=md(e,n);return Kp(e,l,o,n),ud(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function m0(e,n,s){const i={};return ud(i,md(e,n)),e.create(n,e.Fragment,i,s)}function h0(e,n){return n.value}function Kp(e,n,s,i){typeof s!="string"&&s!==e.Fragment&&e.passNode&&(n.node=i)}function ud(e,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(e.children=s)}}function p0(e,n,s){return i;function i(r,o,l,c){const d=Array.isArray(l.children)?s:n;return c?d(o,l,c):d(o,l)}}function f0(e,n){return s;function s(i,r,o,l){const c=Array.isArray(o.children),u=cd(i);return n(r,o,l,c,{columnNumber:u?u.column-1:void 0,fileName:e,lineNumber:u?u.line:void 0},void 0)}}function g0(e,n){const s={};let i,r;for(r in n.properties)if(r!=="children"&&dd.call(n.properties,r)){const o=b0(e,r,n.properties[r]);if(o){const[l,c]=o;e.tableCellAlignToStyle&&l==="align"&&typeof c=="string"&&r0.has(n.tagName)?i=c:s[l]=c}}if(i){const o=s.style||(s.style={});o[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=i}return s}function x0(e,n){const s={};for(const i of n.attributes)if(i.type==="mdxJsxExpressionAttribute")if(i.data&&i.data.estree&&e.evaluater){const o=i.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 fr(e,n.position);else{const r=i.name;let o;if(i.value&&typeof i.value=="object")if(i.value.data&&i.value.data.estree&&e.evaluater){const c=i.value.data.estree.body[0];c.type,o=e.evaluater.evaluateExpression(c.expression)}else fr(e,n.position);else o=i.value===null?!0:i.value;s[r]=o}return s}function md(e,n){const s=[];let i=-1;const r=e.passKeys?new Map:s0;for(;++i<n.children.length;){const o=n.children[i];let l;if(e.passKeys){const u=o.type==="element"?o.tagName:o.type==="mdxJsxFlowElement"||o.type==="mdxJsxTextElement"?o.name:void 0;if(u){const d=r.get(u)||0;l=u+"-"+d,r.set(u,d+1)}}const c=Wp(e,o,l);c!==void 0&&s.push(c)}return s}function b0(e,n,s){const i=V1(e.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=i.commaSeparated?P1(s):J1(s)),i.property==="style"){let r=typeof s=="object"?s:v0(e,String(s));return e.stylePropertyNameCase==="css"&&(r=y0(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&i.space?B1[i.property]||i.property:i.attribute,s]}}function v0(e,n){try{return t0(n,{reactCompat:!0})}catch(s){if(e.ignoreInvalidStyle)return{};const i=s,r=new Vn("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:i,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw r.file=e.filePath||void 0,r.url=Vp+"#cannot-parse-style-attribute",r}}function Gp(e,n,s){let i;if(!s)i={type:"Literal",value:n};else if(n.includes(".")){const r=n.split(".");let o=-1,l;for(;++o<r.length;){const c=Wu(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}i=l}else i=Wu(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(i.type==="Literal"){const r=i.value;return dd.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(i);fr(e)}function fr(e,n){const s=new Vn("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=Vp+"#cannot-handle-mdx-estrees-without-createevaluater",s}function y0(e){const n={};let s;for(s in e)dd.call(e,s)&&(n[k0(s)]=e[s]);return n}function k0(e){let n=e.replace(i0,j0);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function j0(e){return"-"+e.toLowerCase()}const El={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"]},w0={};function hd(e,n){const s=w0,i=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return Jp(e,i,r)}function Jp(e,n,s){if(N0(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 nm(e.children,n,s)}return Array.isArray(e)?nm(e,n,s):""}function nm(e,n,s){const i=[];let r=-1;for(;++r<e.length;)i[r]=Jp(e[r],n,s);return i.join("")}function N0(e){return!!(e&&typeof e=="object")}const sm=document.createElement("i");function pd(e){const n="&"+e+";";sm.innerHTML=n;const s=sm.textContent;return s.charCodeAt(s.length-1)===59&&e!=="semi"||s===n?!1:s}function fs(e,n,s,i){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,i.length<1e4)l=Array.from(i),l.unshift(n,s),e.splice(...l);else for(s&&e.splice(n,s);o<i.length;)l=i.slice(o,o+1e4),l.unshift(n,0),e.splice(...l),o+=1e4,n+=1e4}function Ns(e,n){return e.length>0?(fs(e,e.length,0,n),e):n}const im={}.hasOwnProperty;function Yp(e){const n={};let s=-1;for(;++s<e.length;)S0(n,e[s]);return n}function S0(e,n){let s;for(s in n){const r=(im.call(e,s)?e[s]:void 0)||(e[s]={}),o=n[s];let l;if(o)for(l in o){im.call(r,l)||(r[l]=[]);const c=o[l];C0(r[l],Array.isArray(c)?c:c?[c]:[])}}}function C0(e,n){let s=-1;const i=[];for(;++s<n.length;)(n[s].add==="after"?e:i).push(n[s]);fs(e,0,0,i)}function Qp(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 $s(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Qn=Ni(/[A-Za-z]/),Hn=Ni(/[\dA-Za-z]/),E0=Ni(/[#-'*+\--9=?A-Z^-~]/);function jo(e){return e!==null&&(e<32||e===127)}const Ic=Ni(/\d/),_0=Ni(/[\dA-Fa-f]/),M0=Ni(/[!-/:-@[-`{-~]/);function bt(e){return e!==null&&e<-2}function an(e){return e!==null&&(e<0||e===32)}function Bt(e){return e===-2||e===-1||e===32}const Vo=Ni(/\p{P}|\p{S}/u),Hi=Ni(/\s/);function Ni(e){return n;function n(s){return s!==null&&s>-1&&e.test(String.fromCharCode(s))}}function Ea(e){const n=[];let s=-1,i=0,r=0;for(;++s<e.length;){const o=e.charCodeAt(s);let l="";if(o===37&&Hn(e.charCodeAt(s+1))&&Hn(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(i,s),encodeURIComponent(l)),i=s+r+1,l=""),r&&(s+=r,r=0)}return n.join("")+e.slice(i)}function Wt(e,n,s,i){const r=i?i-1:Number.POSITIVE_INFINITY;let o=0;return l;function l(u){return Bt(u)?(e.enter(s),c(u)):n(u)}function c(u){return Bt(u)&&o++<r?(e.consume(u),c):(e.exit(s),n(u))}}const A0={tokenize:R0};function R0(e){const n=e.attempt(this.parser.constructs.contentInitial,i,r);let s;return n;function i(c){if(c===null){e.consume(c);return}return e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),Wt(e,n,"linePrefix")}function r(c){return e.enter("paragraph"),o(c)}function o(c){const u=e.enter("chunkText",{contentType:"text",previous:s});return s&&(s.next=u),s=u,l(c)}function l(c){if(c===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(c);return}return bt(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),l)}}const T0={tokenize:P0},am={tokenize:I0};function P0(e){const n=this,s=[];let i=0,r,o,l;return c;function c(S){if(i<s.length){const k=s[i];return n.containerState=k[1],e.attempt(k[0].continuation,u,d)(S)}return d(S)}function u(S){if(i++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&y();const k=n.events.length;let R=k,N;for(;R--;)if(n.events[R][0]==="exit"&&n.events[R][1].type==="chunkFlow"){N=n.events[R][1].end;break}b(i);let M=k;for(;M<n.events.length;)n.events[M][1].end={...N},M++;return fs(n.events,R+1,0,n.events.slice(k)),n.events.length=M,d(S)}return c(S)}function d(S){if(i===s.length){if(!r)return g(S);if(r.currentConstruct&&r.currentConstruct.concrete)return f(S);n.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return n.containerState={},e.check(am,m,h)(S)}function m(S){return r&&y(),b(i),g(S)}function h(S){return n.parser.lazy[n.now().line]=i!==s.length,l=n.now().offset,f(S)}function g(S){return n.containerState={},e.attempt(am,p,f)(S)}function p(S){return i++,s.push([n.currentConstruct,n.containerState]),g(S)}function f(S){if(S===null){r&&y(),b(0),e.consume(S);return}return r=r||n.parser.flow(n.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:o}),x(S)}function x(S){if(S===null){v(e.exit("chunkFlow"),!0),b(0),e.consume(S);return}return bt(S)?(e.consume(S),v(e.exit("chunkFlow")),i=0,n.interrupt=void 0,c):(e.consume(S),x)}function v(S,k){const R=n.sliceStream(S);if(k&&R.push(null),S.previous=o,o&&(o.next=S),o=S,r.defineSkip(S.start),r.write(R),n.parser.lazy[S.start.line]){let N=r.events.length;for(;N--;)if(r.events[N][1].start.offset<l&&(!r.events[N][1].end||r.events[N][1].end.offset>l))return;const M=n.events.length;let C=M,z,A;for(;C--;)if(n.events[C][0]==="exit"&&n.events[C][1].type==="chunkFlow"){if(z){A=n.events[C][1].end;break}z=!0}for(b(i),N=M;N<n.events.length;)n.events[N][1].end={...A},N++;fs(n.events,C+1,0,n.events.slice(M)),n.events.length=N}}function b(S){let k=s.length;for(;k-- >S;){const R=s[k];n.containerState=R[1],R[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 I0(e,n,s){return Wt(e,e.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function ga(e){if(e===null||an(e)||Hi(e))return 1;if(Vo(e))return 2}function Wo(e,n,s){const i=[];let r=-1;for(;++r<e.length;){const o=e[r].resolveAll;o&&!i.includes(o)&&(n=o(n,s),i.push(o))}return n}const $c={name:"attention",resolveAll:$0,tokenize:D0};function $0(e,n){let s=-1,i,r,o,l,c,u,d,m;for(;++s<e.length;)if(e[s][0]==="enter"&&e[s][1].type==="attentionSequence"&&e[s][1]._close){for(i=s;i--;)if(e[i][0]==="exit"&&e[i][1].type==="attentionSequence"&&e[i][1]._open&&n.sliceSerialize(e[i][1]).charCodeAt(0)===n.sliceSerialize(e[s][1]).charCodeAt(0)){if((e[i][1]._close||e[s][1]._open)&&(e[s][1].end.offset-e[s][1].start.offset)%3&&!((e[i][1].end.offset-e[i][1].start.offset+e[s][1].end.offset-e[s][1].start.offset)%3))continue;u=e[i][1].end.offset-e[i][1].start.offset>1&&e[s][1].end.offset-e[s][1].start.offset>1?2:1;const h={...e[i][1].end},g={...e[s][1].start};rm(h,-u),rm(g,u),l={type:u>1?"strongSequence":"emphasisSequence",start:h,end:{...e[i][1].end}},c={type:u>1?"strongSequence":"emphasisSequence",start:{...e[s][1].start},end:g},o={type:u>1?"strongText":"emphasisText",start:{...e[i][1].end},end:{...e[s][1].start}},r={type:u>1?"strong":"emphasis",start:{...l.start},end:{...c.end}},e[i][1].end={...l.start},e[s][1].start={...c.end},d=[],e[i][1].end.offset-e[i][1].start.offset&&(d=Ns(d,[["enter",e[i][1],n],["exit",e[i][1],n]])),d=Ns(d,[["enter",r,n],["enter",l,n],["exit",l,n],["enter",o,n]]),d=Ns(d,Wo(n.parser.constructs.insideSpan.null,e.slice(i+1,s),n)),d=Ns(d,[["exit",o,n],["enter",c,n],["exit",c,n],["exit",r,n]]),e[s][1].end.offset-e[s][1].start.offset?(m=2,d=Ns(d,[["enter",e[s][1],n],["exit",e[s][1],n]])):m=0,fs(e,i-1,s-i+3,d),s=i+d.length-m-2;break}}for(s=-1;++s<e.length;)e[s][1].type==="attentionSequence"&&(e[s][1].type="data");return e}function D0(e,n){const s=this.parser.constructs.attentionMarkers.null,i=this.previous,r=ga(i);let o;return l;function l(u){return o=u,e.enter("attentionSequence"),c(u)}function c(u){if(u===o)return e.consume(u),c;const d=e.exit("attentionSequence"),m=ga(u),h=!m||m===2&&r||s.includes(u),g=!r||r===2&&m||s.includes(i);return d._open=!!(o===42?h:h&&(r||!g)),d._close=!!(o===42?g:g&&(m||!h)),n(u)}}function rm(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const L0={name:"autolink",tokenize:z0};function z0(e,n,s){let i=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 Qn(p)?(e.consume(p),l):p===64?s(p):d(p)}function l(p){return p===43||p===45||p===46||Hn(p)?(i=1,c(p)):d(p)}function c(p){return p===58?(e.consume(p),i=0,u):(p===43||p===45||p===46||Hn(p))&&i++<32?(e.consume(p),c):(i=0,d(p))}function u(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||jo(p)?s(p):(e.consume(p),u)}function d(p){return p===64?(e.consume(p),m):E0(p)?(e.consume(p),d):s(p)}function m(p){return Hn(p)?h(p):s(p)}function h(p){return p===46?(e.consume(p),i=0,m):p===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),n):g(p)}function g(p){if((p===45||Hn(p))&&i++<63){const f=p===45?g:h;return e.consume(p),f}return s(p)}}const _r={partial:!0,tokenize:F0};function F0(e,n,s){return i;function i(o){return Bt(o)?Wt(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||bt(o)?n(o):s(o)}}const Xp={continuation:{tokenize:U0},exit:B0,name:"blockQuote",tokenize:O0};function O0(e,n,s){const i=this;return r;function r(l){if(l===62){const c=i.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 Bt(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(l))}}function U0(e,n,s){const i=this;return r;function r(l){return Bt(l)?Wt(e,o,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(Xp,n,s)(l)}}function B0(e){e.exit("blockQuote")}const Zp={name:"characterEscape",tokenize:H0};function H0(e,n,s){return i;function i(o){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(o),e.exit("escapeMarker"),r}function r(o){return M0(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):s(o)}}const ef={name:"characterReference",tokenize:q0};function q0(e,n,s){const i=this;let r=0,o,l;return c;function c(h){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),u}function u(h){return h===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(h),e.exit("characterReferenceMarkerNumeric"),d):(e.enter("characterReferenceValue"),o=31,l=Hn,m(h))}function d(h){return h===88||h===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(h),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),o=6,l=_0,m):(e.enter("characterReferenceValue"),o=7,l=Ic,m(h))}function m(h){if(h===59&&r){const g=e.exit("characterReferenceValue");return l===Hn&&!pd(i.sliceSerialize(g))?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 om={partial:!0,tokenize:W0},lm={concrete:!0,name:"codeFenced",tokenize:V0};function V0(e,n,s){const i=this,r={partial:!0,tokenize:R};let o=0,l=0,c;return u;function u(N){return d(N)}function d(N){const M=i.events[i.events.length-1];return o=M&&M[1].type==="linePrefix"?M[2].sliceSerialize(M[1],!0).length:0,c=N,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),m(N)}function m(N){return N===c?(l++,e.consume(N),m):l<3?s(N):(e.exit("codeFencedFenceSequence"),Bt(N)?Wt(e,h,"whitespace")(N):h(N))}function h(N){return N===null||bt(N)?(e.exit("codeFencedFence"),i.interrupt?n(N):e.check(om,x,k)(N)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),g(N))}function g(N){return N===null||bt(N)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(N)):Bt(N)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),Wt(e,p,"whitespace")(N)):N===96&&N===c?s(N):(e.consume(N),g)}function p(N){return N===null||bt(N)?h(N):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),f(N))}function f(N){return N===null||bt(N)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),h(N)):N===96&&N===c?s(N):(e.consume(N),f)}function x(N){return e.attempt(r,k,v)(N)}function v(N){return e.enter("lineEnding"),e.consume(N),e.exit("lineEnding"),b}function b(N){return o>0&&Bt(N)?Wt(e,y,"linePrefix",o+1)(N):y(N)}function y(N){return N===null||bt(N)?e.check(om,x,k)(N):(e.enter("codeFlowValue"),S(N))}function S(N){return N===null||bt(N)?(e.exit("codeFlowValue"),y(N)):(e.consume(N),S)}function k(N){return e.exit("codeFenced"),n(N)}function R(N,M,C){let z=0;return A;function A(_){return N.enter("lineEnding"),N.consume(_),N.exit("lineEnding"),P}function P(_){return N.enter("codeFencedFence"),Bt(_)?Wt(N,F,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(_):F(_)}function F(_){return _===c?(N.enter("codeFencedFenceSequence"),W(_)):C(_)}function W(_){return _===c?(z++,N.consume(_),W):z>=l?(N.exit("codeFencedFenceSequence"),Bt(_)?Wt(N,$,"whitespace")(_):$(_)):C(_)}function $(_){return _===null||bt(_)?(N.exit("codeFencedFence"),M(_)):C(_)}}}function W0(e,n,s){const i=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 i.parser.lazy[i.now().line]?s(l):n(l)}}const _l={name:"codeIndented",tokenize:G0},K0={partial:!0,tokenize:J0};function G0(e,n,s){const i=this;return r;function r(d){return e.enter("codeIndented"),Wt(e,o,"linePrefix",5)(d)}function o(d){const m=i.events[i.events.length-1];return m&&m[1].type==="linePrefix"&&m[2].sliceSerialize(m[1],!0).length>=4?l(d):s(d)}function l(d){return d===null?u(d):bt(d)?e.attempt(K0,l,u)(d):(e.enter("codeFlowValue"),c(d))}function c(d){return d===null||bt(d)?(e.exit("codeFlowValue"),l(d)):(e.consume(d),c)}function u(d){return e.exit("codeIndented"),n(d)}}function J0(e,n,s){const i=this;return r;function r(l){return i.parser.lazy[i.now().line]?s(l):bt(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r):Wt(e,o,"linePrefix",5)(l)}function o(l){const c=i.events[i.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?n(l):bt(l)?r(l):s(l)}}const Y0={name:"codeText",previous:X0,resolve:Q0,tokenize:Z0};function Q0(e){let n=e.length-4,s=3,i,r;if((e[s][1].type==="lineEnding"||e[s][1].type==="space")&&(e[n][1].type==="lineEnding"||e[n][1].type==="space")){for(i=s;++i<n;)if(e[i][1].type==="codeTextData"){e[s][1].type="codeTextPadding",e[n][1].type="codeTextPadding",s+=2,n-=2;break}}for(i=s-1,n++;++i<=n;)r===void 0?i!==n&&e[i][1].type!=="lineEnding"&&(r=i):(i===n||e[i][1].type==="lineEnding")&&(e[r][1].type="codeTextData",i!==r+2&&(e[r][1].end=e[i-1][1].end,e.splice(r+2,i-r-2),n-=i-r-2,i=r+2),r=void 0);return e}function X0(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function Z0(e,n,s){let i=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),i++,c):(e.exit("codeTextSequence"),u(h))}function u(h){return h===null?s(h):h===32?(e.enter("space"),e.consume(h),e.exit("space"),u):h===96?(o=e.enter("codeTextSequence"),r=0,m(h)):bt(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),u):(e.enter("codeTextData"),d(h))}function d(h){return h===null||h===32||h===96||bt(h)?(e.exit("codeTextData"),u(h)):(e.consume(h),d)}function m(h){return h===96?(e.consume(h),r++,m):r===i?(e.exit("codeTextSequence"),e.exit("codeText"),n(h)):(o.type="codeTextData",d(h))}}class eS{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 i=s??Number.POSITIVE_INFINITY;return i<this.left.length?this.left.slice(n,i):n>this.left.length?this.right.slice(this.right.length-i+this.left.length,this.right.length-n+this.left.length).reverse():this.left.slice(n).concat(this.right.slice(this.right.length-i+this.left.length).reverse())}splice(n,s,i){const r=s||0;this.setCursor(Math.trunc(n));const o=this.right.splice(this.right.length-r,Number.POSITIVE_INFINITY);return i&&Oa(this.left,i),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),Oa(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),Oa(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);Oa(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);Oa(this.left,s.reverse())}}}function Oa(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 tf(e){const n={};let s=-1,i,r,o,l,c,u,d;const m=new eS(e);for(;++s<m.length;){for(;s in n;)s=n[s];if(i=m.get(s),s&&i[1].type==="chunkFlow"&&m.get(s-1)[1].type==="listItemPrefix"&&(u=i[1]._tokenizer.events,o=0,o<u.length&&u[o][1].type==="lineEndingBlank"&&(o+=2),o<u.length&&u[o][1].type==="content"))for(;++o<u.length&&u[o][1].type!=="content";)u[o][1].type==="chunkText"&&(u[o][1]._isInFirstContentOfListItem=!0,o++);if(i[0]==="enter")i[1].contentType&&(Object.assign(n,tS(m,s)),s=n[s],d=!0);else if(i[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&&(i[1].end={...m.get(r)[1].start},c=m.slice(r,s),c.unshift(i),m.splice(r,s-r+1,c))}}return fs(e,0,Number.POSITIVE_INFINITY,m.slice(0)),!d}function tS(e,n){const s=e.get(n)[1],i=e.get(n)[2];let r=n-1;const o=[];let l=s._tokenizer;l||(l=i.parser[s.contentType](s.start),s._contentTypeTextTrailing&&(l._contentTypeTextTrailing=!0));const c=l.events,u=[],d={};let m,h,g=-1,p=s,f=0,x=0;const v=[x];for(;p;){for(;e.get(++r)[1]!==p;);o.push(r),p._tokenizer||(m=i.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;++g<c.length;)c[g][0]==="exit"&&c[g-1][0]==="enter"&&c[g][1].type===c[g-1][1].type&&c[g][1].start.line!==c[g][1].end.line&&(x=g+1,v.push(x),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(l.events=[],p?(p._tokenizer=void 0,p.previous=void 0):v.pop(),g=v.length;g--;){const b=c.slice(v[g],v[g+1]),y=o.pop();u.push([y,y+b.length-1]),e.splice(y,2,b)}for(u.reverse(),g=-1;++g<u.length;)d[f+u[g][0]]=f+u[g][1],f+=u[g][1]-u[g][0]-1;return d}const nS={resolve:iS,tokenize:aS},sS={partial:!0,tokenize:rS};function iS(e){return tf(e),e}function aS(e,n){let s;return i;function i(c){return e.enter("content"),s=e.enter("chunkContent",{contentType:"content"}),r(c)}function r(c){return c===null?o(c):bt(c)?e.check(sS,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 rS(e,n,s){const i=this;return r;function r(l){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),Wt(e,o,"linePrefix")}function o(l){if(l===null||bt(l))return s(l);const c=i.events[i.events.length-1];return!i.parser.constructs.disable.null.includes("codeIndented")&&c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?n(l):e.interrupt(i.parser.constructs.flow,s,n)(l)}}function nf(e,n,s,i,r,o,l,c,u){const d=u||Number.POSITIVE_INFINITY;let m=0;return h;function h(b){return b===60?(e.enter(i),e.enter(r),e.enter(o),e.consume(b),e.exit(o),g):b===null||b===32||b===41||jo(b)?s(b):(e.enter(i),e.enter(l),e.enter(c),e.enter("chunkString",{contentType:"string"}),x(b))}function g(b){return b===62?(e.enter(o),e.consume(b),e.exit(o),e.exit(r),e.exit(i),n):(e.enter(c),e.enter("chunkString",{contentType:"string"}),p(b))}function p(b){return b===62?(e.exit("chunkString"),e.exit(c),g(b)):b===null||b===60||bt(b)?s(b):(e.consume(b),b===92?f:p)}function f(b){return b===60||b===62||b===92?(e.consume(b),p):p(b)}function x(b){return!m&&(b===null||b===41||an(b))?(e.exit("chunkString"),e.exit(c),e.exit(l),e.exit(i),n(b)):m<d&&b===40?(e.consume(b),m++,x):b===41?(e.consume(b),m--,x):b===null||b===32||b===40||jo(b)?s(b):(e.consume(b),b===92?v:x)}function v(b){return b===40||b===41||b===92?(e.consume(b),x):x(b)}}function sf(e,n,s,i,r,o){const l=this;let c=0,u;return d;function d(p){return e.enter(i),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&&!u||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(i),n):bt(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||bt(p)||c++>999?(e.exit("chunkString"),m(p)):(e.consume(p),u||(u=!Bt(p)),p===92?g:h)}function g(p){return p===91||p===92||p===93?(e.consume(p),c++,h):h(p)}}function af(e,n,s,i,r,o){let l;return c;function c(g){return g===34||g===39||g===40?(e.enter(i),e.enter(r),e.consume(g),e.exit(r),l=g===40?41:g,u):s(g)}function u(g){return g===l?(e.enter(r),e.consume(g),e.exit(r),e.exit(i),n):(e.enter(o),d(g))}function d(g){return g===l?(e.exit(o),u(l)):g===null?s(g):bt(g)?(e.enter("lineEnding"),e.consume(g),e.exit("lineEnding"),Wt(e,d,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),m(g))}function m(g){return g===l||g===null||bt(g)?(e.exit("chunkString"),d(g)):(e.consume(g),g===92?h:m)}function h(g){return g===l||g===92?(e.consume(g),m):m(g)}}function rr(e,n){let s;return i;function i(r){return bt(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s=!0,i):Bt(r)?Wt(e,i,s?"linePrefix":"lineSuffix")(r):n(r)}}const oS={name:"definition",tokenize:cS},lS={partial:!0,tokenize:dS};function cS(e,n,s){const i=this;let r;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return sf.call(i,e,c,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function c(p){return r=$s(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)),p===58?(e.enter("definitionMarker"),e.consume(p),e.exit("definitionMarker"),u):s(p)}function u(p){return an(p)?rr(e,d)(p):d(p)}function d(p){return nf(e,m,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function m(p){return e.attempt(lS,h,h)(p)}function h(p){return Bt(p)?Wt(e,g,"whitespace")(p):g(p)}function g(p){return p===null||bt(p)?(e.exit("definition"),i.parser.defined.push(r),n(p)):s(p)}}function dS(e,n,s){return i;function i(c){return an(c)?rr(e,r)(c):s(c)}function r(c){return af(e,o,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return Bt(c)?Wt(e,l,"whitespace")(c):l(c)}function l(c){return c===null||bt(c)?n(c):s(c)}}const uS={name:"hardBreakEscape",tokenize:mS};function mS(e,n,s){return i;function i(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return bt(o)?(e.exit("hardBreakEscape"),n(o)):s(o)}}const hS={name:"headingAtx",resolve:pS,tokenize:fS};function pS(e,n){let s=e.length-2,i=3,r,o;return e[i][1].type==="whitespace"&&(i+=2),s-2>i&&e[s][1].type==="whitespace"&&(s-=2),e[s][1].type==="atxHeadingSequence"&&(i===s-1||s-4>i&&e[s-2][1].type==="whitespace")&&(s-=i+1===s?2:4),s>i&&(r={type:"atxHeadingText",start:e[i][1].start,end:e[s][1].end},o={type:"chunkText",start:e[i][1].start,end:e[s][1].end,contentType:"text"},fs(e,i,s-i+1,[["enter",r,n],["enter",o,n],["exit",o,n],["exit",r,n]])),e}function fS(e,n,s){let i=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&&i++<6?(e.consume(m),l):m===null||an(m)?(e.exit("atxHeadingSequence"),c(m)):s(m)}function c(m){return m===35?(e.enter("atxHeadingSequence"),u(m)):m===null||bt(m)?(e.exit("atxHeading"),n(m)):Bt(m)?Wt(e,c,"whitespace")(m):(e.enter("atxHeadingText"),d(m))}function u(m){return m===35?(e.consume(m),u):(e.exit("atxHeadingSequence"),c(m))}function d(m){return m===null||m===35||an(m)?(e.exit("atxHeadingText"),c(m)):(e.consume(m),d)}}const gS=["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"],cm=["pre","script","style","textarea"],xS={concrete:!0,name:"htmlFlow",resolveTo:yS,tokenize:kS},bS={partial:!0,tokenize:wS},vS={partial:!0,tokenize:jS};function yS(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 kS(e,n,s){const i=this;let r,o,l,c,u;return d;function d(w){return m(w)}function m(w){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(w),h}function h(w){return w===33?(e.consume(w),g):w===47?(e.consume(w),o=!0,x):w===63?(e.consume(w),r=3,i.interrupt?n:E):Qn(w)?(e.consume(w),l=String.fromCharCode(w),v):s(w)}function g(w){return w===45?(e.consume(w),r=2,p):w===91?(e.consume(w),r=5,c=0,f):Qn(w)?(e.consume(w),r=4,i.interrupt?n:E):s(w)}function p(w){return w===45?(e.consume(w),i.interrupt?n:E):s(w)}function f(w){const q="CDATA[";return w===q.charCodeAt(c++)?(e.consume(w),c===q.length?i.interrupt?n:F:f):s(w)}function x(w){return Qn(w)?(e.consume(w),l=String.fromCharCode(w),v):s(w)}function v(w){if(w===null||w===47||w===62||an(w)){const q=w===47,G=l.toLowerCase();return!q&&!o&&cm.includes(G)?(r=1,i.interrupt?n(w):F(w)):gS.includes(l.toLowerCase())?(r=6,q?(e.consume(w),b):i.interrupt?n(w):F(w)):(r=7,i.interrupt&&!i.parser.lazy[i.now().line]?s(w):o?y(w):S(w))}return w===45||Hn(w)?(e.consume(w),l+=String.fromCharCode(w),v):s(w)}function b(w){return w===62?(e.consume(w),i.interrupt?n:F):s(w)}function y(w){return Bt(w)?(e.consume(w),y):A(w)}function S(w){return w===47?(e.consume(w),A):w===58||w===95||Qn(w)?(e.consume(w),k):Bt(w)?(e.consume(w),S):A(w)}function k(w){return w===45||w===46||w===58||w===95||Hn(w)?(e.consume(w),k):R(w)}function R(w){return w===61?(e.consume(w),N):Bt(w)?(e.consume(w),R):S(w)}function N(w){return w===null||w===60||w===61||w===62||w===96?s(w):w===34||w===39?(e.consume(w),u=w,M):Bt(w)?(e.consume(w),N):C(w)}function M(w){return w===u?(e.consume(w),u=null,z):w===null||bt(w)?s(w):(e.consume(w),M)}function C(w){return w===null||w===34||w===39||w===47||w===60||w===61||w===62||w===96||an(w)?R(w):(e.consume(w),C)}function z(w){return w===47||w===62||Bt(w)?S(w):s(w)}function A(w){return w===62?(e.consume(w),P):s(w)}function P(w){return w===null||bt(w)?F(w):Bt(w)?(e.consume(w),P):s(w)}function F(w){return w===45&&r===2?(e.consume(w),I):w===60&&r===1?(e.consume(w),O):w===62&&r===4?(e.consume(w),D):w===63&&r===3?(e.consume(w),E):w===93&&r===5?(e.consume(w),Q):bt(w)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(bS,T,W)(w)):w===null||bt(w)?(e.exit("htmlFlowData"),W(w)):(e.consume(w),F)}function W(w){return e.check(vS,$,T)(w)}function $(w){return e.enter("lineEnding"),e.consume(w),e.exit("lineEnding"),_}function _(w){return w===null||bt(w)?W(w):(e.enter("htmlFlowData"),F(w))}function I(w){return w===45?(e.consume(w),E):F(w)}function O(w){return w===47?(e.consume(w),l="",J):F(w)}function J(w){if(w===62){const q=l.toLowerCase();return cm.includes(q)?(e.consume(w),D):F(w)}return Qn(w)&&l.length<8?(e.consume(w),l+=String.fromCharCode(w),J):F(w)}function Q(w){return w===93?(e.consume(w),E):F(w)}function E(w){return w===62?(e.consume(w),D):w===45&&r===2?(e.consume(w),E):F(w)}function D(w){return w===null||bt(w)?(e.exit("htmlFlowData"),T(w)):(e.consume(w),D)}function T(w){return e.exit("htmlFlow"),n(w)}}function jS(e,n,s){const i=this;return r;function r(l){return bt(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),o):s(l)}function o(l){return i.parser.lazy[i.now().line]?s(l):n(l)}}function wS(e,n,s){return i;function i(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(_r,n,s)}}const NS={name:"htmlText",tokenize:SS};function SS(e,n,s){const i=this;let r,o,l;return c;function c(E){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(E),u}function u(E){return E===33?(e.consume(E),d):E===47?(e.consume(E),R):E===63?(e.consume(E),S):Qn(E)?(e.consume(E),C):s(E)}function d(E){return E===45?(e.consume(E),m):E===91?(e.consume(E),o=0,f):Qn(E)?(e.consume(E),y):s(E)}function m(E){return E===45?(e.consume(E),p):s(E)}function h(E){return E===null?s(E):E===45?(e.consume(E),g):bt(E)?(l=h,O(E)):(e.consume(E),h)}function g(E){return E===45?(e.consume(E),p):h(E)}function p(E){return E===62?I(E):E===45?g(E):h(E)}function f(E){const D="CDATA[";return E===D.charCodeAt(o++)?(e.consume(E),o===D.length?x:f):s(E)}function x(E){return E===null?s(E):E===93?(e.consume(E),v):bt(E)?(l=x,O(E)):(e.consume(E),x)}function v(E){return E===93?(e.consume(E),b):x(E)}function b(E){return E===62?I(E):E===93?(e.consume(E),b):x(E)}function y(E){return E===null||E===62?I(E):bt(E)?(l=y,O(E)):(e.consume(E),y)}function S(E){return E===null?s(E):E===63?(e.consume(E),k):bt(E)?(l=S,O(E)):(e.consume(E),S)}function k(E){return E===62?I(E):S(E)}function R(E){return Qn(E)?(e.consume(E),N):s(E)}function N(E){return E===45||Hn(E)?(e.consume(E),N):M(E)}function M(E){return bt(E)?(l=M,O(E)):Bt(E)?(e.consume(E),M):I(E)}function C(E){return E===45||Hn(E)?(e.consume(E),C):E===47||E===62||an(E)?z(E):s(E)}function z(E){return E===47?(e.consume(E),I):E===58||E===95||Qn(E)?(e.consume(E),A):bt(E)?(l=z,O(E)):Bt(E)?(e.consume(E),z):I(E)}function A(E){return E===45||E===46||E===58||E===95||Hn(E)?(e.consume(E),A):P(E)}function P(E){return E===61?(e.consume(E),F):bt(E)?(l=P,O(E)):Bt(E)?(e.consume(E),P):z(E)}function F(E){return E===null||E===60||E===61||E===62||E===96?s(E):E===34||E===39?(e.consume(E),r=E,W):bt(E)?(l=F,O(E)):Bt(E)?(e.consume(E),F):(e.consume(E),$)}function W(E){return E===r?(e.consume(E),r=void 0,_):E===null?s(E):bt(E)?(l=W,O(E)):(e.consume(E),W)}function $(E){return E===null||E===34||E===39||E===60||E===61||E===96?s(E):E===47||E===62||an(E)?z(E):(e.consume(E),$)}function _(E){return E===47||E===62||an(E)?z(E):s(E)}function I(E){return E===62?(e.consume(E),e.exit("htmlTextData"),e.exit("htmlText"),n):s(E)}function O(E){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(E),e.exit("lineEnding"),J}function J(E){return Bt(E)?Wt(e,Q,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(E):Q(E)}function Q(E){return e.enter("htmlTextData"),l(E)}}const fd={name:"labelEnd",resolveAll:MS,resolveTo:AS,tokenize:RS},CS={tokenize:TS},ES={tokenize:PS},_S={tokenize:IS};function MS(e){let n=-1;const s=[];for(;++n<e.length;){const i=e[n][1];if(s.push(e[n]),i.type==="labelImage"||i.type==="labelLink"||i.type==="labelEnd"){const r=i.type==="labelImage"?4:2;i.type="data",n+=r}}return e.length!==s.length&&fs(e,0,e.length,s),e}function AS(e,n){let s=e.length,i=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")){i=2;break}}else r.type==="labelEnd"&&(l=s);const u={type:e[o][1].type==="labelLink"?"link":"image",start:{...e[o][1].start},end:{...e[e.length-1][1].end}},d={type:"label",start:{...e[o][1].start},end:{...e[l][1].end}},m={type:"labelText",start:{...e[o+i+2][1].end},end:{...e[l-2][1].start}};return c=[["enter",u,n],["enter",d,n]],c=Ns(c,e.slice(o+1,o+i+3)),c=Ns(c,[["enter",m,n]]),c=Ns(c,Wo(n.parser.constructs.insideSpan.null,e.slice(o+i+4,l-3),n)),c=Ns(c,[["exit",m,n],e[l-2],e[l-1],["exit",d,n]]),c=Ns(c,e.slice(l+1)),c=Ns(c,[["exit",u,n]]),fs(e,o,e.length,c),e}function RS(e,n,s){const i=this;let r=i.events.length,o,l;for(;r--;)if((i.events[r][1].type==="labelImage"||i.events[r][1].type==="labelLink")&&!i.events[r][1]._balanced){o=i.events[r][1];break}return c;function c(g){return o?o._inactive?h(g):(l=i.parser.defined.includes($s(i.sliceSerialize({start:o.end,end:i.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(g),e.exit("labelMarker"),e.exit("labelEnd"),u):s(g)}function u(g){return g===40?e.attempt(CS,m,l?m:h)(g):g===91?e.attempt(ES,m,l?d:h)(g):l?m(g):h(g)}function d(g){return e.attempt(_S,m,h)(g)}function m(g){return n(g)}function h(g){return o._balanced=!0,s(g)}}function TS(e,n,s){return i;function i(h){return e.enter("resource"),e.enter("resourceMarker"),e.consume(h),e.exit("resourceMarker"),r}function r(h){return an(h)?rr(e,o)(h):o(h)}function o(h){return h===41?m(h):nf(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function l(h){return an(h)?rr(e,u)(h):m(h)}function c(h){return s(h)}function u(h){return h===34||h===39||h===40?af(e,d,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):m(h)}function d(h){return an(h)?rr(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 PS(e,n,s){const i=this;return r;function r(c){return sf.call(i,e,o,l,"reference","referenceMarker","referenceString")(c)}function o(c){return i.parser.defined.includes($s(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)))?n(c):s(c)}function l(c){return s(c)}}function IS(e,n,s){return i;function i(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 $S={name:"labelStartImage",resolveAll:fd.resolveAll,tokenize:DS};function DS(e,n,s){const i=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 i.parser.constructs?s(c):n(c)}}const LS={name:"labelStartLink",resolveAll:fd.resolveAll,tokenize:zS};function zS(e,n,s){const i=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 i.parser.constructs?s(l):n(l)}}const Ml={name:"lineEnding",tokenize:FS};function FS(e,n){return s;function s(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),Wt(e,n,"linePrefix")}}const ro={name:"thematicBreak",tokenize:OS};function OS(e,n,s){let i=0,r;return o;function o(d){return e.enter("thematicBreak"),l(d)}function l(d){return r=d,c(d)}function c(d){return d===r?(e.enter("thematicBreakSequence"),u(d)):i>=3&&(d===null||bt(d))?(e.exit("thematicBreak"),n(d)):s(d)}function u(d){return d===r?(e.consume(d),i++,u):(e.exit("thematicBreakSequence"),Bt(d)?Wt(e,c,"whitespace")(d):c(d))}}const rs={continuation:{tokenize:qS},exit:WS,name:"list",tokenize:HS},US={partial:!0,tokenize:KS},BS={partial:!0,tokenize:VS};function HS(e,n,s){const i=this,r=i.events[i.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 f=i.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(f==="listUnordered"?!i.containerState.marker||p===i.containerState.marker:Ic(p)){if(i.containerState.type||(i.containerState.type=f,e.enter(f,{_container:!0})),f==="listUnordered")return e.enter("listItemPrefix"),p===42||p===45?e.check(ro,s,d)(p):d(p);if(!i.interrupt||p===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),u(p)}return s(p)}function u(p){return Ic(p)&&++l<10?(e.consume(p),u):(!i.interrupt||l<2)&&(i.containerState.marker?p===i.containerState.marker:p===41||p===46)?(e.exit("listItemValue"),d(p)):s(p)}function d(p){return e.enter("listItemMarker"),e.consume(p),e.exit("listItemMarker"),i.containerState.marker=i.containerState.marker||p,e.check(_r,i.interrupt?s:m,e.attempt(US,g,h))}function m(p){return i.containerState.initialBlankLine=!0,o++,g(p)}function h(p){return Bt(p)?(e.enter("listItemPrefixWhitespace"),e.consume(p),e.exit("listItemPrefixWhitespace"),g):s(p)}function g(p){return i.containerState.size=o+i.sliceSerialize(e.exit("listItemPrefix"),!0).length,n(p)}}function qS(e,n,s){const i=this;return i.containerState._closeFlow=void 0,e.check(_r,r,o);function r(c){return i.containerState.furtherBlankLines=i.containerState.furtherBlankLines||i.containerState.initialBlankLine,Wt(e,n,"listItemIndent",i.containerState.size+1)(c)}function o(c){return i.containerState.furtherBlankLines||!Bt(c)?(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,l(c)):(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,e.attempt(BS,n,l)(c))}function l(c){return i.containerState._closeFlow=!0,i.interrupt=void 0,Wt(e,e.attempt(rs,n,s),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function VS(e,n,s){const i=this;return Wt(e,r,"listItemIndent",i.containerState.size+1);function r(o){const l=i.events[i.events.length-1];return l&&l[1].type==="listItemIndent"&&l[2].sliceSerialize(l[1],!0).length===i.containerState.size?n(o):s(o)}}function WS(e){e.exit(this.containerState.type)}function KS(e,n,s){const i=this;return Wt(e,r,"listItemPrefixWhitespace",i.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function r(o){const l=i.events[i.events.length-1];return!Bt(o)&&l&&l[1].type==="listItemPrefixWhitespace"?n(o):s(o)}}const dm={name:"setextUnderline",resolveTo:GS,tokenize:JS};function GS(e,n){let s=e.length,i,r,o;for(;s--;)if(e[s][0]==="enter"){if(e[s][1].type==="content"){i=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[i][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[i][1],n]),e[i][1].end={...e[o][1].end}):e[i][1]=l,e.push(["exit",l,n]),e}function JS(e,n,s){const i=this;let r;return o;function o(d){let m=i.events.length,h;for(;m--;)if(i.events[m][1].type!=="lineEnding"&&i.events[m][1].type!=="linePrefix"&&i.events[m][1].type!=="content"){h=i.events[m][1].type==="paragraph";break}return!i.parser.lazy[i.now().line]&&(i.interrupt||h)?(e.enter("setextHeadingLine"),r=d,l(d)):s(d)}function l(d){return e.enter("setextHeadingLineSequence"),c(d)}function c(d){return d===r?(e.consume(d),c):(e.exit("setextHeadingLineSequence"),Bt(d)?Wt(e,u,"lineSuffix")(d):u(d))}function u(d){return d===null||bt(d)?(e.exit("setextHeadingLine"),n(d)):s(d)}}const YS={tokenize:QS};function QS(e){const n=this,s=e.attempt(_r,i,e.attempt(this.parser.constructs.flowInitial,r,Wt(e,e.attempt(this.parser.constructs.flow,r,e.attempt(nS,r)),"linePrefix")));return s;function i(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 XS={resolveAll:of()},ZS=rf("string"),eC=rf("text");function rf(e){return{resolveAll:of(e==="text"?tC:void 0),tokenize:n};function n(s){const i=this,r=this.parser.constructs[e],o=s.attempt(r,l,c);return l;function l(m){return d(m)?o(m):c(m)}function c(m){if(m===null){s.consume(m);return}return s.enter("data"),s.consume(m),u}function u(m){return d(m)?(s.exit("data"),o(m)):(s.consume(m),u)}function d(m){if(m===null)return!0;const h=r[m];let g=-1;if(h)for(;++g<h.length;){const p=h[g];if(!p.previous||p.previous.call(i,i.previous))return!0}return!1}}}function of(e){return n;function n(s,i){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,i):s}}function tC(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 i=e[s-1][1],r=n.sliceStream(i);let o=r.length,l=-1,c=0,u;for(;o--;){const d=r[o];if(typeof d=="string"){for(l=d.length;d.charCodeAt(l-1)===32;)c++,l--;if(l)break;l=-1}else if(d===-2)u=!0,c++;else if(d!==-1){o++;break}}if(n._contentTypeTextTrailing&&s===e.length&&(c=0),c){const d={type:s===e.length||u||c<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:o?l:i.start._bufferIndex+l,_index:i.start._index+o,line:i.end.line,column:i.end.column-c,offset:i.end.offset-c},end:{...i.end}};i.end={...d.start},i.start.offset===i.end.offset?Object.assign(i,d):(e.splice(s,0,["enter",d,n],["exit",d,n]),s+=2)}s++}return e}const nC={42:rs,43:rs,45:rs,48:rs,49:rs,50:rs,51:rs,52:rs,53:rs,54:rs,55:rs,56:rs,57:rs,62:Xp},sC={91:oS},iC={[-2]:_l,[-1]:_l,32:_l},aC={35:hS,42:ro,45:[dm,ro],60:xS,61:dm,95:ro,96:lm,126:lm},rC={38:ef,92:Zp},oC={[-5]:Ml,[-4]:Ml,[-3]:Ml,33:$S,38:ef,42:$c,60:[L0,NS],91:LS,92:[uS,Zp],93:fd,95:$c,96:Y0},lC={null:[$c,XS]},cC={null:[42,95]},dC={null:[]},uC=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:cC,contentInitial:sC,disable:dC,document:nC,flow:aC,flowInitial:iC,insideSpan:lC,string:rC,text:oC},Symbol.toStringTag,{value:"Module"}));function mC(e,n,s){let i={_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 u={attempt:M(R),check:M(N),consume:y,enter:S,exit:k,interrupt:M(N,{interrupt:!0})},d={code:null,containerState:{},defineSkip:x,events:[],now:f,parser:e,previous:null,sliceSerialize:g,sliceStream:p,write:h};let m=n.tokenize.call(d,u);return n.resolveAll&&o.push(n),d;function h(P){return l=Ns(l,P),v(),l[l.length-1]!==null?[]:(C(n,0),d.events=Wo(o,d.events,d),d.events)}function g(P,F){return pC(p(P),F)}function p(P){return hC(l,P)}function f(){const{_bufferIndex:P,_index:F,line:W,column:$,offset:_}=i;return{_bufferIndex:P,_index:F,line:W,column:$,offset:_}}function x(P){r[P.line]=P.column,A()}function v(){let P;for(;i._index<l.length;){const F=l[i._index];if(typeof F=="string")for(P=i._index,i._bufferIndex<0&&(i._bufferIndex=0);i._index===P&&i._bufferIndex<F.length;)b(F.charCodeAt(i._bufferIndex));else b(F)}}function b(P){m=m(P)}function y(P){bt(P)?(i.line++,i.column=1,i.offset+=P===-3?2:1,A()):P!==-1&&(i.column++,i.offset++),i._bufferIndex<0?i._index++:(i._bufferIndex++,i._bufferIndex===l[i._index].length&&(i._bufferIndex=-1,i._index++)),d.previous=P}function S(P,F){const W=F||{};return W.type=P,W.start=f(),d.events.push(["enter",W,d]),c.push(W),W}function k(P){const F=c.pop();return F.end=f(),d.events.push(["exit",F,d]),F}function R(P,F){C(P,F.from)}function N(P,F){F.restore()}function M(P,F){return W;function W($,_,I){let O,J,Q,E;return Array.isArray($)?T($):"tokenize"in $?T([$]):D($);function D(me){return ce;function ce(ae){const pe=ae!==null&&me[ae],U=ae!==null&&me.null,Ne=[...Array.isArray(pe)?pe:pe?[pe]:[],...Array.isArray(U)?U:U?[U]:[]];return T(Ne)(ae)}}function T(me){return O=me,J=0,me.length===0?I:w(me[J])}function w(me){return ce;function ce(ae){return E=z(),Q=me,me.partial||(d.currentConstruct=me),me.name&&d.parser.constructs.disable.null.includes(me.name)?G():me.tokenize.call(F?Object.assign(Object.create(d),F):d,u,q,G)(ae)}}function q(me){return P(Q,E),_}function G(me){return E.restore(),++J<O.length?w(O[J]):I}}}function C(P,F){P.resolveAll&&!o.includes(P)&&o.push(P),P.resolve&&fs(d.events,F,d.events.length-F,P.resolve(d.events.slice(F),d)),P.resolveTo&&(d.events=P.resolveTo(d.events,d))}function z(){const P=f(),F=d.previous,W=d.currentConstruct,$=d.events.length,_=Array.from(c);return{from:$,restore:I};function I(){i=P,d.previous=F,d.currentConstruct=W,d.events.length=$,c=_,A()}}function A(){i.line in r&&i.column<2&&(i.column=r[i.line],i.offset+=r[i.line]-1)}}function hC(e,n){const s=n.start._index,i=n.start._bufferIndex,r=n.end._index,o=n.end._bufferIndex;let l;if(s===r)l=[e[s].slice(i,o)];else{if(l=e.slice(s,r),i>-1){const c=l[0];typeof c=="string"?l[0]=c.slice(i):l.shift()}o>0&&l.push(e[r].slice(0,o))}return l}function pC(e,n){let s=-1;const i=[];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=`
|
|
620
|
+
`;break}case-3:{l=`\r
|
|
621
|
+
`;break}case-2:{l=n?" ":" ";break}case-1:{if(!n&&r)continue;l=" ";break}default:l=String.fromCharCode(o)}r=o===-2,i.push(l)}return i.join("")}function fC(e){const i={constructs:Yp([uC,...(e||{}).extensions||[]]),content:r(A0),defined:[],document:r(T0),flow:r(YS),lazy:{},string:r(ZS),text:r(eC)};return i;function r(o){return l;function l(c){return mC(i,o,c)}}}function gC(e){for(;!tf(e););return e}const um=/[\0\t\n\r]/g;function xC(){let e=1,n="",s=!0,i;return r;function r(o,l,c){const u=[];let d,m,h,g,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(um.lastIndex=h,d=um.exec(o),g=d&&d.index!==void 0?d.index:o.length,p=o.charCodeAt(g),!d){n=o.slice(h);break}if(p===10&&h===g&&i)u.push(-3),i=void 0;else switch(i&&(u.push(-5),i=void 0),h<g&&(u.push(o.slice(h,g)),e+=g-h),p){case 0:{u.push(65533),e++;break}case 9:{for(m=Math.ceil(e/4)*4,u.push(-2);e++<m;)u.push(-1);break}case 10:{u.push(-4),e=1;break}default:i=!0,e=1}h=g+1}return c&&(i&&u.push(-5),n&&u.push(n),u.push(null)),u}}const bC=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function vC(e){return e.replace(bC,yC)}function yC(e,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),o=r===120||r===88;return Qp(s.slice(o?2:1),o?16:10)}return pd(s)||e}const lf={}.hasOwnProperty;function kC(e,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),jC(s)(gC(fC(s).document().write(xC()(e,n,!0))))}function jC(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(Ke),autolinkProtocol:z,autolinkEmail:z,atxHeading:o(ve),blockQuote:o(U),characterEscape:z,characterReference:z,codeFenced:o(Ne),codeFencedFenceInfo:l,codeFencedFenceMeta:l,codeIndented:o(Ne,l),codeText:o(ne,l),codeTextData:z,data:z,codeFlowValue:z,definition:o(xe),definitionDestinationString:l,definitionLabelString:l,definitionTitleString:l,emphasis:o(le),hardBreakEscape:o(ee),hardBreakTrailing:o(ee),htmlFlow:o(Ee,l),htmlFlowData:z,htmlText:o(Ee,l),htmlTextData:z,image:o(Fe),label:l,link:o(Ke),listItem:o(Xe),listItemValue:g,listOrdered:o(Ze,h),listUnordered:o(Ze),paragraph:o(Qe),reference:w,referenceString:l,resourceDestinationString:l,resourceTitleString:l,setextHeading:o(ve),strong:o(it),thematicBreak:o(Ge)},exit:{atxHeading:u(),atxHeadingSequence:R,autolink:u(),autolinkEmail:pe,autolinkProtocol:ae,blockQuote:u(),characterEscapeValue:A,characterReferenceMarkerHexadecimal:G,characterReferenceMarkerNumeric:G,characterReferenceValue:me,characterReference:ce,codeFenced:u(v),codeFencedFence:x,codeFencedFenceInfo:p,codeFencedFenceMeta:f,codeFlowValue:A,codeIndented:u(b),codeText:u(_),codeTextData:A,data:A,definition:u(),definitionDestinationString:k,definitionLabelString:y,definitionTitleString:S,emphasis:u(),hardBreakEscape:u(F),hardBreakTrailing:u(F),htmlFlow:u(W),htmlFlowData:A,htmlText:u($),htmlTextData:A,image:u(O),label:Q,labelText:J,lineEnding:P,link:u(I),listItem:u(),listOrdered:u(),listUnordered:u(),paragraph:u(),referenceString:q,resourceDestinationString:E,resourceTitleString:D,resource:T,setextHeading:u(C),setextHeadingLineSequence:M,setextHeadingText:N,strong:u(),thematicBreak:u()}};cf(n,(e||{}).mdastExtensions||[]);const s={};return i;function i(se){let ye={type:"root",children:[]};const Z={stack:[ye],tokenStack:[],config:n,enter:c,exit:d,buffer:l,resume:m,data:s},Te=[];let ze=-1;for(;++ze<se.length;)if(se[ze][1].type==="listOrdered"||se[ze][1].type==="listUnordered")if(se[ze][0]==="enter")Te.push(ze);else{const be=Te.pop();ze=r(se,be,ze)}for(ze=-1;++ze<se.length;){const be=n[se[ze][0]];lf.call(be,se[ze][1].type)&&be[se[ze][1].type].call(Object.assign({sliceSerialize:se[ze][2].sliceSerialize},Z),se[ze][1])}if(Z.tokenStack.length>0){const be=Z.tokenStack[Z.tokenStack.length-1];(be[1]||mm).call(Z,void 0,be[0])}for(ye.position={start:gi(se.length>0?se[0][1].start:{line:1,column:1,offset:0}),end:gi(se.length>0?se[se.length-2][1].end:{line:1,column:1,offset:0})},ze=-1;++ze<n.transforms.length;)ye=n.transforms[ze](ye)||ye;return ye}function r(se,ye,Z){let Te=ye-1,ze=-1,be=!1,Me,Be,lt,je;for(;++Te<=Z;){const ie=se[Te];switch(ie[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{ie[0]==="enter"?ze++:ze--,je=void 0;break}case"lineEndingBlank":{ie[0]==="enter"&&(Me&&!je&&!ze&&!lt&&(lt=Te),je=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:je=void 0}if(!ze&&ie[0]==="enter"&&ie[1].type==="listItemPrefix"||ze===-1&&ie[0]==="exit"&&(ie[1].type==="listUnordered"||ie[1].type==="listOrdered")){if(Me){let Ae=Te;for(Be=void 0;Ae--;){const he=se[Ae];if(he[1].type==="lineEnding"||he[1].type==="lineEndingBlank"){if(he[0]==="exit")continue;Be&&(se[Be][1].type="lineEndingBlank",be=!0),he[1].type="lineEnding",Be=Ae}else if(!(he[1].type==="linePrefix"||he[1].type==="blockQuotePrefix"||he[1].type==="blockQuotePrefixWhitespace"||he[1].type==="blockQuoteMarker"||he[1].type==="listItemIndent"))break}lt&&(!Be||lt<Be)&&(Me._spread=!0),Me.end=Object.assign({},Be?se[Be][1].start:ie[1].end),se.splice(Be||Te,0,["exit",Me,ie[2]]),Te++,Z++}if(ie[1].type==="listItemPrefix"){const Ae={type:"listItem",_spread:!1,start:Object.assign({},ie[1].start),end:void 0};Me=Ae,se.splice(Te,0,["enter",Ae,ie[2]]),Te++,Z++,lt=void 0,je=!0}}}return se[ye][1]._spread=be,Z}function o(se,ye){return Z;function Z(Te){c.call(this,se(Te),Te),ye&&ye.call(this,Te)}}function l(){this.stack.push({type:"fragment",children:[]})}function c(se,ye,Z){this.stack[this.stack.length-1].children.push(se),this.stack.push(se),this.tokenStack.push([ye,Z||void 0]),se.position={start:gi(ye.start),end:void 0}}function u(se){return ye;function ye(Z){se&&se.call(this,Z),d.call(this,Z)}}function d(se,ye){const Z=this.stack.pop(),Te=this.tokenStack.pop();if(Te)Te[0].type!==se.type&&(ye?ye.call(this,se,Te[0]):(Te[1]||mm).call(this,se,Te[0]));else throw new Error("Cannot close `"+se.type+"` ("+ar({start:se.start,end:se.end})+"): it’s not open");Z.position.end=gi(se.end)}function m(){return hd(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function g(se){if(this.data.expectingFirstListItemValue){const ye=this.stack[this.stack.length-2];ye.start=Number.parseInt(this.sliceSerialize(se),10),this.data.expectingFirstListItemValue=void 0}}function p(){const se=this.resume(),ye=this.stack[this.stack.length-1];ye.lang=se}function f(){const se=this.resume(),ye=this.stack[this.stack.length-1];ye.meta=se}function x(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function v(){const se=this.resume(),ye=this.stack[this.stack.length-1];ye.value=se.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function b(){const se=this.resume(),ye=this.stack[this.stack.length-1];ye.value=se.replace(/(\r?\n|\r)$/g,"")}function y(se){const ye=this.resume(),Z=this.stack[this.stack.length-1];Z.label=ye,Z.identifier=$s(this.sliceSerialize(se)).toLowerCase()}function S(){const se=this.resume(),ye=this.stack[this.stack.length-1];ye.title=se}function k(){const se=this.resume(),ye=this.stack[this.stack.length-1];ye.url=se}function R(se){const ye=this.stack[this.stack.length-1];if(!ye.depth){const Z=this.sliceSerialize(se).length;ye.depth=Z}}function N(){this.data.setextHeadingSlurpLineEnding=!0}function M(se){const ye=this.stack[this.stack.length-1];ye.depth=this.sliceSerialize(se).codePointAt(0)===61?1:2}function C(){this.data.setextHeadingSlurpLineEnding=void 0}function z(se){const Z=this.stack[this.stack.length-1].children;let Te=Z[Z.length-1];(!Te||Te.type!=="text")&&(Te=Ie(),Te.position={start:gi(se.start),end:void 0},Z.push(Te)),this.stack.push(Te)}function A(se){const ye=this.stack.pop();ye.value+=this.sliceSerialize(se),ye.position.end=gi(se.end)}function P(se){const ye=this.stack[this.stack.length-1];if(this.data.atHardBreak){const Z=ye.children[ye.children.length-1];Z.position.end=gi(se.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(ye.type)&&(z.call(this,se),A.call(this,se))}function F(){this.data.atHardBreak=!0}function W(){const se=this.resume(),ye=this.stack[this.stack.length-1];ye.value=se}function $(){const se=this.resume(),ye=this.stack[this.stack.length-1];ye.value=se}function _(){const se=this.resume(),ye=this.stack[this.stack.length-1];ye.value=se}function I(){const se=this.stack[this.stack.length-1];if(this.data.inReference){const ye=this.data.referenceType||"shortcut";se.type+="Reference",se.referenceType=ye,delete se.url,delete se.title}else delete se.identifier,delete se.label;this.data.referenceType=void 0}function O(){const se=this.stack[this.stack.length-1];if(this.data.inReference){const ye=this.data.referenceType||"shortcut";se.type+="Reference",se.referenceType=ye,delete se.url,delete se.title}else delete se.identifier,delete se.label;this.data.referenceType=void 0}function J(se){const ye=this.sliceSerialize(se),Z=this.stack[this.stack.length-2];Z.label=vC(ye),Z.identifier=$s(ye).toLowerCase()}function Q(){const se=this.stack[this.stack.length-1],ye=this.resume(),Z=this.stack[this.stack.length-1];if(this.data.inReference=!0,Z.type==="link"){const Te=se.children;Z.children=Te}else Z.alt=ye}function E(){const se=this.resume(),ye=this.stack[this.stack.length-1];ye.url=se}function D(){const se=this.resume(),ye=this.stack[this.stack.length-1];ye.title=se}function T(){this.data.inReference=void 0}function w(){this.data.referenceType="collapsed"}function q(se){const ye=this.resume(),Z=this.stack[this.stack.length-1];Z.label=ye,Z.identifier=$s(this.sliceSerialize(se)).toLowerCase(),this.data.referenceType="full"}function G(se){this.data.characterReferenceType=se.type}function me(se){const ye=this.sliceSerialize(se),Z=this.data.characterReferenceType;let Te;Z?(Te=Qp(ye,Z==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Te=pd(ye);const ze=this.stack[this.stack.length-1];ze.value+=Te}function ce(se){const ye=this.stack.pop();ye.position.end=gi(se.end)}function ae(se){A.call(this,se);const ye=this.stack[this.stack.length-1];ye.url=this.sliceSerialize(se)}function pe(se){A.call(this,se);const ye=this.stack[this.stack.length-1];ye.url="mailto:"+this.sliceSerialize(se)}function U(){return{type:"blockquote",children:[]}}function Ne(){return{type:"code",lang:null,meta:null,value:""}}function ne(){return{type:"inlineCode",value:""}}function xe(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function le(){return{type:"emphasis",children:[]}}function ve(){return{type:"heading",depth:0,children:[]}}function ee(){return{type:"break"}}function Ee(){return{type:"html",value:""}}function Fe(){return{type:"image",title:null,url:"",alt:null}}function Ke(){return{type:"link",title:null,url:"",children:[]}}function Ze(se){return{type:"list",ordered:se.type==="listOrdered",start:null,spread:se._spread,children:[]}}function Xe(se){return{type:"listItem",spread:se._spread,checked:null,children:[]}}function Qe(){return{type:"paragraph",children:[]}}function it(){return{type:"strong",children:[]}}function Ie(){return{type:"text",value:""}}function Ge(){return{type:"thematicBreak"}}}function gi(e){return{line:e.line,column:e.column,offset:e.offset}}function cf(e,n){let s=-1;for(;++s<n.length;){const i=n[s];Array.isArray(i)?cf(e,i):wC(e,i)}}function wC(e,n){let s;for(s in n)if(lf.call(n,s))switch(s){case"canContainEols":{const i=n[s];i&&e[s].push(...i);break}case"transforms":{const i=n[s];i&&e[s].push(...i);break}case"enter":case"exit":{const i=n[s];i&&Object.assign(e[s],i);break}}}function mm(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+ar({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+ar({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+ar({start:n.start,end:n.end})+") is still open")}function NC(e){const n=this;n.parser=s;function s(i){return kC(i,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function SC(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 CC(e,n){const s={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,s),[e.applyData(n,s),{type:"text",value:`
|
|
622
|
+
`}]}function EC(e,n){const s=n.value?n.value+`
|
|
623
|
+
`:"",i={},r=n.lang?n.lang.split(/\s+/):[];r.length>0&&(i.className=["language-"+r[0]]);let o={type:"element",tagName:"code",properties:i,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 _C(e,n){const s={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function MC(e,n){const s={type:"element",tagName:"em",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function AC(e,n){const s=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=String(n.identifier).toUpperCase(),r=Ea(i.toLowerCase()),o=e.footnoteOrder.indexOf(i);let l,c=e.footnoteCounts.get(i);c===void 0?(c=0,e.footnoteOrder.push(i),l=e.footnoteOrder.length):l=o+1,c+=1,e.footnoteCounts.set(i,c);const u={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,u);const d={type:"element",tagName:"sup",properties:{},children:[u]};return e.patch(n,d),e.applyData(n,d)}function RC(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 TC(e,n){if(e.options.allowDangerousHtml){const s={type:"raw",value:n.value};return e.patch(n,s),e.applyData(n,s)}}function df(e,n){const s=n.referenceType;let i="]";if(s==="collapsed"?i+="[]":s==="full"&&(i+="["+(n.label||n.identifier)+"]"),n.type==="imageReference")return[{type:"text",value:"!["+n.alt+i}];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+=i:r.push({type:"text",value:i}),r}function PC(e,n){const s=String(n.identifier).toUpperCase(),i=e.definitionById.get(s);if(!i)return df(e,n);const r={src:Ea(i.url||""),alt:n.alt};i.title!==null&&i.title!==void 0&&(r.title=i.title);const o={type:"element",tagName:"img",properties:r,children:[]};return e.patch(n,o),e.applyData(n,o)}function IC(e,n){const s={src:Ea(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 i={type:"element",tagName:"img",properties:s,children:[]};return e.patch(n,i),e.applyData(n,i)}function $C(e,n){const s={type:"text",value:n.value.replace(/\r?\n|\r/g," ")};e.patch(n,s);const i={type:"element",tagName:"code",properties:{},children:[s]};return e.patch(n,i),e.applyData(n,i)}function DC(e,n){const s=String(n.identifier).toUpperCase(),i=e.definitionById.get(s);if(!i)return df(e,n);const r={href:Ea(i.url||"")};i.title!==null&&i.title!==void 0&&(r.title=i.title);const o={type:"element",tagName:"a",properties:r,children:e.all(n)};return e.patch(n,o),e.applyData(n,o)}function LC(e,n){const s={href:Ea(n.url)};n.title!==null&&n.title!==void 0&&(s.title=n.title);const i={type:"element",tagName:"a",properties:s,children:e.all(n)};return e.patch(n,i),e.applyData(n,i)}function zC(e,n,s){const i=e.all(n),r=s?FC(s):uf(n),o={},l=[];if(typeof n.checked=="boolean"){const m=i[0];let h;m&&m.type==="element"&&m.tagName==="p"?h=m:(h={type:"element",tagName:"p",properties:{},children:[]},i.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<i.length;){const m=i[c];(r||c!==0||m.type!=="element"||m.tagName!=="p")&&l.push({type:"text",value:`
|
|
624
|
+
`}),m.type==="element"&&m.tagName==="p"&&!r?l.push(...m.children):l.push(m)}const u=i[i.length-1];u&&(r||u.type!=="element"||u.tagName!=="p")&&l.push({type:"text",value:`
|
|
625
|
+
`});const d={type:"element",tagName:"li",properties:o,children:l};return e.patch(n,d),e.applyData(n,d)}function FC(e){let n=!1;if(e.type==="list"){n=e.spread||!1;const s=e.children;let i=-1;for(;!n&&++i<s.length;)n=uf(s[i])}return n}function uf(e){const n=e.spread;return n??e.children.length>1}function OC(e,n){const s={},i=e.all(n);let r=-1;for(typeof n.start=="number"&&n.start!==1&&(s.start=n.start);++r<i.length;){const l=i[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(i,!0)};return e.patch(n,o),e.applyData(n,o)}function UC(e,n){const s={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function BC(e,n){const s={type:"root",children:e.wrap(e.all(n))};return e.patch(n,s),e.applyData(n,s)}function HC(e,n){const s={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function qC(e,n){const s=e.all(n),i=s.shift(),r=[];if(i){const l={type:"element",tagName:"thead",properties:{},children:e.wrap([i],!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=cd(n.children[1]),u=Hp(n.children[n.children.length-1]);c&&u&&(l.position={start:c,end:u}),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 VC(e,n,s){const i=s?s.children:void 0,o=(i?i.indexOf(n):1)===0?"th":"td",l=s&&s.type==="table"?s.align:void 0,c=l?l.length:n.children.length;let u=-1;const d=[];for(;++u<c;){const h=n.children[u],g={},p=l?l[u]:void 0;p&&(g.align=p);let f={type:"element",tagName:o,properties:g,children:[]};h&&(f.children=e.all(h),e.patch(h,f),f=e.applyData(h,f)),d.push(f)}const m={type:"element",tagName:"tr",properties:{},children:e.wrap(d,!0)};return e.patch(n,m),e.applyData(n,m)}function WC(e,n){const s={type:"element",tagName:"td",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}const hm=9,pm=32;function KC(e){const n=String(e),s=/\r?\n|\r/g;let i=s.exec(n),r=0;const o=[];for(;i;)o.push(fm(n.slice(r,i.index),r>0,!0),i[0]),r=i.index+i[0].length,i=s.exec(n);return o.push(fm(n.slice(r),r>0,!1)),o.join("")}function fm(e,n,s){let i=0,r=e.length;if(n){let o=e.codePointAt(i);for(;o===hm||o===pm;)i++,o=e.codePointAt(i)}if(s){let o=e.codePointAt(r-1);for(;o===hm||o===pm;)r--,o=e.codePointAt(r-1)}return r>i?e.slice(i,r):""}function GC(e,n){const s={type:"text",value:KC(String(n.value))};return e.patch(n,s),e.applyData(n,s)}function JC(e,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,s),e.applyData(n,s)}const YC={blockquote:SC,break:CC,code:EC,delete:_C,emphasis:MC,footnoteReference:AC,heading:RC,html:TC,imageReference:PC,image:IC,inlineCode:$C,linkReference:DC,link:LC,listItem:zC,list:OC,paragraph:UC,root:BC,strong:HC,table:qC,tableCell:WC,tableRow:VC,text:GC,thematicBreak:JC,toml:Kr,yaml:Kr,definition:Kr,footnoteDefinition:Kr};function Kr(){}const mf=-1,Ko=0,or=1,wo=2,gd=3,xd=4,bd=5,vd=6,hf=7,pf=8,gm=typeof self=="object"?self:globalThis,QC=(e,n)=>{const s=(r,o)=>(e.set(o,r),r),i=r=>{if(e.has(r))return e.get(r);const[o,l]=n[r];switch(o){case Ko:case mf:return s(l,r);case or:{const c=s([],r);for(const u of l)c.push(i(u));return c}case wo:{const c=s({},r);for(const[u,d]of l)c[i(u)]=i(d);return c}case gd:return s(new Date(l),r);case xd:{const{source:c,flags:u}=l;return s(new RegExp(c,u),r)}case bd:{const c=s(new Map,r);for(const[u,d]of l)c.set(i(u),i(d));return c}case vd:{const c=s(new Set,r);for(const u of l)c.add(i(u));return c}case hf:{const{name:c,message:u}=l;return s(new gm[c](u),r)}case pf: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 gm[o](l),r)};return i},xm=e=>QC(new Map,e)(0),sa="",{toString:XC}={},{keys:ZC}=Object,Ua=e=>{const n=typeof e;if(n!=="object"||!e)return[Ko,n];const s=XC.call(e).slice(8,-1);switch(s){case"Array":return[or,sa];case"Object":return[wo,sa];case"Date":return[gd,sa];case"RegExp":return[xd,sa];case"Map":return[bd,sa];case"Set":return[vd,sa];case"DataView":return[or,s]}return s.includes("Array")?[or,s]:s.includes("Error")?[hf,s]:[wo,s]},Gr=([e,n])=>e===Ko&&(n==="function"||n==="symbol"),e2=(e,n,s,i)=>{const r=(l,c)=>{const u=i.push(l)-1;return s.set(c,u),u},o=l=>{if(s.has(l))return s.get(l);let[c,u]=Ua(l);switch(c){case Ko:{let m=l;switch(u){case"bigint":c=pf,m=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+u);m=null;break;case"undefined":return r([mf],l)}return r([c,m],l)}case or:{if(u){let g=l;return u==="DataView"?g=new Uint8Array(l.buffer):u==="ArrayBuffer"&&(g=new Uint8Array(l)),r([u,[...g]],l)}const m=[],h=r([c,m],l);for(const g of l)m.push(o(g));return h}case wo:{if(u)switch(u){case"BigInt":return r([u,l.toString()],l);case"Boolean":case"Number":case"String":return r([u,l.valueOf()],l)}if(n&&"toJSON"in l)return o(l.toJSON());const m=[],h=r([c,m],l);for(const g of ZC(l))(e||!Gr(Ua(l[g])))&&m.push([o(g),o(l[g])]);return h}case gd:return r([c,l.toISOString()],l);case xd:{const{source:m,flags:h}=l;return r([c,{source:m,flags:h}],l)}case bd:{const m=[],h=r([c,m],l);for(const[g,p]of l)(e||!(Gr(Ua(g))||Gr(Ua(p))))&&m.push([o(g),o(p)]);return h}case vd:{const m=[],h=r([c,m],l);for(const g of l)(e||!Gr(Ua(g)))&&m.push(o(g));return h}}const{message:d}=l;return r([c,{name:u,message:d}],l)};return o},bm=(e,{json:n,lossy:s}={})=>{const i=[];return e2(!(n||s),!!n,new Map,i)(e),i},No=typeof structuredClone=="function"?(e,n)=>n&&("json"in n||"lossy"in n)?xm(bm(e,n)):structuredClone(e):(e,n)=>xm(bm(e,n));function t2(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 n2(e,n){return"Back to reference "+(e+1)+(n>1?"-"+n:"")}function s2(e){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=e.options.footnoteBackContent||t2,i=e.options.footnoteBackLabel||n2,r=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",l=e.options.footnoteLabelProperties||{className:["sr-only"]},c=[];let u=-1;for(;++u<e.footnoteOrder.length;){const d=e.footnoteById.get(e.footnoteOrder[u]);if(!d)continue;const m=e.all(d),h=String(d.identifier).toUpperCase(),g=Ea(h.toLowerCase());let p=0;const f=[],x=e.footnoteCounts.get(h);for(;x!==void 0&&++p<=x;){f.length>0&&f.push({type:"text",value:" "});let y=typeof s=="string"?s:s(u,p);typeof y=="string"&&(y={type:"text",value:y}),f.push({type:"element",tagName:"a",properties:{href:"#"+n+"fnref-"+g+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof i=="string"?i:i(u,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(...f)}else m.push(...f);const b={type:"element",tagName:"li",properties:{id:n+"fn-"+g},children:e.wrap(m,!0)};e.patch(d,b),c.push(b)}if(c.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...No(l),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
|
|
626
|
+
`},{type:"element",tagName:"ol",properties:{},children:e.wrap(c,!0)},{type:"text",value:`
|
|
627
|
+
`}]}}const Go=(function(e){if(e==null)return o2;if(typeof e=="function")return Jo(e);if(typeof e=="object")return Array.isArray(e)?i2(e):a2(e);if(typeof e=="string")return r2(e);throw new Error("Expected function, string, or object as test")});function i2(e){const n=[];let s=-1;for(;++s<e.length;)n[s]=Go(e[s]);return Jo(i);function i(...r){let o=-1;for(;++o<n.length;)if(n[o].apply(this,r))return!0;return!1}}function a2(e){const n=e;return Jo(s);function s(i){const r=i;let o;for(o in e)if(r[o]!==n[o])return!1;return!0}}function r2(e){return Jo(n);function n(s){return s&&s.type===e}}function Jo(e){return n;function n(s,i,r){return!!(l2(s)&&e.call(this,s,typeof i=="number"?i:void 0,r||void 0))}}function o2(){return!0}function l2(e){return e!==null&&typeof e=="object"&&"type"in e}const ff=[],c2=!0,Dc=!1,d2="skip";function gf(e,n,s,i){let r;typeof n=="function"&&typeof s!="function"?(i=s,s=n):r=n;const o=Go(r),l=i?-1:1;c(e,void 0,[])();function c(u,d,m){const h=u&&typeof u=="object"?u:{};if(typeof h.type=="string"){const p=typeof h.tagName=="string"?h.tagName:typeof h.name=="string"?h.name:void 0;Object.defineProperty(g,"name",{value:"node ("+(u.type+(p?"<"+p+">":""))+")"})}return g;function g(){let p=ff,f,x,v;if((!n||o(u,d,m[m.length-1]||void 0))&&(p=u2(s(u,m)),p[0]===Dc))return p;if("children"in u&&u.children){const b=u;if(b.children&&p[0]!==d2)for(x=(i?b.children.length:-1)+l,v=m.concat(b);x>-1&&x<b.children.length;){const y=b.children[x];if(f=c(y,x,v)(),f[0]===Dc)return f;x=typeof f[1]=="number"?f[1]:x+l}}return p}}}function u2(e){return Array.isArray(e)?e:typeof e=="number"?[c2,e]:e==null?ff:[e]}function yd(e,n,s,i){let r,o,l;typeof n=="function"&&typeof s!="function"?(o=void 0,l=n,r=s):(o=n,l=s,r=i),gf(e,o,c,r);function c(u,d){const m=d[d.length-1],h=m?m.children.indexOf(u):void 0;return l(u,h,m)}}const Lc={}.hasOwnProperty,m2={};function h2(e,n){const s=n||m2,i=new Map,r=new Map,o=new Map,l={...YC,...s.handlers},c={all:d,applyData:f2,definitionById:i,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:l,one:u,options:s,patch:p2,wrap:x2};return yd(e,function(m){if(m.type==="definition"||m.type==="footnoteDefinition"){const h=m.type==="definition"?i:r,g=String(m.identifier).toUpperCase();h.has(g)||h.set(g,m)}}),c;function u(m,h){const g=m.type,p=c.handlers[g];if(Lc.call(c.handlers,g)&&p)return p(c,m,h);if(c.options.passThrough&&c.options.passThrough.includes(g)){if("children"in m){const{children:x,...v}=m,b=No(v);return b.children=c.all(m),b}return No(m)}return(c.options.unknownHandler||g2)(c,m,h)}function d(m){const h=[];if("children"in m){const g=m.children;let p=-1;for(;++p<g.length;){const f=c.one(g[p],m);if(f){if(p&&g[p-1].type==="break"&&(!Array.isArray(f)&&f.type==="text"&&(f.value=vm(f.value)),!Array.isArray(f)&&f.type==="element")){const x=f.children[0];x&&x.type==="text"&&(x.value=vm(x.value))}Array.isArray(f)?h.push(...f):h.push(f)}}}return h}}function p2(e,n){e.position&&(n.position=n0(e))}function f2(e,n){let s=n;if(e&&e.data){const i=e.data.hName,r=e.data.hChildren,o=e.data.hProperties;if(typeof i=="string")if(s.type==="element")s.tagName=i;else{const l="children"in s?s.children:[s];s={type:"element",tagName:i,properties:{},children:l}}s.type==="element"&&o&&Object.assign(s.properties,No(o)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function g2(e,n){const s=n.data||{},i="value"in n&&!(Lc.call(s,"hProperties")||Lc.call(s,"hChildren"))?{type:"text",value:n.value}:{type:"element",tagName:"div",properties:{},children:e.all(n)};return e.patch(n,i),e.applyData(n,i)}function x2(e,n){const s=[];let i=-1;for(n&&s.push({type:"text",value:`
|
|
628
|
+
`});++i<e.length;)i&&s.push({type:"text",value:`
|
|
629
|
+
`}),s.push(e[i]);return n&&e.length>0&&s.push({type:"text",value:`
|
|
630
|
+
`}),s}function vm(e){let n=0,s=e.charCodeAt(n);for(;s===9||s===32;)n++,s=e.charCodeAt(n);return e.slice(n)}function ym(e,n){const s=h2(e,n),i=s.one(e,void 0),r=s2(s),o=Array.isArray(i)?{type:"root",children:i}:i||{type:"root",children:[]};return r&&o.children.push({type:"text",value:`
|
|
631
|
+
`},r),o}function b2(e,n){return e&&"run"in e?async function(s,i){const r=ym(s,{file:i,...n});await e.run(r,i)}:function(s,i){return ym(s,{file:i,...e||n})}}function km(e){if(e)throw e}var Al,jm;function v2(){if(jm)return Al;jm=1;var e=Object.prototype.hasOwnProperty,n=Object.prototype.toString,s=Object.defineProperty,i=Object.getOwnPropertyDescriptor,r=function(d){return typeof Array.isArray=="function"?Array.isArray(d):n.call(d)==="[object Array]"},o=function(d){if(!d||n.call(d)!=="[object Object]")return!1;var m=e.call(d,"constructor"),h=d.constructor&&d.constructor.prototype&&e.call(d.constructor.prototype,"isPrototypeOf");if(d.constructor&&!m&&!h)return!1;var g;for(g in d);return typeof g>"u"||e.call(d,g)},l=function(d,m){s&&m.name==="__proto__"?s(d,m.name,{enumerable:!0,configurable:!0,value:m.newValue,writable:!0}):d[m.name]=m.newValue},c=function(d,m){if(m==="__proto__")if(e.call(d,m)){if(i)return i(d,m).value}else return;return d[m]};return Al=function u(){var d,m,h,g,p,f,x=arguments[0],v=1,b=arguments.length,y=!1;for(typeof x=="boolean"&&(y=x,x=arguments[1]||{},v=2),(x==null||typeof x!="object"&&typeof x!="function")&&(x={});v<b;++v)if(d=arguments[v],d!=null)for(m in d)h=c(x,m),g=c(d,m),x!==g&&(y&&g&&(o(g)||(p=r(g)))?(p?(p=!1,f=h&&r(h)?h:[]):f=h&&o(h)?h:{},l(x,{name:m,newValue:u(y,f,g)})):typeof g<"u"&&l(x,{name:m,newValue:g}));return x},Al}var y2=v2();const Rl=$h(y2);function zc(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 k2(){const e=[],n={run:s,use:i};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(u,...d){const m=e[++o];let h=-1;if(u){l(u);return}for(;++h<r.length;)(d[h]===null||d[h]===void 0)&&(d[h]=r[h]);r=d,m?j2(m,c)(...d):l(null,...d)}}function i(r){if(typeof r!="function")throw new TypeError("Expected `middelware` to be a function, not "+r);return e.push(r),n}}function j2(e,n){let s;return i;function i(...l){const c=e.length>l.length;let u;c&&l.push(r);try{u=e.apply(this,l)}catch(d){const m=d;if(c&&s)throw m;return r(m)}c||(u&&u.then&&typeof u.then=="function"?u.then(o,r):u instanceof Error?r(u):o(u))}function r(l,...c){s||(s=!0,n(l,...c))}function o(l){r(null,l)}}const Vs={basename:w2,dirname:N2,extname:S2,join:C2,sep:"/"};function w2(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');Mr(e);let s=0,i=-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 i<0&&(o=!0,i=r+1);return i<0?"":e.slice(s,i)}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&&(i=r):(c=-1,i=l));return s===i?i=l:i<0&&(i=e.length),e.slice(s,i)}function N2(e){if(Mr(e),e.length===0)return".";let n=-1,s=e.length,i;for(;--s;)if(e.codePointAt(s)===47){if(i){n=s;break}}else i||(i=!0);return n<0?e.codePointAt(0)===47?"/":".":n===1&&e.codePointAt(0)===47?"//":e.slice(0,n)}function S2(e){Mr(e);let n=e.length,s=-1,i=0,r=-1,o=0,l;for(;n--;){const c=e.codePointAt(n);if(c===47){if(l){i=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===i+1?"":e.slice(r,s)}function C2(...e){let n=-1,s;for(;++n<e.length;)Mr(e[n]),e[n]&&(s=s===void 0?e[n]:s+"/"+e[n]);return s===void 0?".":E2(s)}function E2(e){Mr(e);const n=e.codePointAt(0)===47;let s=_2(e,!n);return s.length===0&&!n&&(s="."),s.length>0&&e.codePointAt(e.length-1)===47&&(s+="/"),n?"/"+s:s}function _2(e,n){let s="",i=0,r=-1,o=0,l=-1,c,u;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||i!==2||s.codePointAt(s.length-1)!==46||s.codePointAt(s.length-2)!==46){if(s.length>2){if(u=s.lastIndexOf("/"),u!==s.length-1){u<0?(s="",i=0):(s=s.slice(0,u),i=s.length-1-s.lastIndexOf("/")),r=l,o=0;continue}}else if(s.length>0){s="",i=0,r=l,o=0;continue}}n&&(s=s.length>0?s+"/..":"..",i=2)}else s.length>0?s+="/"+e.slice(r+1,l):s=e.slice(r+1,l),i=l-r-1;r=l,o=0}else c===46&&o>-1?o++:o=-1}return s}function Mr(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const M2={cwd:A2};function A2(){return"/"}function Fc(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function R2(e){if(typeof e=="string")e=new URL(e);else if(!Fc(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 T2(e)}function T2(e){if(e.hostname!==""){const i=new TypeError('File URL host must be "localhost" or empty on darwin');throw i.code="ERR_INVALID_FILE_URL_HOST",i}const n=e.pathname;let s=-1;for(;++s<n.length;)if(n.codePointAt(s)===37&&n.codePointAt(s+1)===50){const i=n.codePointAt(s+2);if(i===70||i===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 Tl=["history","path","basename","stem","extname","dirname"];class xf{constructor(n){let s;n?Fc(n)?s={path:n}:typeof n=="string"||P2(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":M2.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let i=-1;for(;++i<Tl.length;){const o=Tl[i];o in s&&s[o]!==void 0&&s[o]!==null&&(this[o]=o==="history"?[...s[o]]:s[o])}let r;for(r in s)Tl.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?Vs.basename(this.path):void 0}set basename(n){Il(n,"basename"),Pl(n,"basename"),this.path=Vs.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?Vs.dirname(this.path):void 0}set dirname(n){wm(this.basename,"dirname"),this.path=Vs.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?Vs.extname(this.path):void 0}set extname(n){if(Pl(n,"extname"),wm(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=Vs.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){Fc(n)&&(n=R2(n)),Il(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?Vs.basename(this.path,this.extname):void 0}set stem(n){Il(n,"stem"),Pl(n,"stem"),this.path=Vs.join(this.dirname||"",n+(this.extname||""))}fail(n,s,i){const r=this.message(n,s,i);throw r.fatal=!0,r}info(n,s,i){const r=this.message(n,s,i);return r.fatal=void 0,r}message(n,s,i){const r=new Vn(n,s,i);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 Pl(e,n){if(e&&e.includes(Vs.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+Vs.sep+"`")}function Il(e,n){if(!e)throw new Error("`"+n+"` cannot be empty")}function wm(e,n){if(!e)throw new Error("Setting `"+n+"` requires `path` to be set too")}function P2(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const I2=(function(e){const i=this.constructor.prototype,r=i[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,i),o}),$2={}.hasOwnProperty;class kd extends I2{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=k2()}copy(){const n=new kd;let s=-1;for(;++s<this.attachers.length;){const i=this.attachers[s];n.use(...i)}return n.data(Rl(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(Ll("data",this.frozen),this.namespace[n]=s,this):$2.call(this.namespace,n)&&this.namespace[n]||void 0:n?(Ll("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,...i]=this.attachers[this.freezeIndex];if(i[0]===!1)continue;i[0]===!0&&(i[0]=void 0);const r=s.call(n,...i);typeof r=="function"&&this.transformers.use(r)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(n){this.freeze();const s=Jr(n),i=this.parser||this.Parser;return $l("parse",i),i(String(s),s)}process(n,s){const i=this;return this.freeze(),$l("process",this.parser||this.Parser),Dl("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(o,l){const c=Jr(n),u=i.parse(c);i.run(u,c,function(m,h,g){if(m||!h||!g)return d(m);const p=h,f=i.stringify(p,g);z2(f)?g.value=f:g.result=f,d(m,g)});function d(m,h){m||!h?l(m):o?o(h):s(void 0,h)}}}processSync(n){let s=!1,i;return this.freeze(),$l("processSync",this.parser||this.Parser),Dl("processSync",this.compiler||this.Compiler),this.process(n,r),Sm("processSync","process",s),i;function r(o,l){s=!0,km(o),i=l}}run(n,s,i){Nm(n),this.freeze();const r=this.transformers;return!i&&typeof s=="function"&&(i=s,s=void 0),i?o(void 0,i):new Promise(o);function o(l,c){const u=Jr(s);r.run(n,u,d);function d(m,h,g){const p=h||n;m?c(m):l?l(p):i(void 0,p,g)}}}runSync(n,s){let i=!1,r;return this.run(n,s,o),Sm("runSync","run",i),r;function o(l,c){km(l),r=c,i=!0}}stringify(n,s){this.freeze();const i=Jr(s),r=this.compiler||this.Compiler;return Dl("stringify",r),Nm(n),r(n,i)}use(n,...s){const i=this.attachers,r=this.namespace;if(Ll("use",this.frozen),n!=null)if(typeof n=="function")u(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(d){if(typeof d=="function")u(d,[]);else if(typeof d=="object")if(Array.isArray(d)){const[m,...h]=d;u(m,h)}else l(d);else throw new TypeError("Expected usable value, not `"+d+"`")}function l(d){if(!("plugins"in d)&&!("settings"in d))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(d.plugins),d.settings&&(r.settings=Rl(!0,r.settings,d.settings))}function c(d){let m=-1;if(d!=null)if(Array.isArray(d))for(;++m<d.length;){const h=d[m];o(h)}else throw new TypeError("Expected a list of plugins, not `"+d+"`")}function u(d,m){let h=-1,g=-1;for(;++h<i.length;)if(i[h][0]===d){g=h;break}if(g===-1)i.push([d,...m]);else if(m.length>0){let[p,...f]=m;const x=i[g][1];zc(x)&&zc(p)&&(p=Rl(!0,x,p)),i[g]=[d,p,...f]}}}}const D2=new kd().freeze();function $l(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Dl(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Ll(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 Nm(e){if(!zc(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Sm(e,n,s){if(!s)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function Jr(e){return L2(e)?e:new xf(e)}function L2(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function z2(e){return typeof e=="string"||F2(e)}function F2(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const O2="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Cm=[],Em={allowDangerousHtml:!0},U2=/^(https?|ircs?|mailto|xmpp)$/i,B2=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function ci(e){const n=H2(e),s=q2(e);return V2(n.runSync(n.parse(s),s),e)}function H2(e){const n=e.rehypePlugins||Cm,s=e.remarkPlugins||Cm,i=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Em}:Em;return D2().use(NC).use(s).use(b2,i).use(n)}function q2(e){const n=e.children||"",s=new xf;return typeof n=="string"&&(s.value=n),s}function V2(e,n){const s=n.allowedElements,i=n.allowElement,r=n.components,o=n.disallowedElements,l=n.skipHtml,c=n.unwrapDisallowed,u=n.urlTransform||W2;for(const m of B2)Object.hasOwn(n,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+O2+m.id,void 0);return yd(e,d),o0(e,{Fragment:t.Fragment,components:r,ignoreInvalidStyle:!0,jsx:t.jsx,jsxs:t.jsxs,passKeys:!0,passNode:!0});function d(m,h,g){if(m.type==="raw"&&g&&typeof h=="number")return l?g.children.splice(h,1):g.children[h]={type:"text",value:m.value},h;if(m.type==="element"){let p;for(p in El)if(Object.hasOwn(El,p)&&Object.hasOwn(m.properties,p)){const f=m.properties[p],x=El[p];(x===null||x.includes(m.tagName))&&(m.properties[p]=u(String(f||""),p,m))}}if(m.type==="element"){let p=s?!s.includes(m.tagName):o?o.includes(m.tagName):!1;if(!p&&i&&typeof h=="number"&&(p=!i(m,h,g)),p&&g&&typeof h=="number")return c&&m.children?g.children.splice(h,1,...m.children):g.children.splice(h,1),h}}}function W2(e){const n=e.indexOf(":"),s=e.indexOf("?"),i=e.indexOf("#"),r=e.indexOf("/");return n===-1||r!==-1&&n>r||s!==-1&&n>s||i!==-1&&n>i||U2.test(e.slice(0,n))?e:""}function _m(e,n){const s=String(e);if(typeof n!="string")throw new TypeError("Expected character");let i=0,r=s.indexOf(n);for(;r!==-1;)i++,r=s.indexOf(n,r+n.length);return i}function K2(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function G2(e,n,s){const r=Go((s||{}).ignore||[]),o=J2(n);let l=-1;for(;++l<o.length;)gf(e,"text",c);function c(d,m){let h=-1,g;for(;++h<m.length;){const p=m[h],f=g?g.children:void 0;if(r(p,f?f.indexOf(p):void 0,g))return;g=p}if(g)return u(d,m)}function u(d,m){const h=m[m.length-1],g=o[l][0],p=o[l][1];let f=0;const v=h.children.indexOf(d);let b=!1,y=[];g.lastIndex=0;let S=g.exec(d.value);for(;S;){const k=S.index,R={index:S.index,input:S.input,stack:[...m,d]};let N=p(...S,R);if(typeof N=="string"&&(N=N.length>0?{type:"text",value:N}:void 0),N===!1?g.lastIndex=k+1:(f!==k&&y.push({type:"text",value:d.value.slice(f,k)}),Array.isArray(N)?y.push(...N):N&&y.push(N),f=k+S[0].length,b=!0),!g.global)break;S=g.exec(d.value)}return b?(f<d.value.length&&y.push({type:"text",value:d.value.slice(f)}),h.children.splice(v,1,...y)):y=[d],v+y.length}}function J2(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 i=-1;for(;++i<s.length;){const r=s[i];n.push([Y2(r[0]),Q2(r[1])])}return n}function Y2(e){return typeof e=="string"?new RegExp(K2(e),"g"):e}function Q2(e){return typeof e=="function"?e:function(){return e}}const zl="phrasing",Fl=["autolink","link","image","label"];function X2(){return{transforms:[aE],enter:{literalAutolink:eE,literalAutolinkEmail:Ol,literalAutolinkHttp:Ol,literalAutolinkWww:Ol},exit:{literalAutolink:iE,literalAutolinkEmail:sE,literalAutolinkHttp:tE,literalAutolinkWww:nE}}}function Z2(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:zl,notInConstruct:Fl},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:zl,notInConstruct:Fl},{character:":",before:"[ps]",after:"\\/",inConstruct:zl,notInConstruct:Fl}]}}function eE(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Ol(e){this.config.enter.autolinkProtocol.call(this,e)}function tE(e){this.config.exit.autolinkProtocol.call(this,e)}function nE(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 sE(e){this.config.exit.autolinkEmail.call(this,e)}function iE(e){this.exit(e)}function aE(e){G2(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,rE],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,oE]],{ignore:["link","linkReference"]})}function rE(e,n,s,i,r){let o="";if(!bf(r)||(/^w/i.test(n)&&(s=n+s,n="",o="http://"),!lE(s)))return!1;const l=cE(s+i);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 oE(e,n,s,i){return!bf(i,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function lE(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 cE(e){const n=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!n)return[e,void 0];e=e.slice(0,n.index);let s=n[0],i=s.indexOf(")");const r=_m(e,"(");let o=_m(e,")");for(;i!==-1&&r>o;)e+=s.slice(0,i+1),s=s.slice(i+1),i=s.indexOf(")"),o++;return[e,s]}function bf(e,n){const s=e.input.charCodeAt(e.index-1);return(e.index===0||Hi(s)||Vo(s))&&(!n||s!==47)}vf.peek=bE;function dE(){this.buffer()}function uE(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function mE(){this.buffer()}function hE(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function pE(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=$s(this.sliceSerialize(e)).toLowerCase(),s.label=n}function fE(e){this.exit(e)}function gE(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=$s(this.sliceSerialize(e)).toLowerCase(),s.label=n}function xE(e){this.exit(e)}function bE(){return"["}function vf(e,n,s,i){const r=s.createTracker(i);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 vE(){return{enter:{gfmFootnoteCallString:dE,gfmFootnoteCall:uE,gfmFootnoteDefinitionLabelString:mE,gfmFootnoteDefinition:hE},exit:{gfmFootnoteCallString:pE,gfmFootnoteCall:fE,gfmFootnoteDefinitionLabelString:gE,gfmFootnoteDefinition:xE}}}function yE(e){let n=!1;return e&&e.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:vf},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function s(i,r,o,l){const c=o.createTracker(l);let u=c.move("[^");const d=o.enter("footnoteDefinition"),m=o.enter("label");return u+=c.move(o.safe(o.associationId(i),{before:u,after:"]"})),m(),u+=c.move("]:"),i.children&&i.children.length>0&&(c.shift(4),u+=c.move((n?`
|
|
632
|
+
`:" ")+o.indentLines(o.containerFlow(i,c.current()),n?yf:kE))),d(),u}}function kE(e,n,s){return n===0?e:yf(e,n,s)}function yf(e,n,s){return(s?"":" ")+e}const jE=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];kf.peek=EE;function wE(){return{canContainEols:["delete"],enter:{strikethrough:SE},exit:{strikethrough:CE}}}function NE(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:jE}],handlers:{delete:kf}}}function SE(e){this.enter({type:"delete",children:[]},e)}function CE(e){this.exit(e)}function kf(e,n,s,i){const r=s.createTracker(i),o=s.enter("strikethrough");let l=r.move("~~");return l+=s.containerPhrasing(e,{...r.current(),before:l,after:"~"}),l+=r.move("~~"),o(),l}function EE(){return"~"}function _E(e){return e.length}function ME(e,n){const s=n||{},i=(s.align||[]).concat(),r=s.stringLength||_E,o=[],l=[],c=[],u=[];let d=0,m=-1;for(;++m<e.length;){const x=[],v=[];let b=-1;for(e[m].length>d&&(d=e[m].length);++b<e[m].length;){const y=AE(e[m][b]);if(s.alignDelimiters!==!1){const S=r(y);v[b]=S,(u[b]===void 0||S>u[b])&&(u[b]=S)}x.push(y)}l[m]=x,c[m]=v}let h=-1;if(typeof i=="object"&&"length"in i)for(;++h<d;)o[h]=Mm(i[h]);else{const x=Mm(i);for(;++h<d;)o[h]=x}h=-1;const g=[],p=[];for(;++h<d;){const x=o[h];let v="",b="";x===99?(v=":",b=":"):x===108?v=":":x===114&&(b=":");let y=s.alignDelimiters===!1?1:Math.max(1,u[h]-v.length-b.length);const S=v+"-".repeat(y)+b;s.alignDelimiters!==!1&&(y=v.length+y+b.length,y>u[h]&&(u[h]=y),p[h]=y),g[h]=S}l.splice(1,0,g),c.splice(1,0,p),m=-1;const f=[];for(;++m<l.length;){const x=l[m],v=c[m];h=-1;const b=[];for(;++h<d;){const y=x[h]||"";let S="",k="";if(s.alignDelimiters!==!1){const R=u[h]-(v[h]||0),N=o[h];N===114?S=" ".repeat(R):N===99?R%2?(S=" ".repeat(R/2+.5),k=" ".repeat(R/2-.5)):(S=" ".repeat(R/2),k=S):k=" ".repeat(R)}s.delimiterStart!==!1&&!h&&b.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&y==="")&&(s.delimiterStart!==!1||h)&&b.push(" "),s.alignDelimiters!==!1&&b.push(S),b.push(y),s.alignDelimiters!==!1&&b.push(k),s.padding!==!1&&b.push(" "),(s.delimiterEnd!==!1||h!==d-1)&&b.push("|")}f.push(s.delimiterEnd===!1?b.join("").replace(/ +$/,""):b.join(""))}return f.join(`
|
|
633
|
+
`)}function AE(e){return e==null?"":String(e)}function Mm(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 RE(e,n,s,i){const r=s.enter("blockquote"),o=s.createTracker(i);o.move("> "),o.shift(2);const l=s.indentLines(s.containerFlow(e,o.current()),TE);return r(),l}function TE(e,n,s){return">"+(s?"":" ")+e}function PE(e,n){return Am(e,n.inConstruct,!0)&&!Am(e,n.notInConstruct,!1)}function Am(e,n,s){if(typeof n=="string"&&(n=[n]),!n||n.length===0)return s;let i=-1;for(;++i<n.length;)if(e.includes(n[i]))return!0;return!1}function Rm(e,n,s,i){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
|
|
634
|
+
`&&PE(s.stack,s.unsafe[r]))return/[ \t]/.test(i.before)?"":" ";return`\\
|
|
635
|
+
`}function IE(e,n){const s=String(e);let i=s.indexOf(n),r=i,o=0,l=0;if(typeof n!="string")throw new TypeError("Expected substring");for(;i!==-1;)i===r?++o>l&&(l=o):o=1,r=i+n.length,i=s.indexOf(n,r);return l}function $E(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 DE(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 LE(e,n,s,i){const r=DE(s),o=e.value||"",l=r==="`"?"GraveAccent":"Tilde";if($E(e,s)){const h=s.enter("codeIndented"),g=s.indentLines(o,zE);return h(),g}const c=s.createTracker(i),u=r.repeat(Math.max(IE(o,r)+1,3)),d=s.enter("codeFenced");let m=c.move(u);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:`
|
|
636
|
+
`,encode:["`"],...c.current()})),h()}return m+=c.move(`
|
|
637
|
+
`),o&&(m+=c.move(o+`
|
|
638
|
+
`)),m+=c.move(u),d(),m}function zE(e,n,s){return(s?"":" ")+e}function jd(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 FE(e,n,s,i){const r=jd(s),o=r==='"'?"Quote":"Apostrophe",l=s.enter("definition");let c=s.enter("label");const u=s.createTracker(i);let d=u.move("[");return d+=u.move(s.safe(s.associationId(e),{before:d,after:"]",...u.current()})),d+=u.move("]: "),c(),!e.url||/[\0- \u007F]/.test(e.url)?(c=s.enter("destinationLiteral"),d+=u.move("<"),d+=u.move(s.safe(e.url,{before:d,after:">",...u.current()})),d+=u.move(">")):(c=s.enter("destinationRaw"),d+=u.move(s.safe(e.url,{before:d,after:e.title?" ":`
|
|
639
|
+
`,...u.current()}))),c(),e.title&&(c=s.enter(`title${o}`),d+=u.move(" "+r),d+=u.move(s.safe(e.title,{before:d,after:r,...u.current()})),d+=u.move(r),c()),l(),d}function OE(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 gr(e){return"&#x"+e.toString(16).toUpperCase()+";"}function So(e,n,s){const i=ga(e),r=ga(n);return i===void 0?r===void 0?s==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:i===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}}jf.peek=UE;function jf(e,n,s,i){const r=OE(s),o=s.enter("emphasis"),l=s.createTracker(i),c=l.move(r);let u=l.move(s.containerPhrasing(e,{after:r,before:c,...l.current()}));const d=u.charCodeAt(0),m=So(i.before.charCodeAt(i.before.length-1),d,r);m.inside&&(u=gr(d)+u.slice(1));const h=u.charCodeAt(u.length-1),g=So(i.after.charCodeAt(0),h,r);g.inside&&(u=u.slice(0,-1)+gr(h));const p=l.move(r);return o(),s.attentionEncodeSurroundingInfo={after:g.outside,before:m.outside},c+u+p}function UE(e,n,s){return s.options.emphasis||"*"}function BE(e,n){let s=!1;return yd(e,function(i){if("value"in i&&/\r?\n|\r/.test(i.value)||i.type==="break")return s=!0,Dc}),!!((!e.depth||e.depth<3)&&hd(e)&&(n.options.setext||s))}function HE(e,n,s,i){const r=Math.max(Math.min(6,e.depth||1),1),o=s.createTracker(i);if(BE(e,s)){const m=s.enter("headingSetext"),h=s.enter("phrasing"),g=s.containerPhrasing(e,{...o.current(),before:`
|
|
640
|
+
`,after:`
|
|
641
|
+
`});return h(),m(),g+`
|
|
642
|
+
`+(r===1?"=":"-").repeat(g.length-(Math.max(g.lastIndexOf("\r"),g.lastIndexOf(`
|
|
643
|
+
`))+1))}const l="#".repeat(r),c=s.enter("headingAtx"),u=s.enter("phrasing");o.move(l+" ");let d=s.containerPhrasing(e,{before:"# ",after:`
|
|
644
|
+
`,...o.current()});return/^[\t ]/.test(d)&&(d=gr(d.charCodeAt(0))+d.slice(1)),d=d?l+" "+d:l,s.options.closeAtx&&(d+=" "+l),u(),c(),d}wf.peek=qE;function wf(e){return e.value||""}function qE(){return"<"}Nf.peek=VE;function Nf(e,n,s,i){const r=jd(s),o=r==='"'?"Quote":"Apostrophe",l=s.enter("image");let c=s.enter("label");const u=s.createTracker(i);let d=u.move("![");return d+=u.move(s.safe(e.alt,{before:d,after:"]",...u.current()})),d+=u.move("]("),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=s.enter("destinationLiteral"),d+=u.move("<"),d+=u.move(s.safe(e.url,{before:d,after:">",...u.current()})),d+=u.move(">")):(c=s.enter("destinationRaw"),d+=u.move(s.safe(e.url,{before:d,after:e.title?" ":")",...u.current()}))),c(),e.title&&(c=s.enter(`title${o}`),d+=u.move(" "+r),d+=u.move(s.safe(e.title,{before:d,after:r,...u.current()})),d+=u.move(r),c()),d+=u.move(")"),l(),d}function VE(){return"!"}Sf.peek=WE;function Sf(e,n,s,i){const r=e.referenceType,o=s.enter("imageReference");let l=s.enter("label");const c=s.createTracker(i);let u=c.move("![");const d=s.safe(e.alt,{before:u,after:"]",...c.current()});u+=c.move(d+"]["),l();const m=s.stack;s.stack=[],l=s.enter("reference");const h=s.safe(s.associationId(e),{before:u,after:"]",...c.current()});return l(),s.stack=m,o(),r==="full"||!d||d!==h?u+=c.move(h+"]"):r==="shortcut"?u=u.slice(0,-1):u+=c.move("]"),u}function WE(){return"!"}Cf.peek=KE;function Cf(e,n,s){let i=e.value||"",r="`",o=-1;for(;new RegExp("(^|[^`])"+r+"([^`]|$)").test(i);)r+="`";for(/[^ \r\n]/.test(i)&&(/^[ \r\n]/.test(i)&&/[ \r\n]$/.test(i)||/^`|`$/.test(i))&&(i=" "+i+" ");++o<s.unsafe.length;){const l=s.unsafe[o],c=s.compilePattern(l);let u;if(l.atBreak)for(;u=c.exec(i);){let d=u.index;i.charCodeAt(d)===10&&i.charCodeAt(d-1)===13&&d--,i=i.slice(0,d)+" "+i.slice(u.index+1)}}return r+i+r}function KE(){return"`"}function Ef(e,n){const s=hd(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))}_f.peek=GE;function _f(e,n,s,i){const r=jd(s),o=r==='"'?"Quote":"Apostrophe",l=s.createTracker(i);let c,u;if(Ef(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"),u=s.enter("label");let d=l.move("[");return d+=l.move(s.containerPhrasing(e,{before:d,after:"](",...l.current()})),d+=l.move("]("),u(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(u=s.enter("destinationLiteral"),d+=l.move("<"),d+=l.move(s.safe(e.url,{before:d,after:">",...l.current()})),d+=l.move(">")):(u=s.enter("destinationRaw"),d+=l.move(s.safe(e.url,{before:d,after:e.title?" ":")",...l.current()}))),u(),e.title&&(u=s.enter(`title${o}`),d+=l.move(" "+r),d+=l.move(s.safe(e.title,{before:d,after:r,...l.current()})),d+=l.move(r),u()),d+=l.move(")"),c(),d}function GE(e,n,s){return Ef(e,s)?"<":"["}Mf.peek=JE;function Mf(e,n,s,i){const r=e.referenceType,o=s.enter("linkReference");let l=s.enter("label");const c=s.createTracker(i);let u=c.move("[");const d=s.containerPhrasing(e,{before:u,after:"]",...c.current()});u+=c.move(d+"]["),l();const m=s.stack;s.stack=[],l=s.enter("reference");const h=s.safe(s.associationId(e),{before:u,after:"]",...c.current()});return l(),s.stack=m,o(),r==="full"||!d||d!==h?u+=c.move(h+"]"):r==="shortcut"?u=u.slice(0,-1):u+=c.move("]"),u}function JE(){return"["}function wd(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 YE(e){const n=wd(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 QE(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 Af(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 XE(e,n,s,i){const r=s.enter("list"),o=s.bulletCurrent;let l=e.ordered?QE(s):wd(s);const c=e.ordered?l==="."?")":".":YE(s);let u=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&&(u=!0),Af(s)===l&&m){let h=-1;for(;++h<e.children.length;){const g=e.children[h];if(g&&g.type==="listItem"&&g.children&&g.children[0]&&g.children[0].type==="thematicBreak"){u=!0;break}}}}u&&(l=c),s.bulletCurrent=l;const d=s.containerFlow(e,i);return s.bulletLastUsed=l,s.bulletCurrent=o,r(),d}function ZE(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 e_(e,n,s,i){const r=ZE(s);let o=s.bulletCurrent||wd(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(i);c.move(o+" ".repeat(l-o.length)),c.shift(l);const u=s.enter("listItem"),d=s.indentLines(s.containerFlow(e,c.current()),m);return u(),d;function m(h,g,p){return g?(p?"":" ".repeat(l))+h:(p?o:o+" ".repeat(l-o.length))+h}}function t_(e,n,s,i){const r=s.enter("paragraph"),o=s.enter("phrasing"),l=s.containerPhrasing(e,i);return o(),r(),l}const n_=Go(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function s_(e,n,s,i){return(e.children.some(function(l){return n_(l)})?s.containerPhrasing:s.containerFlow).call(s,e,i)}function i_(e){const n=e.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}Rf.peek=a_;function Rf(e,n,s,i){const r=i_(s),o=s.enter("strong"),l=s.createTracker(i),c=l.move(r+r);let u=l.move(s.containerPhrasing(e,{after:r,before:c,...l.current()}));const d=u.charCodeAt(0),m=So(i.before.charCodeAt(i.before.length-1),d,r);m.inside&&(u=gr(d)+u.slice(1));const h=u.charCodeAt(u.length-1),g=So(i.after.charCodeAt(0),h,r);g.inside&&(u=u.slice(0,-1)+gr(h));const p=l.move(r+r);return o(),s.attentionEncodeSurroundingInfo={after:g.outside,before:m.outside},c+u+p}function a_(e,n,s){return s.options.strong||"*"}function r_(e,n,s,i){return s.safe(e.value,i)}function o_(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 l_(e,n,s){const i=(Af(s)+(s.options.ruleSpaces?" ":"")).repeat(o_(s));return s.options.ruleSpaces?i.slice(0,-1):i}const Tf={blockquote:RE,break:Rm,code:LE,definition:FE,emphasis:jf,hardBreak:Rm,heading:HE,html:wf,image:Nf,imageReference:Sf,inlineCode:Cf,link:_f,linkReference:Mf,list:XE,listItem:e_,paragraph:t_,root:s_,strong:Rf,text:r_,thematicBreak:l_};function c_(){return{enter:{table:d_,tableData:Tm,tableHeader:Tm,tableRow:m_},exit:{codeText:h_,table:u_,tableData:Ul,tableHeader:Ul,tableRow:Ul}}}function d_(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 u_(e){this.exit(e),this.data.inTable=void 0}function m_(e){this.enter({type:"tableRow",children:[]},e)}function Ul(e){this.exit(e)}function Tm(e){this.enter({type:"tableCell",children:[]},e)}function h_(e){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,p_));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(e)}function p_(e,n){return n==="|"?n:e}function f_(e){const n=e||{},s=n.tableCellPadding,i=n.tablePipeAlign,r=n.stringLength,o=s?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
|
|
645
|
+
`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:g,table:l,tableCell:u,tableRow:c}};function l(p,f,x,v){return d(m(p,x,v),p.align)}function c(p,f,x,v){const b=h(p,x,v),y=d([b]);return y.slice(0,y.indexOf(`
|
|
646
|
+
`))}function u(p,f,x,v){const b=x.enter("tableCell"),y=x.enter("phrasing"),S=x.containerPhrasing(p,{...v,before:o,after:o});return y(),b(),S}function d(p,f){return ME(p,{align:f,alignDelimiters:i,padding:s,stringLength:r})}function m(p,f,x){const v=p.children;let b=-1;const y=[],S=f.enter("table");for(;++b<v.length;)y[b]=h(v[b],f,x);return S(),y}function h(p,f,x){const v=p.children;let b=-1;const y=[],S=f.enter("tableRow");for(;++b<v.length;)y[b]=u(v[b],p,f,x);return S(),y}function g(p,f,x){let v=Tf.inlineCode(p,f,x);return x.stack.includes("tableCell")&&(v=v.replace(/\|/g,"\\$&")),v}}function g_(){return{exit:{taskListCheckValueChecked:Pm,taskListCheckValueUnchecked:Pm,paragraph:b_}}}function x_(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:v_}}}function Pm(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function b_(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 i=s.children[0];if(i&&i.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&&(i.value=i.value.slice(1),i.value.length===0?s.children.shift():s.position&&i.position&&typeof i.position.start.offset=="number"&&(i.position.start.column++,i.position.start.offset++,s.position.start=Object.assign({},i.position.start)))}}this.exit(e)}function v_(e,n,s,i){const r=e.children[0],o=typeof e.checked=="boolean"&&r&&r.type==="paragraph",l="["+(e.checked?"x":" ")+"] ",c=s.createTracker(i);o&&c.move(l);let u=Tf.listItem(e,n,s,{...i,...c.current()});return o&&(u=u.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,d)),u;function d(m){return m+l}}function y_(){return[X2(),vE(),wE(),c_(),g_()]}function k_(e){return{extensions:[Z2(),yE(e),NE(),f_(e),x_()]}}const j_={tokenize:__,partial:!0},Pf={tokenize:M_,partial:!0},If={tokenize:A_,partial:!0},$f={tokenize:R_,partial:!0},w_={tokenize:T_,partial:!0},Df={name:"wwwAutolink",tokenize:C_,previous:zf},Lf={name:"protocolAutolink",tokenize:E_,previous:Ff},ui={name:"emailAutolink",tokenize:S_,previous:Of},Zs={};function N_(){return{text:Zs}}let Ii=48;for(;Ii<123;)Zs[Ii]=ui,Ii++,Ii===58?Ii=65:Ii===91&&(Ii=97);Zs[43]=ui;Zs[45]=ui;Zs[46]=ui;Zs[95]=ui;Zs[72]=[ui,Lf];Zs[104]=[ui,Lf];Zs[87]=[ui,Df];Zs[119]=[ui,Df];function S_(e,n,s){const i=this;let r,o;return l;function l(h){return!Oc(h)||!Of.call(i,i.previous)||Nd(i.events)?s(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(h))}function c(h){return Oc(h)?(e.consume(h),c):h===64?(e.consume(h),u):s(h)}function u(h){return h===46?e.check(w_,m,d)(h):h===45||h===95||Hn(h)?(o=!0,e.consume(h),u):m(h)}function d(h){return e.consume(h),r=!0,u}function m(h){return o&&r&&Qn(i.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),n(h)):s(h)}}function C_(e,n,s){const i=this;return r;function r(l){return l!==87&&l!==119||!zf.call(i,i.previous)||Nd(i.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(j_,e.attempt(Pf,e.attempt(If,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function E_(e,n,s){const i=this;let r="",o=!1;return l;function l(h){return(h===72||h===104)&&Ff.call(i,i.previous)&&!Nd(i.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),e.consume(h),c):s(h)}function c(h){if(Qn(h)&&r.length<5)return r+=String.fromCodePoint(h),e.consume(h),c;if(h===58){const g=r.toLowerCase();if(g==="http"||g==="https")return e.consume(h),u}return s(h)}function u(h){return h===47?(e.consume(h),o?d:(o=!0,u)):s(h)}function d(h){return h===null||jo(h)||an(h)||Hi(h)||Vo(h)?s(h):e.attempt(Pf,e.attempt(If,m),s)(h)}function m(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(h)}}function __(e,n,s){let i=0;return r;function r(l){return(l===87||l===119)&&i<3?(i++,e.consume(l),r):l===46&&i===3?(e.consume(l),o):s(l)}function o(l){return l===null?s(l):n(l)}}function M_(e,n,s){let i,r,o;return l;function l(d){return d===46||d===95?e.check($f,u,c)(d):d===null||an(d)||Hi(d)||d!==45&&Vo(d)?u(d):(o=!0,e.consume(d),l)}function c(d){return d===95?i=!0:(r=i,i=void 0),e.consume(d),l}function u(d){return r||i||!o?s(d):n(d)}}function A_(e,n){let s=0,i=0;return r;function r(l){return l===40?(s++,e.consume(l),r):l===41&&i<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($f,n,o)(l):l===null||an(l)||Hi(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&i++,e.consume(l),r}}function R_(e,n,s){return i;function i(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),i):c===38?(e.consume(c),o):c===93?(e.consume(c),r):c===60||c===null||an(c)||Hi(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||an(c)||Hi(c)?n(c):i(c)}function o(c){return Qn(c)?l(c):s(c)}function l(c){return c===59?(e.consume(c),i):Qn(c)?(e.consume(c),l):s(c)}}function T_(e,n,s){return i;function i(o){return e.consume(o),r}function r(o){return Hn(o)?s(o):n(o)}}function zf(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||an(e)}function Ff(e){return!Qn(e)}function Of(e){return!(e===47||Oc(e))}function Oc(e){return e===43||e===45||e===46||e===95||Hn(e)}function Nd(e){let n=e.length,s=!1;for(;n--;){const i=e[n][1];if((i.type==="labelLink"||i.type==="labelImage")&&!i._balanced){s=!0;break}if(i._gfmAutolinkLiteralWalkedInto){s=!1;break}}return e.length>0&&!s&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),s}const P_={tokenize:U_,partial:!0};function I_(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:z_,continuation:{tokenize:F_},exit:O_}},text:{91:{name:"gfmFootnoteCall",tokenize:L_},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:$_,resolveTo:D_}}}}function $_(e,n,s){const i=this;let r=i.events.length;const o=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let l;for(;r--;){const u=i.events[r][1];if(u.type==="labelImage"){l=u;break}if(u.type==="gfmFootnoteCall"||u.type==="labelLink"||u.type==="label"||u.type==="image"||u.type==="link")break}return c;function c(u){if(!l||!l._balanced)return s(u);const d=$s(i.sliceSerialize({start:l.end,end:i.now()}));return d.codePointAt(0)!==94||!o.includes(d.slice(1))?s(u):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(u),e.exit("gfmFootnoteCallLabelMarker"),n(u))}}function D_(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 i={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",i,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",i,n]];return e.splice(s,e.length-s+1,...c),e}function L_(e,n,s){const i=this,r=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let o=0,l;return c;function c(h){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),u}function u(h){return h!==94?s(h):(e.enter("gfmFootnoteCallMarker"),e.consume(h),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",d)}function d(h){if(o>999||h===93&&!l||h===null||h===91||an(h))return s(h);if(h===93){e.exit("chunkString");const g=e.exit("gfmFootnoteCallString");return r.includes($s(i.sliceSerialize(g)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),n):s(h)}return an(h)||(l=!0),o++,e.consume(h),h===92?m:d}function m(h){return h===91||h===92||h===93?(e.consume(h),o++,d):d(h)}}function z_(e,n,s){const i=this,r=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let o,l=0,c;return u;function u(f){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionLabelMarker"),d}function d(f){return f===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",m):s(f)}function m(f){if(l>999||f===93&&!c||f===null||f===91||an(f))return s(f);if(f===93){e.exit("chunkString");const x=e.exit("gfmFootnoteDefinitionLabelString");return o=$s(i.sliceSerialize(x)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),g}return an(f)||(c=!0),l++,e.consume(f),f===92?h:m}function h(f){return f===91||f===92||f===93?(e.consume(f),l++,m):m(f)}function g(f){return f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),r.includes(o)||r.push(o),Wt(e,p,"gfmFootnoteDefinitionWhitespace")):s(f)}function p(f){return n(f)}}function F_(e,n,s){return e.check(_r,n,e.attempt(P_,n,s))}function O_(e){e.exit("gfmFootnoteDefinition")}function U_(e,n,s){const i=this;return Wt(e,r,"gfmFootnoteDefinitionIndent",5);function r(o){const l=i.events[i.events.length-1];return l&&l[1].type==="gfmFootnoteDefinitionIndent"&&l[2].sliceSerialize(l[1],!0).length===4?n(o):s(o)}}function B_(e){let s=(e||{}).singleTilde;const i={name:"strikethrough",tokenize:o,resolveAll:r};return s==null&&(s=!0),{text:{126:i},insideSpan:{null:[i]},attentionMarkers:{null:[126]}};function r(l,c){let u=-1;for(;++u<l.length;)if(l[u][0]==="enter"&&l[u][1].type==="strikethroughSequenceTemporary"&&l[u][1]._close){let d=u;for(;d--;)if(l[d][0]==="exit"&&l[d][1].type==="strikethroughSequenceTemporary"&&l[d][1]._open&&l[u][1].end.offset-l[u][1].start.offset===l[d][1].end.offset-l[d][1].start.offset){l[u][1].type="strikethroughSequence",l[d][1].type="strikethroughSequence";const m={type:"strikethrough",start:Object.assign({},l[d][1].start),end:Object.assign({},l[u][1].end)},h={type:"strikethroughText",start:Object.assign({},l[d][1].end),end:Object.assign({},l[u][1].start)},g=[["enter",m,c],["enter",l[d][1],c],["exit",l[d][1],c],["enter",h,c]],p=c.parser.constructs.insideSpan.null;p&&fs(g,g.length,0,Wo(p,l.slice(d+1,u),c)),fs(g,g.length,0,[["exit",h,c],["enter",l[u][1],c],["exit",l[u][1],c],["exit",m,c]]),fs(l,d-1,u-d+3,g),u=d+g.length-2;break}}for(u=-1;++u<l.length;)l[u][1].type==="strikethroughSequenceTemporary"&&(l[u][1].type="data");return l}function o(l,c,u){const d=this.previous,m=this.events;let h=0;return g;function g(f){return d===126&&m[m.length-1][1].type!=="characterEscape"?u(f):(l.enter("strikethroughSequenceTemporary"),p(f))}function p(f){const x=ga(d);if(f===126)return h>1?u(f):(l.consume(f),h++,p);if(h<2&&!s)return u(f);const v=l.exit("strikethroughSequenceTemporary"),b=ga(f);return v._open=!b||b===2&&!!x,v._close=!x||x===2&&!!b,c(f)}}}class H_{constructor(){this.map=[]}add(n,s,i){q_(this,n,s,i)}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 i=[];for(;s>0;)s-=1,i.push(n.slice(this.map[s][0]+this.map[s][1]),this.map[s][2]),n.length=this.map[s][0];i.push(n.slice()),n.length=0;let r=i.pop();for(;r;){for(const o of r)n.push(o);r=i.pop()}this.map.length=0}}function q_(e,n,s,i){let r=0;if(!(s===0&&i.length===0)){for(;r<e.map.length;){if(e.map[r][0]===n){e.map[r][1]+=s,e.map[r][2].push(...i);return}r+=1}e.map.push([n,s,i])}}function V_(e,n){let s=!1;const i=[];for(;n<e.length;){const r=e[n];if(s){if(r[0]==="enter")r[1].type==="tableContent"&&i.push(e[n+1][1].type==="tableDelimiterMarker"?"left":"none");else if(r[1].type==="tableContent"){if(e[n-1][1].type==="tableDelimiterMarker"){const o=i.length-1;i[o]=i[o]==="left"?"center":"right"}}else if(r[1].type==="tableDelimiterRow")break}else r[0]==="enter"&&r[1].type==="tableDelimiterRow"&&(s=!0);n+=1}return i}function W_(){return{flow:{null:{name:"table",tokenize:K_,resolveAll:G_}}}}function K_(e,n,s){const i=this;let r=0,o=0,l;return c;function c(A){let P=i.events.length-1;for(;P>-1;){const $=i.events[P][1].type;if($==="lineEnding"||$==="linePrefix")P--;else break}const F=P>-1?i.events[P][1].type:null,W=F==="tableHead"||F==="tableRow"?N:u;return W===N&&i.parser.lazy[i.now().line]?s(A):W(A)}function u(A){return e.enter("tableHead"),e.enter("tableRow"),d(A)}function d(A){return A===124||(l=!0,o+=1),m(A)}function m(A){return A===null?s(A):bt(A)?o>1?(o=0,i.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(A),e.exit("lineEnding"),p):s(A):Bt(A)?Wt(e,m,"whitespace")(A):(o+=1,l&&(l=!1,r+=1),A===124?(e.enter("tableCellDivider"),e.consume(A),e.exit("tableCellDivider"),l=!0,m):(e.enter("data"),h(A)))}function h(A){return A===null||A===124||an(A)?(e.exit("data"),m(A)):(e.consume(A),A===92?g:h)}function g(A){return A===92||A===124?(e.consume(A),h):h(A)}function p(A){return i.interrupt=!1,i.parser.lazy[i.now().line]?s(A):(e.enter("tableDelimiterRow"),l=!1,Bt(A)?Wt(e,f,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(A):f(A))}function f(A){return A===45||A===58?v(A):A===124?(l=!0,e.enter("tableCellDivider"),e.consume(A),e.exit("tableCellDivider"),x):R(A)}function x(A){return Bt(A)?Wt(e,v,"whitespace")(A):v(A)}function v(A){return A===58?(o+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(A),e.exit("tableDelimiterMarker"),b):A===45?(o+=1,b(A)):A===null||bt(A)?k(A):R(A)}function b(A){return A===45?(e.enter("tableDelimiterFiller"),y(A)):R(A)}function y(A){return A===45?(e.consume(A),y):A===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(A),e.exit("tableDelimiterMarker"),S):(e.exit("tableDelimiterFiller"),S(A))}function S(A){return Bt(A)?Wt(e,k,"whitespace")(A):k(A)}function k(A){return A===124?f(A):A===null||bt(A)?!l||r!==o?R(A):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(A)):R(A)}function R(A){return s(A)}function N(A){return e.enter("tableRow"),M(A)}function M(A){return A===124?(e.enter("tableCellDivider"),e.consume(A),e.exit("tableCellDivider"),M):A===null||bt(A)?(e.exit("tableRow"),n(A)):Bt(A)?Wt(e,M,"whitespace")(A):(e.enter("data"),C(A))}function C(A){return A===null||A===124||an(A)?(e.exit("data"),M(A)):(e.consume(A),A===92?z:C)}function z(A){return A===92||A===124?(e.consume(A),C):C(A)}}function G_(e,n){let s=-1,i=!0,r=0,o=[0,0,0,0],l=[0,0,0,0],c=!1,u=0,d,m,h;const g=new H_;for(;++s<e.length;){const p=e[s],f=p[1];p[0]==="enter"?f.type==="tableHead"?(c=!1,u!==0&&(Im(g,n,u,d,m),m=void 0,u=0),d={type:"table",start:Object.assign({},f.start),end:Object.assign({},f.end)},g.add(s,0,[["enter",d,n]])):f.type==="tableRow"||f.type==="tableDelimiterRow"?(i=!0,h=void 0,o=[0,0,0,0],l=[0,s+1,0,0],c&&(c=!1,m={type:"tableBody",start:Object.assign({},f.start),end:Object.assign({},f.end)},g.add(s,0,[["enter",m,n]])),r=f.type==="tableDelimiterRow"?2:m?3:1):r&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")?(i=!1,l[2]===0&&(o[1]!==0&&(l[0]=l[1],h=Yr(g,n,o,r,void 0,h),o=[0,0,0,0]),l[2]=s)):f.type==="tableCellDivider"&&(i?i=!1:(o[1]!==0&&(l[0]=l[1],h=Yr(g,n,o,r,void 0,h)),o=l,l=[o[1],s,0,0])):f.type==="tableHead"?(c=!0,u=s):f.type==="tableRow"||f.type==="tableDelimiterRow"?(u=s,o[1]!==0?(l[0]=l[1],h=Yr(g,n,o,r,s,h)):l[1]!==0&&(h=Yr(g,n,l,r,s,h)),r=0):r&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")&&(l[3]=s)}for(u!==0&&Im(g,n,u,d,m),g.consume(n.events),s=-1;++s<n.events.length;){const p=n.events[s];p[0]==="enter"&&p[1].type==="table"&&(p[1]._align=V_(n.events,s))}return e}function Yr(e,n,s,i,r,o){const l=i===1?"tableHeader":i===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},ra(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const u=ra(n.events,s[1]);if(o={type:l,start:Object.assign({},u),end:Object.assign({},u)},e.add(s[1],0,[["enter",o,n]]),s[2]!==0){const d=ra(n.events,s[2]),m=ra(n.events,s[3]),h={type:c,start:Object.assign({},d),end:Object.assign({},m)};if(e.add(s[2],0,[["enter",h,n]]),i!==2){const g=n.events[s[2]],p=n.events[s[3]];if(g[1].end=Object.assign({},p[1].end),g[1].type="chunkText",g[1].contentType="text",s[3]>s[2]+1){const f=s[2]+1,x=s[3]-s[2]-1;e.add(f,x,[])}}e.add(s[3]+1,0,[["exit",h,n]])}return r!==void 0&&(o.end=Object.assign({},ra(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function Im(e,n,s,i,r){const o=[],l=ra(n.events,s);r&&(r.end=Object.assign({},l),o.push(["exit",r,n])),i.end=Object.assign({},l),o.push(["exit",i,n]),e.add(s+1,0,o)}function ra(e,n){const s=e[n],i=s[0]==="enter"?"start":"end";return s[1][i]}const J_={name:"tasklistCheck",tokenize:Q_};function Y_(){return{text:{91:J_}}}function Q_(e,n,s){const i=this;return r;function r(u){return i.previous!==null||!i._gfmTasklistFirstContentOfListItem?s(u):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(u),e.exit("taskListCheckMarker"),o)}function o(u){return an(u)?(e.enter("taskListCheckValueUnchecked"),e.consume(u),e.exit("taskListCheckValueUnchecked"),l):u===88||u===120?(e.enter("taskListCheckValueChecked"),e.consume(u),e.exit("taskListCheckValueChecked"),l):s(u)}function l(u){return u===93?(e.enter("taskListCheckMarker"),e.consume(u),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),c):s(u)}function c(u){return bt(u)?n(u):Bt(u)?e.check({tokenize:X_},n,s)(u):s(u)}}function X_(e,n,s){return Wt(e,i,"whitespace");function i(r){return r===null?s(r):n(r)}}function Z_(e){return Yp([N_(),I_(),B_(e),W_(),Y_()])}const eM={};function di(e){const n=this,s=e||eM,i=n.data(),r=i.micromarkExtensions||(i.micromarkExtensions=[]),o=i.fromMarkdownExtensions||(i.fromMarkdownExtensions=[]),l=i.toMarkdownExtensions||(i.toMarkdownExtensions=[]);r.push(Z_(s)),o.push(y_()),l.push(k_(s))}const $m=500,Dm=100;function Bl(e){return e.length>$m?e.slice(-$m):e}function Uf(e,n,s){const[i,r]=a.useState([]),[o,l]=a.useState(!1),[c,u]=a.useState(!1),[d,m]=a.useState(null),[h,g]=a.useState(!1),p=a.useRef(null),f=a.useRef(!1),x=a.useRef(0),v=a.useRef(e),b=a.useRef(s),y=a.useRef(n),S=a.useRef(0);(v.current!==e||b.current!==s||y.current!==n)&&(v.current=e,b.current=s,y.current=n,x.current++,f.current=!0,r([]),l(!1),u(!1),m(null),g(!1),p.current&&(p.current(),p.current=null)),a.useEffect(()=>{if(!e||!n){p.current&&(p.current(),p.current=null);return}const M=x.current,C=++S.current;f.current=!1;const z=e,A=s;async function P(){if(!z)return;l(!0),g(!1);try{const W=await Id(z,A,{limit:Dm});if(f.current||x.current!==M||S.current!==C)return;r(Bl(W.entries)),u(W.hasMore),m(W.total)}catch{if(f.current||x.current!==M||S.current!==C)return;r([]),u(!1),m(null)}finally{!f.current&&x.current===M&&S.current===C&&l(!1)}const F=A?`?projectId=${encodeURIComponent(A)}`:"";p.current=Ls(`/api/tasks/${z}/logs/stream${F}`,{events:{"agent:log":W=>{if(!(f.current||x.current!==M))try{const $=JSON.parse(W.data);r(_=>Bl([..._,$])),m(_=>_!==null?_+1:null)}catch{}}}})}return P(),()=>{f.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const R=a.useCallback(async()=>{if(!e||h)return;const M=x.current,C=i.length,z=e;g(!0);try{const A=await Id(z,s,{limit:Dm,offset:C});if(f.current||x.current!==M)return;r(P=>{const F=[...A.entries,...P];return Bl(F)}),u(A.hasMore),m(A.total)}catch{}finally{g(!1)}},[e,s,i.length,h]),N=a.useCallback(()=>r([]),[]);return{entries:i,loading:o,clear:N,loadMore:R,hasMore:c,total:d,loadingMore:h}}function tM(e){const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/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 Lm={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})},Bf=50,nM={triage:"Plan"};function zm(e){return e.scrollHeight-(e.scrollTop+e.clientHeight)<=Bf}function Uc(e){return[e.taskId,e.timestamp,e.agent??"",e.type,e.text,e.detail??""].join("|")}function sM(e){const n=new Map;return e.map(s=>{const i=Uc(s),r=n.get(i)??0;return n.set(i,r+1),`${i}|${r}`})}function iM(e){return e==="tool"||e==="tool_result"||e==="tool_error"}function aM(e,n){return e.agent?iM(e.type)?!0:!n||n.agent!==e.agent||n.type!==e.type:!1}function rM(e,n){const s=[];for(let i=0;i<e.length;i+=1){const r=e[i],o=n[i]??`${Uc(r)}|fallback`,l=i>0?e[i-1]:void 0,c=aM(r,l);if(r.type==="text"||r.type==="thinking"){const u=[r];let d=i+1;for(;d<e.length;){const h=e[d];if(h.type!==r.type||h.agent!==r.agent)break;u.push(h),d+=1}const m=n[d-1]??`${Uc(e[d-1])}|fallback`;s.push({kind:r.type,entries:u,key:`${o}->${m}`,showBadge:c}),i=d-1;continue}s.push({kind:"single",entry:r,key:o,showBadge:c})}return s}function oM({entries:e,loading:n,executorModel:s,validatorModel:i,planningModel:r,hasMore:o=!1,onLoadMore:l,loadingMore:c=!1,totalCount:u=null}){const d=a.useRef(null),m=a.useRef(0),h=a.useRef(0),g=a.useRef(null),p=a.useRef(null),[f,x]=a.useState(!0),[v,b]=a.useState(!1),[y,S]=a.useState(!1),[k,R]=a.useState(!0),N=a.useMemo(()=>sM(e),[e]),M=a.useMemo(()=>rM(e,N),[e,N]);a.useLayoutEffect(()=>{const _=d.current;if(!_)return;const I=e.length,O=m.current,J=h.current||_.scrollHeight,Q=N[0]??null,E=N[N.length-1]??null,D=g.current!==Q,T=p.current!==E;if(I>O)if(O===0)_.scrollTop=_.scrollHeight;else{const w=J-(_.scrollTop+_.clientHeight)<=Bf,q=T&&!D,G=D&&!T;if(q&&w&&(_.scrollTop=_.scrollHeight),G){const me=_.scrollHeight-J;me>0&&(_.scrollTop+=me)}}m.current=I,h.current=_.scrollHeight,g.current=Q,p.current=E,R(zm(_))},[e,N]);const C=a.useCallback(()=>{const _=d.current;_&&R(zm(_))},[]),z=a.useCallback(()=>{const _=d.current;_&&(_.scrollTop=_.scrollHeight,R(!0))},[]),A=a.useCallback(_=>{_.key==="Escape"&&v&&b(!1)},[v]);a.useEffect(()=>{if(v)return document.addEventListener("keydown",A),()=>{document.removeEventListener("keydown",A)}},[v,A]);const P=s?.provider&&s?.modelId,F=i?.provider&&i?.modelId,W=r?.provider&&r?.modelId,$=a.useMemo(()=>{const _=[];return P&&_.push({role:"Executor",provider:s.provider,modelId:s.modelId}),F&&_.push({role:"Reviewer",provider:i.provider,modelId:i.modelId}),W&&_.push({role:"Planning",provider:r.provider,modelId:r.modelId}),_},[P,s,F,i,W,r]);return n&&e.length===0?t.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:t.jsx("div",{className:"agent-log-loading",children:"Loading agent logs…"})}):e.length===0?t.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:t.jsx("div",{className:"agent-log-empty",children:"No agent output yet."})}):t.jsxs("div",{className:`agent-log-viewer agent-log-viewer--streaming${v?" agent-log-viewer--fullscreen":""}`,"data-testid":"agent-log-viewer",children:[t.jsxs("div",{className:"agent-log-model-header","data-testid":"agent-log-model-header",children:[t.jsxs("div",{className:"agent-log-model-icons",children:[$.map(_=>t.jsx(An,{provider:_.provider,size:"sm"},`${_.role}-${_.provider}-${_.modelId??"default"}`)),t.jsx("button",{className:"agent-log-model-expand-btn",onClick:()=>S(_=>!_),"aria-label":y?"Collapse model details":"Expand model details","aria-expanded":y,"aria-controls":"agent-log-model-details","data-testid":"agent-log-model-expand",children:y?t.jsx(qt,{size:14}):t.jsx(hn,{size:14})})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>x(_=>!_),"aria-label":f?"Switch to plain text mode":"Switch to markdown mode","aria-pressed":f,"data-testid":"agent-log-mode-toggle",title:f?"Show raw text":"Show formatted markdown",children:f?"Markdown":"Plain"}),t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>b(_=>!_),"aria-label":v?"Exit full screen":"Expand agent log to full screen","data-testid":"agent-log-fullscreen-toggle",title:v?"Exit full screen":"Expand agent log to full screen",children:v?t.jsx(yr,{size:14}):t.jsx($o,{size:14})})]}),y&&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:"}),P?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(An,{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:"}),F?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(An,{provider:i.provider,size:"sm"}),t.jsxs("span",{children:[i.provider,"/",i.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:"}),W?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(An,{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:d,className:"agent-log-viewer-scroll",onScroll:C,children:[u!==null&&t.jsxs("div",{className:"agent-log-summary","data-testid":"agent-log-summary",children:["Showing ",e.length," of ",u," entries"]}),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(ot,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})}),M.map(_=>{const I=_.kind==="single"?_.entry:_.entries[0],O=_.showBadge?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:tM(I.timestamp)}):null,J=_.showBadge?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",nM[I.agent]??I.agent,"]"]}),O]}):null;if(_.kind==="single"){const{entry:E}=_;if(E.type==="tool")return t.jsxs("div",{className:"agent-log-tool",children:[J,"⚡ ",E.text,E.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",E.detail]})]},_.key);if(E.type==="tool_result")return t.jsxs("div",{className:"agent-log-tool-result",children:[J,"✓ ",E.text,E.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",E.detail]})]},_.key);if(E.type==="tool_error")return t.jsxs("div",{className:"agent-log-tool-error",children:[J,"✗ ",E.text,E.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",E.detail]})]},_.key)}const Q=_.kind==="single"?I.text:_.entries.map(E=>E.text).join("");return _.kind==="thinking"?t.jsxs("div",{className:"agent-log-thinking",children:[J,f?t.jsx("div",{className:"markdown-body",children:t.jsx(ci,{remarkPlugins:[di],components:Lm,children:Q})}):Q]},_.key):t.jsxs("div",{className:"agent-log-text",children:[J,f?t.jsx("div",{className:"markdown-body",children:t.jsx(ci,{remarkPlugins:[di],components:Lm,children:Q})}):Q]},_.key)}),!k&&t.jsxs("button",{type:"button",className:"agent-log-return-to-live",onClick:z,"data-testid":"agent-log-return-to-live",children:[t.jsx(qt,{size:12}),t.jsx("span",{children:"Live"})]})]})]})}function xa(e){return e??void 0}function Qr(e){return{provider:xa(e.modelProvider),modelId:xa(e.modelId)}}function Xr(e){return{provider:xa(e.validatorModelProvider),modelId:xa(e.validatorModelId)}}function Zr(e){return{provider:xa(e.planningModelProvider),modelId:xa(e.planningModelId)}}function lM(e,n){return fp(e,n)}function cM(e,n){return gp(e,n)}function dM(e,n){return xp(e,n)}function Hl(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 ql(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function Vl(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function uM(e,n){const i={executor:"Executor",validator:"Reviewer",planning:"Planning"}[e]||e;return!n.provider||!n.modelId?`${i} model set to default`:`${i} model set to ${n.provider}/${n.modelId}`}function mM({task:e,addToast:n,onTaskUpdated:s,settings:i}){const[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState([]),[m,h]=a.useState(!1),[g,p]=a.useState(null),[f,x]=a.useState(()=>Qr(e)),[v,b]=a.useState(()=>Qr(e)),[y,S]=a.useState(()=>Xr(e)),[k,R]=a.useState(()=>Xr(e)),[N,M]=a.useState(()=>Zr(e)),[C,z]=a.useState(()=>Zr(e)),[A,P]=a.useState(()=>e.thinkingLevel??null),[F,W]=a.useState(()=>e.thinkingLevel??null),[$,_]=a.useState(null),I=a.useRef(e.id);a.useEffect(()=>{h(!0),p(null),cs().then(le=>{o(le.models),c(le.favoriteProviders),d(le.favoriteModels)}).catch(le=>{p(le.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const O=a.useCallback(async le=>{const ve=l,Ee=ve.includes(le)?ve.filter(Fe=>Fe!==le):[le,...ve];c(Ee);try{await sn({favoriteProviders:Ee,favoriteModels:u})}catch{c(ve),n("Failed to update favorites","error")}},[l,u,n]),J=a.useCallback(async le=>{const ve=u,Ee=ve.includes(le)?ve.filter(Fe=>Fe!==le):[le,...ve];d(Ee);try{await sn({favoriteProviders:l,favoriteModels:Ee})}catch{d(ve),n("Failed to update model favorites","error")}},[u,l,n]);a.useEffect(()=>{I.current=e.id;const le=Qr(e),ve=Xr(e),ee=Zr(e);x(le),b(le),S(ve),R(ve),M(ee),z(ee);const Ee=e.thinkingLevel??null;P(Ee),W(Ee),_(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const Q=a.useMemo(()=>ql(f),[f]),E=a.useMemo(()=>ql(y),[y]),D=a.useMemo(()=>ql(N),[N]),T=a.useMemo(()=>lM(e,i),[e,i]),w=a.useMemo(()=>cM(e,i),[e,i]),q=a.useMemo(()=>dM(e,i),[e,i]),G=$!==null,me=a.useCallback(async(le,ve)=>{const ee=e.id,Ee=v,Fe=k,Ke=C;_(le);try{const Ze=s?le==="executor"?{modelProvider:ve.provider??null,modelId:ve.modelId??null}:le==="validator"?{validatorModelProvider:ve.provider??null,validatorModelId:ve.modelId??null}:{planningModelProvider:ve.provider??null,planningModelId:ve.modelId??null}:{modelProvider:(le==="executor"?ve:v).provider??null,modelId:(le==="executor"?ve:v).modelId??null,validatorModelProvider:(le==="validator"?ve:k).provider??null,validatorModelId:(le==="validator"?ve:k).modelId??null,planningModelProvider:(le==="planning"?ve:C).provider??null,planningModelId:(le==="planning"?ve:C).modelId??null},Xe=await Ks(ee,Ze);if(I.current!==ee)return;const Qe=Qr(Xe),it=Xr(Xe),Ie=Zr(Xe);b(Qe),x(Qe),R(it),S(it),z(Ie),M(Ie),s?.(Xe),n(uM(le,{executor:Qe,validator:it,planning:Ie}[le]),"success")}catch(Ze){if(I.current!==ee)return;le==="executor"?x(Ee):le==="validator"?S(Fe):M(Ke),n(ke(Ze)||"Failed to save model settings","error")}finally{I.current===ee&&_(null)}},[e.id,v,k,C,n,s]),ce=a.useCallback(le=>{const ve=Hl(le);x(ve),!Vl(ve,v)&&me("executor",ve)},[v,me]),ae=a.useCallback(le=>{const ve=Hl(le);S(ve),!Vl(ve,k)&&me("validator",ve)},[k,me]),pe=a.useCallback(le=>{const ve=Hl(le);M(ve),!Vl(ve,C)&&me("planning",ve)},[C,me]),U=a.useCallback(async le=>{const ve=e.id,ee=F,Ee=le===""?null:le;P(Ee),_("thinking");try{const Fe=await Ks(ve,{thinkingLevel:Ee});if(I.current!==ve)return;const Ke=Fe.thinkingLevel??null;W(Ke),P(Ke),s?.(Fe);const Ze=i?.defaultThinkingLevel??"off";n(Ke===null?`Thinking level set to default (${Ze})`:`Thinking level set to ${Ke}`,"success")}catch(Fe){if(I.current!==ve)return;P(ee),n(ke(Fe)||"Failed to save thinking level","error")}finally{I.current===ve&&_(null)}},[e.id,F,i,n,s]),Ne=!v.provider&&!v.modelId,ne=!k.provider&&!k.modelId,xe=!C.provider&&!C.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…"}):g?t.jsxs("div",{className:"model-selector-error",children:["Error loading models: ",g,t.jsx("button",{className:"btn btn-sm",onClick:()=>{h(!0),p(null),cs().then(le=>{o(le.models),c(le.favoriteProviders),d(le.favoriteModels)}).catch(le=>p(le.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:Ne?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",T.provider&&T.modelId?` (${T.provider}/${T.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[v.provider&&t.jsx(An,{provider:v.provider,size:"sm"}),v.provider,"/",v.modelId]})}),t.jsx($n,{id:"executorModel",label:"Executor Model",value:Q,onChange:ce,models:r,disabled:G,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:O,favoriteModels:u,onToggleModelFavorite:J}),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:ne?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",w.provider&&w.modelId?` (${w.provider}/${w.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[k.provider&&t.jsx(An,{provider:k.provider,size:"sm"}),k.provider,"/",k.modelId]})}),t.jsx($n,{id:"validatorModel",label:"Reviewer Model",value:E,onChange:ae,models:r,disabled:G,placeholder:"Select reviewer model…",favoriteProviders:l,onToggleFavorite:O,favoriteModels:u,onToggleModelFavorite:J}),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:xe?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",q.provider&&q.modelId?` (${q.provider}/${q.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[C.provider&&t.jsx(An,{provider:C.provider,size:"sm"}),C.provider,"/",C.modelId]})}),t.jsx($n,{id:"planningModel",label:"Planning Model",value:D,onChange:pe,models:r,disabled:G,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:O,favoriteModels:u,onToggleModelFavorite:J}),t.jsx("small",{children:"The AI model used for task specification (triage phase)."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"thinkingLevel",children:"Thinking Level"}),t.jsx("div",{className:"model-selector-current",children:F===null?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default (",i?.defaultThinkingLevel??"off",")"]}):t.jsx("span",{className:"model-badge model-badge-custom",children:F})}),t.jsxs("select",{id:"thinkingLevel",value:A??"",onChange:le=>U(le.target.value),disabled:G,className:"thinking-level-select",children:[t.jsxs("option",{value:"",children:["Default (",i?.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:Ne&&ne&&xe&&F===null?"Using project or global default models.":"Model settings are up to date."})]})]})}const hM={open:t.jsx(Ro,{size:16}),closed:t.jsx(vr,{size:16}),merged:t.jsx(Hh,{size:16})};function pM({taskId:e,projectId:n,prInfo:s,automationStatus:i,autoMerge:r=!1,prAuthAvailable:o,onPrCreated:l,onPrUpdated:c,addToast:u}){const[d,m]=a.useState(!1),[h,g]=a.useState(""),[p,f]=a.useState(""),[x,v]=a.useState(!1),[b,y]=a.useState(!1),[S,k]=a.useState(null),R=a.useCallback(async()=>{if(h.trim()){v(!0);try{const z=await uy(e,{title:h.trim(),body:p.trim()||void 0},n);l(z),m(!1),g(""),f(""),u(`Created PR #${z.number}`,"success")}catch(z){u(ke(z)||"Failed to create PR","error")}finally{v(!1)}}},[e,h,p,n,l,u]),N=a.useCallback(async()=>{if(s){y(!0);try{const z=await my(e,n);k(z),c(z.prInfo),u("PR status refreshed","success")}catch(z){u(ke(z)||"Failed to refresh PR","error")}finally{y(!1)}}},[e,s,n,c,u]);if(!s)return i==="creating-pr"?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(hs,{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(hs,{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."})]}):d?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(hs,{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:h,onChange:z=>g(z.target.value),disabled:x,className:"pr-input"}),t.jsx("textarea",{placeholder:"PR description (optional)",value:p,onChange:z=>f(z.target.value),disabled:x,className:"pr-textarea",rows:3}),t.jsxs("div",{className:"pr-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>m(!1),disabled:x,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:R,disabled:!h.trim()||x,children:x?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(hs,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>m(!0),disabled:!o,title:o?"Create a PR for this task":"PR auth unavailable — run 'gh auth login'",children:[t.jsx(Zt,{size:14,className:"pr-section-icon--sm"}),"Create PR"]}),!o&&t.jsxs("div",{className:"pr-hint pr-hint--subtle",children:["Run ",t.jsx("code",{children:"gh auth login"})," to enable PR creation."]})]});const M=hM[s.status]??t.jsx(Ro,{size:16}),C=S?.blockingReasons??[];return t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(hs,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsxs("div",{className:`pr-card pr-card--status-${s.status}`,children:[t.jsxs("div",{className:"pr-header",children:[t.jsx("span",{className:"pr-status-icon",children:M}),t.jsx("span",{className:`pr-status-badge pr-status-badge--${s.status}`,children:s.status}),t.jsxs("span",{className:"pr-number",children:["#",s.number]}),t.jsx("div",{className:"pr-spacer"}),t.jsx("button",{className:"btn btn-sm pr-refresh-btn",onClick:N,disabled:b,title:"Refresh PR status",children:t.jsx(Nn,{size:14,style:{verticalAlign:"middle",opacity:b?.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})]}),i==="merging-pr"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:"fn is merging this pull request automatically."}),i==="awaiting-pr-checks"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:C.length>0?`Waiting for: ${C.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(bi,{size:14}),s.commentCount]}),t.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[t.jsx(lx,{size:14}),"View on GitHub"]})]})]})]})}const Fm=2e3;function fM(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function gM(e){return e==="agent"||e==="system"}function xM({task:e,onTaskUpdated:n,addToast:s,currentAuthor:i="user",projectId:r}){const[o,l]=a.useState(""),[c,u]=a.useState(null),[d,m]=a.useState(""),[h,g]=a.useState(!1),[p,f]=a.useState(null),x=a.useMemo(()=>[...e.comments||[]].sort((M,C)=>new Date(C.createdAt).getTime()-new Date(M.createdAt).getTime()),[e.comments]),v=o.length>Fm;async function b(){const M=o.trim();if(M){g(!0);try{const C=await qv(e.id,M,r);l(""),n?.(C),s("Comment added","success")}catch(C){s(ke(C)||"Failed to add comment","error")}finally{g(!1)}}}async function y(M){const C=d.trim();if(C){g(!0);try{const z=await Fv(e.id,M,C,r);u(null),m(""),n?.(z),s("Comment updated","success")}catch(z){s(ke(z)||"Failed to update comment","error")}finally{g(!1)}}}async function S(M){f(M);try{const C=await Ov(e.id,M,r);n?.(C),s("Comment deleted","success")}catch(C){s(ke(C)||"Failed to delete comment","error")}finally{f(null)}}function k(M){M.key==="Enter"&&(M.ctrlKey||M.metaKey)&&(M.preventDefault(),b())}return t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Comments"}),x.length===0?t.jsx("div",{className:"detail-log-empty",children:"No comments yet."}):t.jsx("div",{className:"detail-activity-list",children:x.map(M=>{const C=M.author===i,z=c===M.id,A=gM(M.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:[A?t.jsx("span",{className:"ai-guidance-badge","data-testid":"ai-guidance-badge",children:"AI Guidance"}):t.jsx("strong",{children:M.author}),t.jsx("span",{className:"detail-log-timestamp",children:fM(M)})]}),C&&!z?t.jsxs("div",{className:"comments-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{u(M.id),m(M.text)},children:"Edit"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void S(M.id),disabled:p===M.id,children:p===M.id?"Deleting…":"Delete"})]}):null]}),z?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:d,onChange:P=>m(P.target.value),rows:3,className:"comments-textarea"}),t.jsxs("div",{className:"comments-edit-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{u(null),m("")},disabled:h,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void y(M.id),disabled:h||!d.trim(),children:"Save"})]})]}):t.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:M.text})]},M.id)})}),t.jsxs("div",{className:"comments-compose-form",children:[t.jsx("textarea",{value:o,onChange:M=>l(M.target.value),onKeyDown:k,rows:3,placeholder:"Add a comment",className:"comments-textarea"}),t.jsxs("div",{className:"comments-footer-row",children:[t.jsxs("span",{className:`comments-char-count${v?" comments-char-count--over":""}`,children:[o.length," / ",Fm]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void b(),disabled:h||!o.trim()||v,children:h?"Posting…":"Add Comment"})]})]})]})}function bM(e){return e?e.slice(0,7):"Unknown"}function vM({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:bM(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"}),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 Hf(e){return e.split(`
|
|
647
|
+
`).map((s,i)=>{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}
|
|
648
|
+
`},i):t.jsx(lo.Fragment,{children:`${s}
|
|
649
|
+
`},i)})}function Om(e,n=60){if(!e||e.length<=n)return e;if(n<4)return e.slice(0,n);const s="...",i=e.lastIndexOf("/");if(i===-1){const m=Math.max(1,n-s.length);return e.slice(0,m)+s}const r=[];for(let m=1;m<e.length;m++)e[m]==="/"&&r.push(m);const o=n-s.length;let l=null,c=-1;for(let m=r.length-1;m>=0;m--){const h=r[m],g=e.slice(h);if(g.length>o)continue;const p=o-g.length;for(let f=0;f<r.length;f++){const x=r[f],v=e.slice(0,x);v.length<=p&&v.length+s.length+g.length<=n&&v.length+g.length>c&&(c=v.length+g.length,l=v+s+g)}}if(l)return l;const u=e.slice(i);if(s.length+u.length<=n)return s+u;const d=n-s.length;return s+e.slice(e.length-d)}function yM(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function kM({isOpen:e,taskId:n,files:s,stats:i,mergeDetails:r,column:o,onClose:l,onRefresh:c}){const[u,d]=a.useState(null),[m,h]=a.useState(!0),g=a.useRef(null);Xs(g,e,"fusion:changes-diff-modal-size");const p=wi(l);a.useEffect(()=>{s.length>0&&u===null&&d(0)},[s,u]);const f=a.useCallback(()=>{d(y=>y!==null&&y>0?y-1:y)},[]),x=a.useCallback(()=>{d(y=>y!==null&&y<s.length-1?y+1:y)},[]);if(a.useEffect(()=>{if(!e)return;const y=S=>{if(S.key==="Escape"){l();return}S.key==="ArrowUp"&&(S.metaKey||S.ctrlKey)&&(S.preventDefault(),f()),S.key==="ArrowDown"&&(S.metaKey||S.ctrlKey)&&(S.preventDefault(),x())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[e,l,f,x]),!e)return null;const v=u!==null?s[u]: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:g,children:[t.jsxs("div",{className:"modal-header changes-diff-modal-header",children:[t.jsxs("div",{className:"changes-diff-header-title",children:[t.jsx(Is,{size:18}),t.jsxs("span",{children:["Changes — ",n]}),t.jsxs("span",{className:"changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",i.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",i.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:f,disabled:u===null||u<=0,title:"Previous file (Ctrl+↑)","aria-label":"Previous file",children:t.jsx(Ao,{size:14})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:u!==null?`${u+1}/${s.length}`:`—/${s.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:x,disabled:u===null||u>=s.length-1,title:"Next file (Ctrl+↓)","aria-label":"Next file",children:t.jsx(hn,{size:14})})]}),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(ho,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx(Nn,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(Ot,{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(lr,{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 ${u===S?"selected":""}`,onClick:()=>d(S),title:y.path,children:[t.jsx("span",{className:`changes-file-status changes-file-status--${y.status}`,children:yM(y.status)}),t.jsx("span",{className:"changes-diff-file-path",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:Hf(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(Is,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function Um(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function jM({taskId:e,worktree:n,projectId:s,column:i,mergeDetails:r,modifiedFiles:o}){const[l,c]=a.useState([]),[u,d]=a.useState({filesChanged:0,additions:0,deletions:0}),[m,h]=a.useState(!0),[g,p]=a.useState(null),[f,x]=a.useState(new Set),[v,b]=a.useState(null),[y,S]=a.useState(!0),[k,R]=a.useState(!1),N=i==="done",M=N&&!!r?.commitSha,C=i==="in-progress"||i==="in-review"||M,z=a.useCallback(async()=>{if(!C){h(!1);return}try{h(!0),p(null);const $=await lp(e,void 0,s),_=$.files.map(I=>({path:I.path,status:I.status,additions:I.additions,deletions:I.deletions,patch:I.patch}));c(_),d($.stats),_.length>0&&(x(new Set([_[0].path])),b(0))}catch($){p(ke($)||"Failed to load diff")}finally{h(!1)}},[e,s,C]);a.useEffect(()=>{z()},[z]);const A=$=>{x(_=>{const I=new Set(_);if(I.has($))I.delete($);else{I.add($);const O=l.findIndex(J=>J.path===$);O!==-1&&b(O)}return I})},P=$=>{if($<0||$>=l.length)return;const _=l[$].path;x(new Set([_])),b($)},F=v!==null&&v>0,W=v!==null&&v<l.length-1;if(m)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--loading",children:[t.jsx("div",{className:"loading-spinner"}),t.jsx("span",{children:"Loading changes..."})]})});if(g)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--error",children:[t.jsx(Xn,{size:16}),t.jsxs("span",{children:["Error loading changes: ",g]})]})});if(!N&&!n)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Is,{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(N&&!M){const $=r?.filesChanged,_=r?.insertions,I=r?.deletions,O=$!=null||_!=null||I!=null;return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Is,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:O?`Merge summary: ${$??0} file${($??0)===1?"":"s"} changed, +${_??0} additions, -${I??0} deletions.`:"No merge commit was recorded for this task."})]})})}return l.length===0?N&&o&&o.length>0?t.jsxs("div",{className:"detail-section task-changes-tab",children:[N&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(lr,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Is,{size:24}),t.jsxs("p",{children:[o.length," file",o.length===1?"":"s"," modified during execution."]}),t.jsx("span",{className:"task-changes-state-hint",children:"The recorded merge commit has no diff (likely collapsed into a squash on main). Showing file paths only — patches unavailable."})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:o.map($=>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:Um("unknown")}),t.jsx("span",{className:"changes-file-path",title:$,children:Om($)})]})},$))})]}):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Is,{size:24}),t.jsx("p",{children:"No files modified."}),t.jsx("span",{className:"task-changes-state-hint",children:N?"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:[N&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(lr,{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(Is,{size:16}),"Files Changed (",u.filesChanged,")"]}),t.jsxs("span",{className:"task-changes-stats changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",u.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",u.deletions]})]})]}),t.jsxs("div",{className:"changes-header-actions-wrapper",children:[t.jsxs("div",{className:"changes-header-actions",children:[l.length>0&&t.jsxs("div",{className:"changes-nav",children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>F&&P(v-1),disabled:!F,title:"Previous file","aria-label":"Previous file",children:t.jsx(Ao,{size:14})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:v!==null?`${v+1}/${l.length}`:`—/${l.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>W&&P(v+1),disabled:!W,title:"Next file","aria-label":"Next file",children:t.jsx(hn,{size:14})})]}),t.jsx("button",{className:`btn btn-sm ${y?"btn-primary":""}`,onClick:()=>S($=>!$),title:y?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(ho,{size:14})})]}),t.jsxs("div",{className:"changes-header-actions-secondary",children:[t.jsx("button",{className:"btn btn-sm",onClick:z,disabled:m,children:"Refresh"}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>R(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:t.jsx($o,{size:14})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map($=>{const _=f.has($.path);return t.jsxs("div",{className:`changes-file-item ${_?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>A($.path),children:[t.jsx("span",{className:"changes-file-toggle",children:_?t.jsx(qt,{size:14}):t.jsx(hn,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${$.status}`,title:$.status,children:Um($.status)}),t.jsx("span",{className:"changes-file-path",title:$.path,children:Om($.path)}),t.jsxs("span",{className:"changes-file-stat",title:`+${$.additions} -${$.deletions}`,children:["+",$.additions," -",$.deletions]})]}),_&&$.patch&&t.jsx("div",{className:"changes-file-content",children:t.jsx("pre",{className:`changes-diff-patch ${y?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:Hf($.patch)})})})]},$.path)})}),t.jsx(kM,{isOpen:k,taskId:e,files:l,stats:u,mergeDetails:r,column:i,onClose:()=>R(!1),onRefresh:z})]})}function Bm(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function wM(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function kD(e,n){const s=wM(e),i=new Set(n.map(c=>c.id));if(!i.has(s))return s;const r=30;let o=s,l=1;for(;i.has(o)&&l<100;){const c=`-${l}`;o=`${s.slice(0,r-c.length)}${c}`,l++}return o}function Hm(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function NM(e){return e==="online"?"task-form-node-status--online":e==="connecting"?"task-form-node-status--connecting":e==="error"?"task-form-node-status--error":"task-form-node-status--offline"}const qm=["image/png","image/jpeg","image/gif","image/webp"];function SM(e,n,s){const i=e==="post-merge"?"phase-badge--post-merge":"phase-badge--pre-merge";return t.jsx("span",{className:`phase-badge ${i}`,"data-testid":`${s}-${n}`,children:e==="post-merge"?"Post-merge":"Pre-merge"})}function qf({mode:e,description:n,onDescriptionChange:s,title:i,onTitleChange:r,dependencies:o,onDependenciesChange:l,nodeId:c,onNodeIdChange:u,nodeOptions:d,nodeOverrideDisabled:m=!1,nodeOverrideDisabledReason:h,priority:g,onPriorityChange:p,executorModel:f,onExecutorModelChange:x,validatorModel:v,onValidatorModelChange:b,planningModel:y,onPlanningModelChange:S,thinkingLevel:k,onThinkingLevelChange:R,presetMode:N,onPresetModeChange:M,selectedPresetId:C,onSelectedPresetIdChange:z,selectedWorkflowSteps:A,onWorkflowStepsChange:P,onDefaultOnApplied:F,pendingImages:W,onImagesChange:$,tasks:_,projectId:I,disabled:O=!1,addToast:J,isActive:Q=!0,onAutoSaveDescription:E,onPlanningMode:D,onSubtaskBreakdown:T,onClose:w,renderBelowPrimary:q,renderBelowModelConfiguration:G,hideDependencies:me,autoExpandMoreOptionsOnSelection:ce=!0,reviewLevel:ae,onReviewLevelChange:pe,executionMode:U,onExecutionModeChange:Ne}){const ne=(me?!1:o.length>0)||W.length>0||A.length>0||N!=="default"||(g??ps)!==ps||f!==""||v!==""||(y||"")!==""||(k||"")!==""||ae!==void 0||U==="fast"||(c||"")!=="",[xe,le]=a.useState(!1),[ve,ee]=a.useState(ce?ne:!1),[Ee,Fe]=a.useState(""),[Ke,Ze]=a.useState([]),[Xe,Qe]=a.useState([]),[it,Ie]=a.useState([]),[Ge,se]=a.useState(!1),[ye,Z]=a.useState(null),[Te,ze]=a.useState([]),[be,Me]=a.useState("idle"),[Be,lt]=a.useState(!1),[je,ie]=a.useState(!1),[Ae,he]=a.useState(!1),Re=a.useRef(null),Je=a.useRef(null),$e=a.useRef(null),de=a.useRef(null),re=a.useRef(null),ue=a.useRef(null),Pe=a.useRef(null),Se=a.useRef(!1),fe=a.useRef(ne),tt=a.useRef(n.trim()),ut=a.useRef(n.trim());a.useEffect(()=>{Q&&(se(!0),cs().then(j=>{Ze(j.models),Qe(j.favoriteProviders),Ie(j.favoriteModels)}).catch(()=>{}).finally(()=>se(!1)),Lo(I).then(j=>Z(j)).catch(()=>Z(null)),zo(I).then(j=>ze(j.filter(V=>V.enabled))).catch(()=>ze([])))},[Q,I]);const vt=ye?.modelPresets||[],gt=vt.find(j=>j.id===C),dt=(me?!1:o.length>0)||W.length>0||A.length>0||N!=="default"||(g??ps)!==ps||f!==""||v!==""||(y||"")!==""||(k||"")!==""||ae!==void 0||U==="fast"||(c||"")!=="";a.useEffect(()=>{if(e!=="create"||!Q||!ye?.autoSelectModelPreset)return;const j=(ye.defaultPresetBySize,void 0);if(j){const V=Bm(j);z(j.id),M("preset"),x(V.executorValue),b(V.validatorValue)}},[Q,ye,vt,e]);const wt=a.useRef(!1);a.useEffect(()=>{if(e!=="create"||!Q||wt.current||Te.length===0)return;const j=Te.filter(De=>De.defaultOn);if(j.length===0)return;wt.current=!0;const V=j.map(De=>De.id);P(V),F?.(V)},[e,Q,Te]),a.useEffect(()=>{Q||(wt.current=!1)},[Q]),a.useEffect(()=>{if(!ce){fe.current=dt;return}dt&&!fe.current&&ee(!0),fe.current=dt},[dt,ce]),a.useEffect(()=>{ve||(le(!1),Fe(""))},[ve]),a.useEffect(()=>{e!=="edit"||!Q||de.current&&(de.current.focus(),de.current.select())},[e,Q]),a.useEffect(()=>{if(!xe)return;const j=V=>{Je.current&&!Je.current.contains(V.target)&&le(!1)};return document.addEventListener("mousedown",j),()=>document.removeEventListener("mousedown",j)},[xe]),a.useEffect(()=>{(e!=="edit"||O)&&he(!1)},[e,O]),a.useEffect(()=>{if(e!=="edit"){Me("idle");return}const j=n.trim();tt.current=j,ut.current=j,Me("idle")},[e]),a.useEffect(()=>{if(e!=="edit"||!E||!Q)return;const j=n.trim(),V=tt.current;if(j===V||j===ut.current){ue.current&&(clearTimeout(ue.current),ue.current=null),Se.current||Me("idle");return}return ue.current&&clearTimeout(ue.current),ue.current=setTimeout(async()=>{if(!Se.current){Se.current=!0,Me("saving");try{await E(j),ut.current=j,Me("saved"),Pe.current&&clearTimeout(Pe.current),Pe.current=setTimeout(()=>{Me("idle"),Pe.current=null},2e3)}catch{Me("idle")}finally{Se.current=!1,ue.current=null}}},1500),()=>{ue.current&&(clearTimeout(ue.current),ue.current=null)}},[e,n,E,Q]),a.useEffect(()=>()=>{ue.current&&clearTimeout(ue.current),Pe.current&&clearTimeout(Pe.current)},[]),a.useEffect(()=>{if(!Be)return;const j=V=>{Re.current&&!Re.current.contains(V.target)&<(!1)};return document.addEventListener("mousedown",j),()=>document.removeEventListener("mousedown",j)},[Be]);const Mt=a.useCallback(j=>{const V=j.clipboardData?.items;if(V)for(let De=0;De<V.length;De++){const nt=V[De];if(nt.type.startsWith("image/")){const St=nt.getAsFile();if(St&&qm.includes(St.type)){j.preventDefault(),$([...W,{file:St,previewUrl:URL.createObjectURL(St)}]);return}}}},[W,$]),yt=a.useCallback(j=>{j.preventDefault();const V=j.dataTransfer.files;for(let De=0;De<V.length;De++){const nt=V[De];if(qm.includes(nt.type)){$([...W,{file:nt,previewUrl:URL.createObjectURL(nt)}]);return}}},[W,$]),Et=a.useCallback(j=>{const V=W[j];V&&URL.revokeObjectURL(V.previewUrl),$(W.filter((De,nt)=>nt!==j))},[W,$]),Nt=a.useCallback(j=>{l(o.includes(j)?o.filter(V=>V!==j):[...o,j])},[o,l]),Tt=(j,V)=>j.length>V?j.slice(0,V)+"…":j,Ht=a.useCallback(j=>{s(j.target.value);const V=j.target;V.style.height="auto",V.style.height=V.scrollHeight+"px"},[s]),Ut=a.useCallback(()=>{he(j=>!j)},[]),Vt=a.useCallback(j=>{!Ae||j.key!=="Escape"||(j.preventDefault(),j.stopPropagation(),he(!1))},[Ae]),zt=a.useCallback(async j=>{const V=n.trim();if(!(!V||je)){ie(!0);try{const De=await sp(V,j,I);s(De),lt(!1),J("Description refined with AI","success"),$e.current&&($e.current.style.height="auto",$e.current.style.height=$e.current.scrollHeight+"px")}catch(De){const nt=ip(De);J(nt,"error")}finally{ie(!1)}}},[n,je,J,s,I]),Ct=a.useCallback(async j=>{const V=Xe,nt=V.includes(j)?V.filter(St=>St!==j):[j,...V];Qe(nt);try{await sn({favoriteProviders:nt,favoriteModels:it})}catch{Qe(V)}},[Xe,it]),At=a.useCallback(async j=>{const V=it,nt=V.includes(j)?V.filter(St=>St!==j):[j,...V];Ie(nt);try{await sn({favoriteProviders:Xe,favoriteModels:nt})}catch{Ie(V)}},[it,Xe]),kt=a.useCallback(j=>{if(j<=0)return;const V=[...A];[V[j-1],V[j]]=[V[j],V[j-1]],P(V)},[A,P]),Kt=a.useCallback(j=>{if(j>=A.length-1)return;const V=[...A];[V[j],V[j+1]]=[V[j+1],V[j]],P(V)},[A,P]),$t=a.useCallback(j=>{P(A.filter(V=>V!==j))},[A,P]),B=new Map;for(const j of Te)B.set(j.id,{name:j.name,description:j.description});const ge=_.filter(j=>!o.includes(j.id)).sort((j,V)=>{const De=V.createdAt.localeCompare(j.createdAt);if(De!==0)return De;const nt=parseInt(j.id.slice(j.id.lastIndexOf("-")+1),10)||0;return(parseInt(V.id.slice(V.id.lastIndexOf("-")+1),10)||0)-nt}),te=Ee?ge.filter(j=>j.id.toLowerCase().includes(Ee.toLowerCase())||j.title&&j.title.toLowerCase().includes(Ee.toLowerCase())||j.description&&j.description.toLowerCase().includes(Ee.toLowerCase())):ge;return t.jsxs("div",{className:"task-form",onDrop:yt,onDragOver:j=>j.preventDefault(),onPaste:Mt,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:de,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:i||"",onChange:j=>r(j.target.value),disabled:O})]}),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${be==="idle"?"":" is-visible"}`,"aria-live":"polite",children:be==="saving"?"Saving...":be==="saved"?"Saved":""})]}),t.jsxs("div",{className:`description-with-refine${Ae?" description--fullscreen":""}`,ref:Re,onKeyDown:Vt,children:[Ae&&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:Ut,"aria-label":"Collapse description",title:"Collapse description",children:t.jsx(yr,{size:14})})]}),t.jsx("textarea",{ref:$e,autoFocus:e==="create",id:"task-form-description",value:n,onChange:Ht,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:O||je}),(()=>{const j=!!n.trim()&&!O;return t.jsxs(t.Fragment,{children:[!Ae&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${j?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:Ut,"aria-label":"Expand description",title:"Expand description",children:t.jsx($o,{size:14})}),j&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${je?"refine-button--loading":""}`,onClick:()=>lt(V=>!V),disabled:je,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(qn,{size:12,style:{verticalAlign:"middle"}}),je?"Refining...":"Refine"]})]})})(),Be&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:j=>j.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>zt("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:()=>zt("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:()=>zt("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:()=>zt("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"&&(D||T)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[D&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const j=n.trim();if(!j){J("Enter a description first","error");return}w?.(),D(j)},disabled:O||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),T&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const j=n.trim();if(!j){J("Enter a description first","error");return}w?.(),T(j)},disabled:O||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),q,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>ee(j=>!j),"aria-expanded":ve,"aria-controls":"task-form-more-options",disabled:O,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),ve?t.jsx(li,{size:14}):t.jsx(qt,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${ve?"":" collapsed"}`,"aria-hidden":!ve,hidden:!ve,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Attachments"}),W.length>0&&t.jsx("div",{className:"inline-create-previews",children:W.map((j,V)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:j.previewUrl,alt:j.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>Et(V),disabled:O,title:"Remove image",children:"×"})]},j.previewUrl))}),t.jsx("input",{ref:re,type:"file",accept:"image/*",onChange:j=>{const V=j.target.files?.[0];V&&($([...W,{file:V,previewUrl:URL.createObjectURL(V)}]),j.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>re.current?.click(),disabled:O,children:"Attach Screenshot"}),t.jsx("small",{children:"You can also paste images or drag & drop"})]}),u&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"task-node-select",children:"Execution Node Override"}),t.jsxs("select",{id:"task-node-select",className:"select",value:c??"",onChange:j=>u(j.target.value||void 0),disabled:O||m,children:[t.jsx("option",{value:"",children:"Use project default / local"}),(d??[]).map(j=>t.jsxs("option",{value:j.id,children:[j.name," (",Hm(j.status),")"]},j.id))]}),(()=>{const j=(d??[]).find(V=>V.id===c);return j?t.jsxs("div",{className:`task-form-node-status ${NM(j.status)}`,children:[t.jsx("span",{className:"task-form-node-status__dot","aria-hidden":"true"}),t.jsx("span",{children:`Selected node: ${Hm(j.status)}`})]}):null})(),t.jsx("small",{children:h??"Task override takes priority over project default node routing."})]}),!me&&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:Je,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>le(j=>!j),disabled:O,children:o.length>0?`${o.length} selected`:"Add dependencies"}),xe&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Ee,onChange:j=>Fe(j.target.value),onClick:j=>j.stopPropagation()}),te.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):te.map(j=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(j.id)?" selected":""}`,onClick:()=>Nt(j.id),onMouseDown:V=>V.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:j.id}),t.jsx("span",{className:"dep-dropdown-title",children:Tt(j.title||j.description||j.id,30)})]},j.id))]})]}),o.length>0&&t.jsx("div",{className:"selected-deps",children:o.map(j=>t.jsxs("span",{className:"dep-chip",children:[j,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>Nt(j),disabled:O,children:"×"})]},j))})]})}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Model Configuration"}),p&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"task-priority",className:"model-select-label",children:"Priority"}),t.jsx("select",{id:"task-priority","data-testid":"task-priority-select",value:g??ps,onChange:j=>p(j.target.value),disabled:O,children:ed.map(j=>t.jsx("option",{value:j,children:j[0].toUpperCase()+j.slice(1)},j))})]}),Ne&&U!==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:U,onChange:j=>Ne(j.target.value),disabled:O,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),Ge?t.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):Ke.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:N==="preset"?C:N,onChange:j=>{const V=j.target.value;if(V==="default"){M("default"),z(""),x(""),b("");return}if(V==="custom"){M("custom"),z("");return}const De=vt.find(St=>St.id===V),nt=Bm(De);M("preset"),z(V),x(nt.executorValue),b(nt.validatorValue)},disabled:O,children:[t.jsx("option",{value:"default",children:"Use default"}),vt.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,vt.map(j=>t.jsx("option",{value:j.id,children:j.name},j.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),N==="preset"&>?t.jsxs("small",{children:["Using preset: ",gt.name]}):null,N==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>M("custom"),disabled:O,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($n,{id:"executor-model",label:"Executor Model",value:f,onChange:j=>{M("custom"),z(""),x(j)},models:Ke,disabled:O||N==="preset",favoriteProviders:Xe,onToggleFavorite:Ct,favoriteModels:it,onToggleModelFavorite:At})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Reviewer"}),t.jsx($n,{id:"validator-model",label:"Reviewer Model",value:v,onChange:j=>{M("custom"),z(""),b(j)},models:Ke,disabled:O||N==="preset",favoriteProviders:Xe,onToggleFavorite:Ct,favoriteModels:it,onToggleModelFavorite:At})]}),S&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),t.jsx($n,{id:"planning-model",label:"Planning Model",value:y||"",onChange:j=>{M("custom"),z(""),S(j)},models:Ke,disabled:O||N==="preset",favoriteProviders:Xe,onToggleFavorite:Ct,favoriteModels:it,onToggleModelFavorite:At})]}),R&&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:k||"",onChange:j=>R(j.target.value),disabled:O||N==="preset",children:[t.jsxs("option",{value:"",children:["Default (",ye?.defaultThinkingLevel??"off",")"]}),t.jsx("option",{value:"off",children:"Off"}),t.jsx("option",{value:"minimal",children:"Minimal"}),t.jsx("option",{value:"low",children:"Low"}),t.jsx("option",{value:"medium",children:"Medium"}),t.jsx("option",{value:"high",children:"High"})]})]}),pe&&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:ae??"",onChange:j=>pe(j.target.value===""?void 0:parseInt(j.target.value,10)),disabled:O,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"})]})]})]})]}),G,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:Te.length>0&&Te.map(j=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${j.id}`,children:[t.jsx("input",{type:"checkbox",checked:A.includes(j.id),onChange:V=>{P(V.target.checked?[...A,j.id]:A.filter(De=>De!==j.id))},disabled:O}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[j.name,SM(j.phase||"pre-merge",j.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:j.description})]})]},j.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((j,V)=>{const De=B.get(j);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${j}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:V+1}),t.jsx("span",{className:"workflow-step-order-name",children:De?.name||j}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>kt(V),disabled:O||V===0,"data-testid":`workflow-step-move-up-${j}`,title:"Move up",children:t.jsx(li,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Kt(V),disabled:O||V===A.length-1,"data-testid":`workflow-step-move-down-${j}`,title:"Move down",children:t.jsx(qt,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>$t(j),disabled:O,"data-testid":`workflow-step-remove-${j}`,title:"Remove",children:t.jsx(Ot,{size:14})})]})]},j)})]})]})]})]})}const Vm={pre:({children:e,className:n,...s})=>t.jsx("pre",{...s,className:["workflow-markdown-pre",n].filter(Boolean).join(" "),children:e}),table:({children:e,className:n,...s})=>t.jsx("table",{...s,className:["workflow-markdown-table",n].filter(Boolean).join(" "),children:e})};function CM(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function EM(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 _M(e){return e?new Date(e).toLocaleString():null}function MM(e){const n=e.split(`
|
|
650
|
+
`);return n.length<=1?e:`${n.length} lines`}function eo(e,n,s){const i=e==="post-merge"?"phase-badge--post-merge":"phase-badge--pre-merge";return t.jsx("span",{className:`phase-badge ${i}`,"data-testid":`${s}-${n}`,children:e==="post-merge"?"Post-merge":"Pre-merge"})}function AM({entries:e,startedAt:n,stepId:s}){const i=a.useRef(null),r=new Date(n).getTime(),o=e.filter(l=>new Date(l.timestamp).getTime()>=r);return a.useEffect(()=>{const l=i.current;l&&(l.scrollTop=l.scrollHeight)},[o.length]),e.length===0?t.jsx("div",{className:"workflow-live-log","data-testid":`workflow-live-log-${s}`,children:t.jsx("div",{className:"workflow-live-log-empty",children:"Waiting for agent output…"})}):t.jsx("div",{ref:i,className:"workflow-live-log","data-testid":`workflow-live-log-${s}`,children:o.map((l,c)=>l.type==="tool"?t.jsxs("div",{className:"workflow-live-log-tool",children:["⚡ ",l.text,l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",l.detail]})]},c):l.type==="tool_result"?t.jsxs("div",{className:"workflow-live-log-tool-result",children:["✓ ",l.text,l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",l.detail]})]},c):l.type==="tool_error"?t.jsxs("div",{className:"workflow-live-log-tool-error",children:["✗ ",l.text,l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",l.detail]})]},c):l.type==="thinking"?t.jsx("div",{className:"workflow-live-log-thinking",children:l.text},c):t.jsx("span",{className:"workflow-live-log-text",children:l.text},c))})}function RM({taskId:e,results:n,loading:s,enabledWorkflowSteps:i,canEdit:r,projectId:o,isTaskInProgress:l,onWorkflowStepsChange:c}){const[u,d]=a.useState({}),[m,h]=a.useState({}),[g,p]=a.useState(null),[f,x]=a.useState([]),[v,b]=a.useState(!1),y=n.some(w=>w.status==="pending"),{entries:S}=Uf(e,!!l&&y,o);a.useEffect(()=>{let w=!1;return zo(o).then(q=>{w||x(q.filter(G=>G.enabled))}).catch(()=>{w||x([])}),()=>{w=!0}},[o]);const k=i??[],R=a.useMemo(()=>f.map(w=>({id:w.id,name:w.name,description:w.description,phase:w.phase||"pre-merge"})),[f]),N=a.useMemo(()=>new Map(R.map(w=>[w.id,w])),[R]),M=w=>{d(q=>({...q,[w]:!q[w]}))},C=w=>{h(q=>{const G=q[w]??"markdown";return{...q,[w]:G==="markdown"?"plain":"markdown"}})},z=w=>{p(w)},A=()=>{p(null)};a.useEffect(()=>{if(!g)return;const w=q=>{q.key==="Escape"&&A()};return document.addEventListener("keydown",w),()=>{document.removeEventListener("keydown",w)}},[g]);const P=a.useCallback((w,q)=>{if(c){if(q){if(k.includes(w)){c(k);return}c([...k,w]);return}c(k.filter(G=>G!==w))}},[c,k]),F=a.useCallback(w=>{if(!c||w<=0)return;const q=[...k];[q[w-1],q[w]]=[q[w],q[w-1]],c(q)},[c,k]),W=a.useCallback(w=>{if(!c||w>=k.length-1)return;const q=[...k];[q[w],q[w+1]]=[q[w+1],q[w]],c(q)},[c,k]),$=a.useCallback(w=>{c&&c(k.filter(q=>q!==w))},[c,k]),_=n.length>0,I=k.length>0;a.useEffect(()=>{r||b(!1)},[r]);const O=a.useMemo(()=>k.map(w=>{const q=N.get(w);return{id:w,name:q?.name||w,description:q?.description||"Step definition not found.",phase:q?.phase||"pre-merge"}}),[k,N]),J=()=>!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:R.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:k.includes(w.id),onChange:q=>P(w.id,q.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[w.name,eo(w.phase,w.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:w.description})]})]},w.id))})]}),k.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),k.map((w,q)=>{const G=N.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:q+1}),t.jsx("span",{className:"workflow-step-order-name",children:G?.name||w}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>F(q),disabled:q===0,"data-testid":`workflow-step-move-up-${w}`,title:"Move up",children:t.jsx(li,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>W(q),disabled:q===k.length-1,"data-testid":`workflow-step-move-down-${w}`,title:"Move down",children:t.jsx(qt,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>$(w),"data-testid":`workflow-step-remove-${w}`,title:"Remove",children:t.jsx(Ot,{size:14})})]})]},w)})]})]}),Q=()=>{if(s)return t.jsxs("div",{className:"workflow-results-loading","data-testid":"workflow-results-loading",children:[t.jsx("div",{className:"workflow-results-spinner"}),t.jsx("span",{children:"Loading workflow results…"})]});if(!_)return t.jsxs("div",{className:"workflow-results-empty","data-testid":"workflow-results-empty",children:[t.jsx("p",{children:"No workflow steps configured for this task."}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."})]});const w=n.filter(ae=>ae.status==="passed").length,q=n.filter(ae=>ae.status==="failed").length,G=n.filter(ae=>ae.status==="skipped").length,me=n.filter(ae=>ae.status==="pending").length,ce=[`${n.length} step${n.length!==1?"s":""}`];return w>0&&ce.push(`${w} passed`),q>0&&ce.push(`${q} failed`),G>0&&ce.push(`${G} skipped`),me>0&&ce.push(`${me} 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:ce.join(" · ")}),n.map((ae,pe)=>{const U=ae.phase||"pre-merge",Ne=u[ae.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${ae.status}`,"data-testid":`workflow-result-item-${ae.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[ae.workflowStepName,eo(U,ae.workflowStepId,"workflow-result-phase")]}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${ae.status}`,"data-testid":`workflow-result-badge-${ae.workflowStepId}`,children:CM(ae.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[ae.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",_M(ae.startedAt)]}),ae.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:EM(ae.startedAt,ae.completedAt)})]}),ae.status==="pending"&&ae.startedAt?t.jsx(AM,{entries:S,startedAt:ae.startedAt,stepId:ae.workflowStepId}):ae.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",{className:"workflow-result-toggle",onClick:()=>M(ae.workflowStepId),"data-testid":`workflow-result-toggle-${ae.workflowStepId}`,children:Ne?"Hide output":"Show output"}),!Ne&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${ae.workflowStepId}`,children:MM(ae.output)}),Ne&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>C(ae.workflowStepId),"data-testid":`workflow-result-mode-toggle-${ae.workflowStepId}`,title:(m[ae.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(m[ae.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-result-expand-toggle",onClick:()=>z(ae.workflowStepId),"data-testid":`workflow-result-expand-${ae.workflowStepId}`,title:"Expand output",children:t.jsx($o,{size:12})})]})]}),Ne&&t.jsx("div",{className:`workflow-result-output${(m[ae.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${ae.workflowStepId}`,children:(m[ae.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(ci,{remarkPlugins:[di],components:Vm,children:ae.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:ae.output})})]}):null]},`${ae.workflowStepId}-${pe}`)})]})},E=r?t.jsx("button",{type:"button",className:"modal-edit-btn workflow-results-edit-toggle",onClick:()=>b(w=>!w),"data-testid":"workflow-steps-edit-toggle","aria-label":v?"Done editing workflow steps":"Edit workflow steps",title:v?"Done":"Edit",children:v?t.jsxs(t.Fragment,{children:[t.jsx(Mn,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(Yn,{size:14}),"Edit"]})}):null,D=!s&&!_&&I,T=r&&_;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:[O.length," step",O.length===1?"":"s"]})]}),E]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:O.map(w=>t.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${w.id}`,children:[t.jsxs("div",{className:"workflow-configured-name",children:[w.name,eo(w.phase,w.id,"workflow-configured-phase")]}),t.jsx("p",{className:"workflow-configured-description",children:w.description})]},w.id))}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."}),J()]}):t.jsxs(t.Fragment,{children:[T&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:"Workflow Steps"}),E]}),Q(),J()]}),g&&(()=>{const w=n.find(me=>me.workflowStepId===g);if(!w)return null;const q=m[w.workflowStepId]??"markdown",G=w.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:me=>{me.target===me.currentTarget&&A()},"data-testid":"workflow-output-modal",children:t.jsxs("div",{className:"workflow-output-modal",role:"dialog","aria-modal":"true",children:[t.jsxs("div",{className:"workflow-output-modal-header",children:[t.jsxs("div",{className:"workflow-output-modal-title",children:[t.jsx("span",{className:"workflow-output-modal-name",children:w.workflowStepName}),eo(G,w.workflowStepId,"workflow-output-modal-phase")]}),t.jsxs("div",{className:"workflow-output-modal-controls",children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>C(w.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:q==="markdown"?"Switch to plain text":"Switch to markdown",children:q==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-output-modal-close",onClick:A,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:t.jsx(Ot,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${q==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:q==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(ci,{remarkPlugins:[di],components:Vm,children:w.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:w.output})})})]})})})()]})}const Wm={online:"🟢",offline:"🔴",connecting:"🟡",error:"🔴"};function TM(e){return e==="block"?"Block execution":e==="fallback-local"?"Fall back to local":"Not configured"}function PM(e){return e!==void 0&&e!=="online"}function IM({task:e,settings:n,addToast:s,onTaskUpdated:i}){const[r,o]=a.useState([]),[l,c]=a.useState(!1),[u,d]=a.useState(null),[m,h]=a.useState(e.nodeId??""),[g,p]=a.useState(!1),f=a.useRef(e.id);a.useEffect(()=>{f.current=e.id,h(e.nodeId??""),p(!1)},[e.id,e.nodeId]),a.useEffect(()=>{c(!0),d(null),xo().then(A=>{o(A)}).catch(A=>{d(ke(A)||"Failed to load nodes")}).finally(()=>{c(!1)})},[]);const x=a.useMemo(()=>new Map(r.map(A=>[A.id,A])),[r]),v=a.useMemo(()=>[...r].sort((A,P)=>A.name.localeCompare(P.name)),[r]),b=n,y=e.nodeId??b?.defaultNodeId??null,S=e.nodeId?"Per-task override":b?.defaultNodeId?"Project default":"No routing",k=y?x.get(y):void 0,R=k?`${Wm[k.status]} ${k.name} (${k.type})`:y?`${y} (node unavailable or unknown)`:"Local (no routing configured)",N=e.column==="in-progress",M=N||g||l,C=a.useCallback(async A=>{if(A===m)return;const P=e.id,F=m;h(A),p(!0);try{const W=await Ks(P,{nodeId:A||null});if(f.current!==P)return;h(W.nodeId??""),i?.(W),s(A?"Node override updated":"Node override cleared","success")}catch(W){if(f.current!==P)return;h(F),s(ke(W)||"Failed to update node override","error")}finally{f.current===P&&p(!1)}},[s,i,m,e.id]),z=a.useCallback(()=>{C("")},[C]);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:[R,PM(k?.status)?t.jsx("span",{className:"routing-summary-warning",children:"Unhealthy"}):null]})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Routing source"}),t.jsx("span",{className:"routing-summary-value",children:S})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Unavailable-node policy"}),t.jsx("span",{className:"routing-summary-value",children:TM(b?.unavailableNodePolicy)})]})]}),N&&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 leaves in-progress."}):null]}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Node Override"}),N?t.jsx("div",{className:"routing-tab__warning-banner",children:"Node override cannot be changed while the task is in progress."}):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:M,onChange:A=>{C(A.target.value)},children:[t.jsx("option",{value:"",children:"Use project default"}),v.map(A=>t.jsxs("option",{value:A.id,children:[Wm[A.status]," ",A.name," (",A.type,")"]},A.id))]}),u?t.jsx("div",{className:"routing-tab__error",children:u}):null,e.nodeId?t.jsxs("div",{className:"routing-tab__override-row",children:[t.jsxs("span",{className:"routing-tab__override-text",children:["Override set to: ",x.get(e.nodeId)?.name??e.nodeId]}),t.jsx("button",{type:"button",className:"btn btn-sm",disabled:N||g,onClick:z,children:"Clear override"})]}):null]})]})}const $M=/^[a-zA-Z0-9_-]{1,64}$/,DM=200;function Km(e){return e?new Date(e).toLocaleString():""}function LM(e,n=DM){return e.length<=n?e:e.substring(0,n)+"…"}function zM({taskId:e,addToast:n,onTaskUpdated:s,projectId:i,canEdit:r=!1}){const[o,l]=a.useState([]),[c,u]=a.useState(!0),[d,m]=a.useState(null),[h,g]=a.useState(""),[p,f]=a.useState(null),[x,v]=a.useState(""),[b,y]=a.useState(null),[S,k]=a.useState([]),[R,N]=a.useState(!1),[M,C]=a.useState(!1),[z,A]=a.useState(""),[P,F]=a.useState(""),[W,$]=a.useState(!1),[_,I]=a.useState(null),[O,J]=a.useState(null),[Q,E]=a.useState(!1),D=a.useCallback(async()=>{try{const U=await Uv(e,i);l(U)}catch(U){n(ke(U)||"Failed to load documents","error")}finally{u(!1)}},[e,i,n]);a.useEffect(()=>{D()},[D]);async function T(U){d===U.key?(m(null),g(""),f(null),v(""),y(null),k([]),E(!1)):(m(U.key),g(U.content),f(null),v(""),y(null),k([]),E(!1))}async function w(U){if(b===U)y(null),k([]);else{y(U),N(!0);try{const Ne=await Bv(e,U,i);k(Ne)}catch(Ne){n(ke(Ne)||"Failed to load revisions","error")}finally{N(!1)}}}function q(){d&&(f(d),v(h))}function G(){f(null),v("")}async function me(){if(!(!p||!x.trim())){$(!0);try{await $d(e,p,x,{},i),f(null),v(""),await D();const U=o.find(Ne=>Ne.key===p);U&&g(U.content),n("Document saved","success")}catch(U){n(ke(U)||"Failed to save document","error")}finally{$(!1)}}}async function ce(){const U=z.trim(),Ne=P.trim();if(!U){n("Document key is required","error");return}if(!$M.test(U)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!Ne){n("Content is required","error");return}$(!0);try{await $d(e,U,Ne,{},i),C(!1),A(""),F(""),await D(),n("Document created","success")}catch(ne){n(ke(ne)||"Failed to create document","error")}finally{$(!1)}}async function ae(U){I(U);try{await Hv(e,U,i),J(null),I(null),d===U&&(m(null),g("")),b===U&&(y(null),k([])),await D(),n("Document deleted","success")}catch(Ne){n(ke(Ne)||"Failed to delete document","error")}finally{I(null)}}function pe(U){g(U.content),f(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"}),M&&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:z,onChange:U=>A(U.target.value),placeholder:"e.g., plan, notes, research",disabled:W}),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:P,onChange:U=>F(U.target.value),rows:6,placeholder:"Enter document content…",disabled:W})]}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{C(!1),A(""),F("")},disabled:W,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void ce(),disabled:W||!z.trim()||!P.trim(),children:W?"Creating…":"Create"})]})]}),o.length===0&&!M?t.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):t.jsx("div",{className:"task-documents-list",children:o.map(U=>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(Oi,{size:14}),t.jsx("span",{className:"task-document-key",children:U.key}),t.jsxs("span",{className:"task-document-revision-badge",children:["v",U.revision]})]}),t.jsxs("div",{className:"task-document-meta",children:[t.jsx("span",{className:"task-document-author",children:U.author}),t.jsx("span",{className:"task-document-timestamp",children:Km(U.updatedAt||U.createdAt)})]})]}),d===U.key&&p!==U.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:()=>E(Ne=>!Ne),"aria-label":Q?"Switch to plain text":"Switch to markdown","aria-pressed":Q,title:Q?"Switch to plain text":"Switch to markdown",children:Q?"Markdown":"Plain"})}),t.jsx("div",{className:"task-document-content",children:Q?t.jsx("div",{className:"task-document-content-markdown",children:t.jsx("div",{className:"markdown-body",children:t.jsx(ci,{remarkPlugins:[di],children:h})})}):t.jsx("pre",{className:"task-document-content-text",children:h})}),b===U.key&&t.jsxs("div",{className:"task-document-revisions",children:[t.jsx("h5",{children:"Revision History"}),R?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(Ne=>Ne.revision<U.revision).sort((Ne,ne)=>ne.revision-Ne.revision).map(Ne=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>pe(Ne),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",Ne.revision]}),t.jsx("span",{className:"revision-author",children:Ne.author}),t.jsx("span",{className:"revision-timestamp",children:Km(Ne.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:LM(Ne.content,100)})]},Ne.id))})]})]}),p===U.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:x,onChange:Ne=>v(Ne.target.value),rows:10,disabled:W}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:G,disabled:W,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void me(),disabled:W||!x.trim(),children:W?"Saving…":"Save"})]})]}),t.jsxs("div",{className:"task-document-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>void T(U),children:d===U.key?t.jsxs(t.Fragment,{children:[t.jsx(li,{size:14})," Collapse"]}):t.jsxs(t.Fragment,{children:[t.jsx(qt,{size:14})," Expand"]})}),d===U.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void w(U.key),children:[t.jsx(cr,{size:14})," History"]}),r&&p!==U.key&&t.jsx("button",{className:"btn btn-sm",onClick:q,children:"Edit"}),r&&(O===U.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 ae(U.key),disabled:_===U.key,children:_===U.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>J(null),disabled:_===U.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>J(U.key),children:t.jsx(Xt,{size:14})}))]})]})]},U.key))}),r&&!M&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>C(!0),children:[t.jsx(Zt,{size:14})," New Document"]})]})}function to(e){return e.toLocaleString()}function Wl(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function Ba(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),i=Math.round(n%60);return`${s}m ${i}s`}function FM(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 u=new Date(o.completedAt).getTime();if(Number.isNaN(u)||u<l)return null;c=u}else c=Math.max(l,n);return{name:o.workflowStepName||o.workflowStepId,durationMs:c-l}}).filter(o=>o!==null),i=s.reduce((o,l)=>o+l.durationMs,0),r=s.reduce((o,l)=>!o||l.durationMs>o.durationMs?l:o,void 0);return{timedStepCount:s.length,totalDurationMs:i,longestStep:r}}function OM({tokenUsage:e,loading:n,task:s}){const i=wp(s?.log??[]),r=i.filter(m=>typeof m.durationMs=="number"),o=r.reduce((m,h)=>m+(h.durationMs??0),0),l=Math.max(o,s?.timedExecutionMs??0),c=r.reduce((m,h)=>!m||(h.durationMs??0)>(m.durationMs??0)?h:m,void 0),u=FM(s?.workflowStepResults??[]),d=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:i.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:Ba(l)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Workflow timed steps"}),t.jsx("span",{className:"task-token-stats-panel__value",children:u.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:Ba(u.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:Ba(l+u.totalDurationMs)})]})]}),t.jsxs("dl",{className:"task-token-stats-panel__timestamps",children:[t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Longest timing event"}),t.jsx("dd",{children:c?.durationMs?`${c.summary} (${Ba(c.durationMs)})`:"No timed events recorded yet."})]}),t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Longest workflow step"}),t.jsx("dd",{children:u.longestStep?`${u.longestStep.name} (${Ba(u.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:d>0?`${Math.min((s?.currentStep??0)+1,d)} / ${d}`:"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 ${Wl(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:to(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:to(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:to(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:to(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:Wl(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:Wl(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}const UM=new Set(["planning","researching","executing","finalizing","merging"]);function BM(e,n){return fp(e,n)}function HM(e,n){return gp(e,n)}function qM(e){let n=null;for(const s of e){if(s.agent!=="triage"||s.type!=="text")continue;const i=s.text.match(/^Triage using model: (.+?)\/(.+)$/);i&&(n={provider:i[1],modelId:i[2]})}return n}function VM(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const i=qM(n);return i||xp(e,s)}function WM(e){switch(e){case"done":return"var(--color-success, #3fb950)";case"in-progress":return"var(--todo, #58a6ff)";case"skipped":return"var(--text-dim, #484f58)";case"pending":default:return"var(--border, #30363d)"}}function KM(e){const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),o=Math.floor(r/60),l=Math.floor(o/24);return r<1?"just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString()}function GM(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function JM(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(i=>typeof i=="string")};const s=e.message.match(/[A-Z]+-\d+/g)??[];return s.length>1?{dependentIds:[...new Set(s.slice(1))]}:null}function Gm(e,n){return e.length>n?e.slice(0,n)+"…":e}function Jm(e=[],n=[]){return e.length===n.length&&e.every((s,i)=>s===n[i])}function Kl(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function Gl(e){return e.trim()}function YM(e){const n=e.trim();return n.length>0?n:void 0}function Ha(e){return typeof e=="string"&&ed.includes(e)?e:ps}function qa(e){return e==="fast"?"fast":"standard"}const Jl=200,QM=new Set(["triage","todo"]);function XM({task:e,projectId:n,tasks:s=[],onClose:i,onOpenDetail:r,onMoveTask:o,onDeleteTask:l,onMergeTask:c,onRetryTask:u,onDuplicateTask:d,onTaskUpdated:m,addToast:h,prAuthAvailable:g,initialTab:p="definition"}){const[f,x]=a.useState(p),[v,b]=a.useState(()=>"prompt"in e?e:null),[y,S]=a.useState(()=>!("prompt"in e));a.useEffect(()=>{if("prompt"in e){b(e),S(!1);return}let X=!1;return S(!0),b(null),fo(e.id,n).then(He=>{X||(b(He),S(!1))}).catch(()=>{X||S(!1)}),()=>{X=!0}},[e.id,n]);const k=v?{...v,...e,prompt:v.prompt,log:v.log}:{...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;a.useEffect(()=>{x(p)},[p]),a.useEffect(()=>{z(!1)},[e.id]);const[N,M]=a.useState("activity"),[C,z]=a.useState(!1),[A,P]=a.useState(e.attachments||[]),[F,W]=a.useState(!1),[$,_]=a.useState(e.dependencies||[]),[I,O]=a.useState(!1),[J,Q]=a.useState(""),[E,D]=a.useState(null),[T,w]=a.useState([]),[q,G]=a.useState(!1),[me,ce]=a.useState(!1),[ae,pe]=a.useState(!1),[U,Ne]=a.useState(!1),[ne,xe]=a.useState(!1),[le,ve]=a.useState(k.prompt||""),[ee,Ee]=a.useState(""),[Fe,Ke]=a.useState(!1),[Ze,Xe]=a.useState(""),[Qe,it]=a.useState(!1),[Ie,Ge]=a.useState(!1),[se,ye]=a.useState(e.title||""),[Z,Te]=a.useState(e.description||""),[ze,be]=a.useState(e.dependencies||[]),[Me,Be]=a.useState(""),[lt,je]=a.useState(""),[ie,Ae]=a.useState(""),[he,Re]=a.useState(""),[Je,$e]=a.useState("default"),[de,re]=a.useState(void 0),[ue,Pe]=a.useState(ps),[Se,fe]=a.useState(e.nodeId),[tt,ut]=a.useState(qa(e.executionMode)),[vt,gt]=a.useState(""),[dt,wt]=a.useState(e.enabledWorkflowSteps||[]),[Mt,yt]=a.useState(e.sourceIssue?.provider??""),[Et,Nt]=a.useState(e.sourceIssue?.repository??""),[Tt,Ht]=a.useState(e.sourceIssue?.externalIssueId??""),[Ut,Vt]=a.useState(e.sourceIssue?.url??""),[zt,Ct]=a.useState([]),[At,kt]=a.useState(!1),Kt=a.useRef(!1),[$t,B]=a.useState(!1),[ge,te]=a.useState(!1),j=a.useRef(null),V=a.useRef(null),De=a.useRef(null),nt=a.useRef(null);Xs(nt,!0,"fusion:task-detail-modal-size");const{getSlotsForId:St}=hp(n),Pt=St("task-detail-tab");a.useEffect(()=>(Kt.current=!0,()=>{Kt.current=!1}),[]);const[Rt,un]=a.useState(void 0),[mn,wn]=a.useState([]),[Gt,es]=a.useState(!1),[we,rt]=a.useState(e.enabledWorkflowSteps||[]),Jt=e.column==="in-progress"||UM.has(e.status);a.useEffect(()=>{ye(e.title||""),Te(e.description||""),yt(e.sourceIssue?.provider??""),Nt(e.sourceIssue?.repository??""),Ht(e.sourceIssue?.externalIssueId??""),Vt(e.sourceIssue?.url??""),ut(qa(e.executionMode)),Ge(!1)},[e.id,e.title,e.description,e.sourceIssue,e.executionMode]),a.useEffect(()=>{rt(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),a.useEffect(()=>{let X=!1;return Lo(n).then(He=>{X||un(He)}).catch(()=>{}),()=>{X=!0}},[n]),a.useEffect(()=>{if(f!=="workflow")return;let X=!1;return es(!0),mk(e.id,n).then(He=>{X||wn(He)}).catch(He=>{X||h(`Failed to load workflow results: ${ke(He)}`,"error")}).finally(()=>{X||es(!1)}),()=>{X=!0}},[f,e.id,n,h]),a.useEffect(()=>{if(f!=="workflow")return;const X=n?`?projectId=${encodeURIComponent(n)}`:"",He=ct=>{try{const It=JSON.parse(ct.data);It.id===e.id&&Array.isArray(It.workflowStepResults)&&wn(It.workflowStepResults)}catch{}};return Ls(`/api/events${X}`,{events:{"task:updated":He}})},[f,e.id,n]),a.useEffect(()=>{I||Q("")},[I]),a.useEffect(()=>{if(!e.assignedAgentId){D(null);return}const X=T.find(ct=>ct.id===e.assignedAgentId);if(X){D(X);return}let He=!1;return rp(e.assignedAgentId,n).then(ct=>{He||D(ct)}).catch(()=>{He||D(null)}),()=>{He=!0}},[e.assignedAgentId,n,T]),a.useEffect(()=>{G(!1)},[e.id]),a.useEffect(()=>{if(!($t||ge))return;const He=ct=>{const It=ct.target,Us=j.current?.contains(It),vs=De.current?.contains(It);!Us&&$t&&B(!1),!vs&&ge&&te(!1)};return document.addEventListener("mousedown",He),()=>document.removeEventListener("mousedown",He)},[$t,ge]),a.useEffect(()=>{if(!($t||ge))return;const He=ct=>{ct.key==="Escape"&&(ct.stopPropagation(),$t&&B(!1),ge&&te(!1))};return document.addEventListener("keydown",He),()=>document.removeEventListener("keydown",He)},[$t,ge]),a.useEffect(()=>{xe(!1),ve(k.prompt||""),Ee("")},[e.id,k.prompt]);const Sn=QM.has(e.column)&&!At,Cn=a.useCallback(()=>{if(!Sn)return;Ge(!0),ye(e.title||""),Te(e.description||""),be(e.dependencies||[]);const X=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",He=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",ct=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";Be(X),je(He),Ae(ct),Re(e.thinkingLevel??""),fe(e.nodeId),$e(X||He||ct?"custom":"default"),gt(""),wt(e.enabledWorkflowSteps||[]),ut(qa(e.executionMode)),yt(e.sourceIssue?.provider??""),Nt(e.sourceIssue?.repository??""),Ht(e.sourceIssue?.externalIssueId??""),Vt(e.sourceIssue?.url??""),Ct([]),re(e.reviewLevel),Pe(Ha(e.priority))},[Sn,e]),pn=a.useCallback(()=>{Ge(!1),ye(e.title||""),Te(e.description||""),be(e.dependencies||[]),fe(e.nodeId),yt(e.sourceIssue?.provider??""),Nt(e.sourceIssue?.repository??""),Ht(e.sourceIssue?.externalIssueId??""),Vt(e.sourceIssue?.url??""),Pe(Ha(e.priority)),ut(qa(e.executionMode)),zt.forEach(X=>URL.revokeObjectURL(X.previewUrl)),Ct([])},[e.title,e.description,e.dependencies,e.nodeId,e.priority,e.executionMode,zt]),bn=a.useCallback(async()=>{kt(!0);try{const X={},He=se.trim(),ct=Z.trim();He&&He!==(e.title??"")&&(X.title=He),ct&&ct!==(e.description??"")&&(X.description=ct),Jm(ze,e.dependencies??[])||(X.dependencies=ze),Jm(dt,e.enabledWorkflowSteps??[])||(X.enabledWorkflowSteps=dt);const It=Kl(Me),Us=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";Me!==Us&&(X.modelProvider=It?.provider??null,X.modelId=It?.modelId??null);const vs=Kl(lt),Xo=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";lt!==Xo&&(X.validatorModelProvider=vs?.provider??null,X.validatorModelId=vs?.modelId??null);const Gi=Kl(ie),hi=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";ie!==hi&&(X.planningModelProvider=Gi?.provider??null,X.planningModelId=Gi?.modelId??null);const Dr=e.thinkingLevel??"";he!==Dr&&(X.thinkingLevel=he!==""?he:null),(e.nodeId??void 0)!==Se&&(X.nodeId=Se??null);const Lr=e.reviewLevel;de!==Lr&&(X.reviewLevel=de);const Ji=Ha(e.priority);ue!==Ji&&(X.priority=ue);const Zo=qa(e.executionMode);tt!==Zo&&(X.executionMode=tt==="fast"?"fast":null);const Ra=Gl(Mt),Ta=Gl(Et),pi=Gl(Tt),Yi=YM(Ut);if(Ra.length===0&&Ta.length===0&&pi.length===0&&!Yi)e.sourceIssue&&(X.sourceIssue=null);else{if(!Ra||!Ta||!pi){h("Source issue provider, repository, and issue identifier are required","error"),kt(!1);return}const As=Number.parseInt(pi,10),si=e.sourceIssue?.issueNumber??As;if(!Number.isFinite(si)||si<=0){h("Source issue identifier must be numeric for new metadata","error"),kt(!1);return}const Rs={provider:Ra,repository:Ta,externalIssueId:pi,issueNumber:si,...Yi?{url:Yi}:{}},Ts=e.sourceIssue;(!Ts||Ts.provider!==Rs.provider||Ts.repository!==Rs.repository||Ts.externalIssueId!==Rs.externalIssueId||Ts.issueNumber!==Rs.issueNumber||(Ts.url??void 0)!==Rs.url)&&(X.sourceIssue=Rs)}if(Object.keys(X).length>0){const As=await Ks(e.id,X,n);m?.(As)}if(zt.length>0){const As=[];for(const si of zt)try{const Rs=await ur(e.id,si.file,n);P(Ts=>[...Ts,Rs])}catch{As.push(si.file.name)}As.length>0&&h(`Failed to upload: ${As.join(", ")}`,"error")}zt.forEach(As=>URL.revokeObjectURL(As.previewUrl)),Ct([]),h(`Updated ${e.id}`,"success"),Ge(!1)}catch(X){h(`Failed to update ${e.id}: ${ke(X)}`,"error")}finally{Kt.current&&kt(!1)}},[e,se,Z,ze,Me,lt,ie,he,Se,de,ue,tt,dt,Mt,Et,Tt,Ut,zt,h,n,m]),Rn=a.useCallback(async X=>{try{await Ks(e.id,{description:X},n),h("Description saved","success")}catch(He){h(`Failed to save: ${ke(He)}`,"error")}},[e.id,h,n]),vn=a.useCallback(X=>{Ie&&(X.key==="Escape"?(X.preventDefault(),pn()):X.key==="Enter"&&(X.ctrlKey||X.metaKey)&&(X.preventDefault(),bn()))},[Ie,pn,bn]);a.useEffect(()=>{if(Ie)return document.addEventListener("keydown",vn),()=>document.removeEventListener("keydown",vn)},[Ie,vn]);const Y=a.useRef(null),{nodes:Oe}=Bo(),{confirm:Ye}=Ds(),{entries:st,loading:pt,loadMore:jt,hasMore:_t,total:yn,loadingMore:en}=Uf(e.id,f==="logs"&&N==="agent-log",n);a.useEffect(()=>{const X=He=>{He.key==="Escape"&&!Ie&&i()};return document.addEventListener("keydown",X),()=>document.removeEventListener("keydown",X)},[i,Ie]);const xt=wi(i),ts=a.useCallback(async X=>{try{await o(e.id,X),i(),h(`Moved to ${_n[X]}`,"success")}catch(He){h(ke(He),"error")}},[e.id,o,i,h]),ns=a.useCallback(async()=>{if(await Ye({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0}))try{await l(e.id),i(),h(`Deleted ${e.id}`,"info")}catch(He){const ct=JM(He);if(!ct||ct.dependentIds.length===0){h(ke(He),"error");return}const It=ct.dependentIds.join(", ");if(!await Ye({title:"Force Delete Task",message:`${e.id} is a dependency of ${It}.
|
|
651
|
+
|
|
652
|
+
Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await l(e.id,{removeDependencyReferences:!0}),i(),h(`Deleted ${e.id} after removing dependency references`,"info")}catch(vs){h(ke(vs),"error")}}},[e.id,l,i,h,Ye]),ss=a.useCallback(async()=>{await Ye({title:"Merge Task",message:`Merge ${e.id} into the current branch?`})&&(i(),h(`Merging ${e.id}...`,"info"),c(e.id).then(He=>{const ct=He.merged?`Merged ${e.id} (branch: ${He.branch})`:`Closed ${e.id} (${He.error||"no branch to merge"})`;h(ct,"success")}).catch(He=>{h(ke(He),"error")}))},[e.id,c,i,h,Ye]),Si=a.useCallback(()=>{u&&(i(),u(e.id).then(()=>{h(`Retried ${e.id}`,"success")}).catch(X=>{h(ke(X),"error")}))},[e.id,u,i,h]),oe=a.useCallback(async()=>{if(!(!d||!await Ye({title:"Duplicate Task",message:`Duplicate ${e.id}? This will create a new task in Triage with the same description and prompt.`})))try{const He=await d(e.id);i(),h(`Duplicated ${e.id} → ${He.id}`,"success")}catch(He){h(ke(He),"error")}},[e.id,d,i,h,Ye]),_e=a.useCallback(async()=>{try{e.paused?(await Av(e.id,n),h(`Unpaused ${e.id}`,"success")):(await Zh(e.id,n),h(`Paused ${e.id}`,"success")),i()}catch(X){h(ke(X),"error")}},[e.id,e.paused,i,h]),at=a.useCallback(async()=>{try{await Iv(e.id,n),h(`Plan approved — ${e.id} moved to Todo`,"success"),i()}catch(X){h(ke(X),"error")}},[e.id,i,h]),We=a.useCallback(async()=>{if(await Ye({title:"Reject Plan",message:"Reject this plan? The specification will be discarded and regenerated.",danger:!0}))try{await $v(e.id,n),h(`Plan rejected — ${e.id} returned to Planning for replanning`,"info"),i()}catch(He){h(ke(He),"error")}},[e.id,i,h,Ye]),mt=a.useCallback(async()=>{if(await Ye({title:"Rebuild Plan",message:"Rebuild the plan for this task? The task will move to planning for replanning."}))try{await Wv(e.id,n),i(),h(`Replanning ${e.id}...`,"info")}catch(He){h(ke(He),"error")}},[e.id,n,i,h,Ye]),fn=a.useCallback(()=>{Ke(!0),Xe("")},[]),Yt=a.useCallback(()=>{B(!1),te(!1)},[]),tn=a.useCallback(X=>{Yt(),ts(X)},[Yt]),rn=a.useCallback(X=>{Yt(),X()},[Yt]),On=a.useCallback(()=>{Yt(),ss()},[Yt,ss]),Un=a.useCallback(()=>{Ke(!1),Xe(""),it(!1)},[]),xs=a.useCallback(async()=>{if(!Ze.trim()){h("Please enter feedback describing what needs refinement","error");return}if(Ze.length>2e3){h("Feedback must be 2000 characters or less","error");return}it(!0);try{const X=await Kv(e.id,Ze.trim(),n);h(`Refinement task created: ${X.id}`,"success"),i()}catch(X){h(ke(X),"error")}finally{it(!1)}},[e.id,Ze,h,i]),kn=a.useCallback(async X=>{W(!0);try{const He=await ur(e.id,X,n);P(ct=>[...ct,He]),h("Screenshot attached","success")}catch(He){h(ke(He),"error")}finally{W(!1)}},[e.id,h]),Ln=a.useCallback(async X=>{const He=X.target.files?.[0];He&&(await kn(He),Y.current&&(Y.current.value=""))},[kn]);a.useEffect(()=>{const X=He=>{const ct=He.clipboardData?.items;if(ct)for(let It=0;It<ct.length;It++){const Us=ct[It];if(Us.type.startsWith("image/")){const vs=Us.getAsFile();if(vs){He.preventDefault(),kn(vs);return}}}};return document.addEventListener("paste",X),()=>document.removeEventListener("paste",X)},[kn]);const Wn=a.useCallback(X=>{X.preventDefault()},[]),_s=a.useCallback(X=>{X.preventDefault();const He=X.dataTransfer.files;for(let ct=0;ct<He.length;ct++){const It=He[ct];if(It.type.startsWith("image/")){kn(It);return}}},[kn]),zn=a.useCallback(async X=>{try{await zv(e.id,X,n),P(He=>He.filter(ct=>ct.filename!==X)),h("Attachment deleted","info")}catch(He){h(ke(He),"error")}},[e.id,h]),is=a.useCallback(async X=>{const He=we;rt(X);try{const ct=await Ks(e.id,{enabledWorkflowSteps:X},n);h("Workflow steps updated","success"),m?.(ct)}catch(ct){rt(He),h(`Failed to update workflow steps: ${ke(ct)}`,"error")}},[e.id,n,we,m,h]),Ms=a.useCallback(async()=>{ce(!0);try{const X=await Na(void 0,n);w(X),G(!0)}catch(X){h(`Failed to load agents: ${ke(X)}`,"error"),G(!1)}finally{ce(!1)}},[n,h]),bs=a.useCallback(async X=>{try{const He=await Wd(e.id,X,n),ct=T.find(It=>It.id===X)??null;D(ct||(It=>It?.id===X?It:null)),G(!1),m?.(He),h("Assigned agent updated","success")}catch(He){h(`Failed to assign agent: ${ke(He)}`,"error")}},[e.id,n,T,m,h]),Kn=a.useCallback(async()=>{try{const X=await Wd(e.id,null,n);D(null),G(!1),m?.(X),h("Agent unassigned","success")}catch(X){h(`Failed to unassign agent: ${ke(X)}`,"error")}},[e.id,n,m,h]),Gn=a.useCallback(async X=>{const He=[...$,X];_(He);try{await Ks(e.id,{dependencies:He},n)}catch(ct){_($),h(ke(ct),"error")}},[e.id,$,h]),ei=a.useCallback(async(X,He)=>{X.stopPropagation();const ct=$.filter(It=>It!==He);_(ct);try{await Ks(e.id,{dependencies:ct},n)}catch(It){_($),h(ke(It),"error")}},[e.id,$,h]),zs=a.useCallback(async X=>{try{const He=await fo(X,n);r(He)}catch{h(`Failed to load dependency ${X}`,"error")}},[r,h]),Ci=a.useCallback(async X=>{pe(!0);try{await Ks(k.id,{prompt:X},n),h("Spec updated","success"),v&&(v.prompt=X)}catch(He){throw h(ke(He),"error"),He}finally{pe(!1)}},[k,v,h]),Ar=a.useCallback(async X=>{Ne(!0);try{await Vv(e.id,X,n),h("AI revision requested. Task moved to planning.","success"),i()}catch(He){const ct=ke(He);ct.includes("in-review")||ct.includes("done")?h("Cannot request revision: Task must be in 'todo' or 'in-progress' column.","error"):h(ct,"error")}finally{Ne(!1)}},[e.id,h,i]),Yo=a.useCallback(()=>{xe(!0),ve(k.prompt||""),Ee("")},[k.prompt]),Ei=a.useCallback(()=>{xe(!1),ve(k.prompt||""),Ee("")},[k.prompt]),_a=a.useCallback(async()=>{if(le===(k.prompt||"")){Ei();return}xe(!1);try{await Ci(le)}catch(X){throw xe(!0),X}},[le,k.prompt,Ci,Ei]),_i=a.useCallback(async()=>{ee.trim()&&await Ar(ee.trim())},[ee,Ar]),mi=a.useCallback(X=>{X.key==="Escape"?(X.preventDefault(),Ei()):X.key==="Enter"&&(X.ctrlKey||X.metaKey)&&(X.preventDefault(),_a())},[Ei,_a]),Rr=s.filter(X=>X.id!==e.id&&!$.includes(X.id)).sort((X,He)=>{const ct=He.createdAt.localeCompare(X.createdAt);if(ct!==0)return ct;const It=parseInt(X.id.slice(X.id.lastIndexOf("-")+1),10)||0;return(parseInt(He.id.slice(He.id.lastIndexOf("-")+1),10)||0)-It}),Tr=E?.name??e.assignedAgentId??null,Mi=a.useMemo(()=>{const X=[];return k.modelProvider&&X.push(k.modelProvider),k.validatorModelProvider&&!X.includes(k.validatorModelProvider)&&X.push(k.validatorModelProvider),k.planningModelProvider&&!X.includes(k.planningModelProvider)&&X.push(k.planningModelProvider),X},[k.modelProvider,k.validatorModelProvider,k.planningModelProvider]),Qo=Nc[e.column]||[],Fs=["todo","in-progress"],Ma=e.column==="in-review"?Fs:Qo,Tn=Ma[0],Aa=Ma.slice(1),as=Aa.length>0,Pr=a.useCallback(()=>{B(!1),V.current?.focus()},[]),Os=a.useCallback(X=>{if(!as){Tn&&tn(Tn);return}const He=X.currentTarget.querySelector(".detail-move-btn__arrow");if(!!(X.target instanceof Element&&X.target.closest(".detail-move-btn__arrow")||He&&X.clientX>0&&X.clientX>=He.getBoundingClientRect().left)){B(It=>!It),te(!1);return}Tn&&tn(Tn)},[as,Tn,tn]),ti=a.useCallback(X=>{!as||!(X.key==="ArrowDown"||X.altKey&&X.key==="ArrowDown")||(X.preventDefault(),B(!0),te(!1))},[as]),ni=a.useCallback(X=>{X.key==="Escape"&&(X.preventDefault(),X.stopPropagation(),Pr())},[Pr]);a.useEffect(()=>{if(!$t)return;j.current?.querySelector(".detail-move-menu-item")?.focus()},[$t]);const Ir={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…"},$r=e.status?Ir[e.status]:void 0;return t.jsx("div",{className:"modal-overlay open",...xt,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg task-detail-modal",ref:nt,onDragOver:Wn,onDrop:_s,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:_n[e.column]})]}),t.jsxs("div",{className:"modal-header-actions",children:[!Ie&&Sn&&t.jsx("button",{className:"modal-edit-btn",onClick:Cn,title:"Edit task","aria-label":"Edit task",children:t.jsx(Yn,{size:14})}),t.jsx("button",{className:"modal-close",onClick:i,"aria-label":"Close",children:"×"})]})]}),t.jsxs("div",{className:`detail-body${f==="logs"&&N==="agent-log"&&!Ie?" detail-body--agent-log":""}`,children:[Ie?t.jsx("div",{className:"modal-edit-form",children:t.jsx(qf,{mode:"edit",title:se,onTitleChange:ye,description:Z,onDescriptionChange:Te,dependencies:ze,onDependenciesChange:be,executorModel:Me,onExecutorModelChange:Be,validatorModel:lt,onValidatorModelChange:je,planningModel:ie,onPlanningModelChange:Ae,thinkingLevel:he,onThinkingLevelChange:Re,presetMode:Je,onPresetModeChange:$e,selectedPresetId:vt,onSelectedPresetIdChange:gt,selectedWorkflowSteps:dt,onWorkflowStepsChange:wt,pendingImages:zt,onImagesChange:Ct,tasks:s.filter(X=>X.id!==e.id),projectId:n,disabled:At,addToast:h,isActive:Ie,onAutoSaveDescription:Rn,reviewLevel:de,onReviewLevelChange:re,priority:ue,onPriorityChange:Pe,nodeId:Se,onNodeIdChange:fe,nodeOptions:Oe,nodeOverrideDisabled:Jt,nodeOverrideDisabledReason:Jt?"Execution node override is locked while a task is active/in progress.":void 0,executionMode:tt,onExecutionModeChange:ut,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:Mt,onChange:X=>yt(X.target.value),disabled:At,"data-testid":"task-source-provider-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Repository (e.g. owner/repo)",value:Et,onChange:X=>Nt(X.target.value),disabled:At,"data-testid":"task-source-repository-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:Tt,onChange:X=>Ht(X.target.value),disabled:At,"data-testid":"task-source-external-id-input"}),t.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:Ut,onChange:X=>Vt(X.target.value),disabled:At,"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 X=e.title||e.description||e.id,He=!C&&X.length>Jl;return t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"detail-title",children:He?X.slice(0,Jl)+"…":X}),X.length>Jl&&t.jsx("button",{className:"detail-description-toggle",onClick:()=>z(!C),children:C?"Show less":"Show more"})]})})(),t.jsxs("div",{className:"detail-meta",children:["Created ",new Date(e.createdAt).toLocaleDateString()," · Updated"," ",new Date(e.updatedAt).toLocaleDateString()," ·",t.jsxs("span",{className:`detail-priority-chip detail-priority-chip--${Ha(e.priority)}`,children:["Priority: ",Ha(e.priority)]})]})]}),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})]})]}),!Ie&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"detail-tabs",children:[t.jsx("button",{className:`detail-tab${f==="definition"?" detail-tab-active":""}`,onClick:()=>x("definition"),children:"Definition"}),t.jsx("button",{className:`detail-tab${f==="logs"?" detail-tab-active":""}`,onClick:()=>x("logs"),children:"Logs"}),(e.column==="in-progress"||e.column==="in-review"||e.column==="done")&&t.jsx("button",{className:`detail-tab${f==="changes"?" detail-tab-active":""}`,onClick:()=>x("changes"),children:"Changes"}),t.jsx("button",{className:`detail-tab${f==="comments"?" detail-tab-active":""}`,onClick:()=>x("comments"),children:"Comments"}),t.jsx("button",{className:`detail-tab${f==="documents"?" detail-tab-active":""}`,onClick:()=>x("documents"),children:"Documents"}),t.jsx("button",{className:`detail-tab${f==="model"?" detail-tab-active":""}`,onClick:()=>x("model"),children:"Model"}),t.jsx("button",{className:`detail-tab${f==="workflow"?" detail-tab-active":""}`,onClick:()=>x("workflow"),children:"Workflow"}),t.jsx("button",{className:`detail-tab${f==="stats"?" detail-tab-active":""}`,onClick:()=>x("stats"),children:"Stats"}),t.jsx("button",{className:`detail-tab${f==="routing"?" detail-tab-active":""}`,onClick:()=>x("routing"),children:"Routing"}),Pt.map((X,He)=>{const ct=`plugin-${He}`;return t.jsx("button",{className:`detail-tab${f===ct?" detail-tab-active":""}`,onClick:()=>x(ct),children:X.slot.label},`plugin-tab-${X.pluginId}`)})]}),f==="workflow"?t.jsx("div",{className:"detail-section",children:t.jsx(RM,{taskId:e.id,results:mn,loading:Gt,enabledWorkflowSteps:we,canEdit:Sn,projectId:n,isTaskInProgress:e.column==="in-progress"&&e.status!=="paused",onWorkflowStepsChange:is})}):f==="model"?t.jsx("div",{className:"detail-section",children:t.jsx(mM,{task:e,addToast:h,onTaskUpdated:m,settings:Rt})}):f==="logs"?t.jsxs("div",{className:`detail-section${N==="agent-log"?" detail-section--agent-log":""}`,children:[t.jsxs("div",{className:"log-subview-toggle",children:[t.jsx("button",{className:`log-subview-btn${N==="activity"?" log-subview-btn-active":""}`,onClick:()=>M("activity"),children:"Activity"}),t.jsx("button",{className:`log-subview-btn${N==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>M("agent-log"),children:"Agent Log"})]}),N==="agent-log"?t.jsx(oM,{entries:st,loading:pt,executorModel:BM(e,Rt),validatorModel:HM(e,Rt),planningModel:VM(e,st,Rt),hasMore:_t,onLoadMore:jt,loadingMore:en,totalCount:yn}):t.jsxs("div",{className:"detail-activity",children:[t.jsx("h4",{children:"Activity"}),k.activityLogTruncatedCount?t.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",k.log.length," activity entries."]}):null,k.log&&k.log.length>0?t.jsx("div",{className:"detail-activity-list",children:[...k.log].reverse().map((X,He)=>t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-timestamp",children:KM(X.timestamp)}),t.jsx("span",{className:"detail-log-action",children:X.action})]}),X.outcome&&t.jsx("div",{className:"detail-log-outcome",children:X.outcome})]},He))}):t.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):f==="changes"?t.jsx(jM,{taskId:e.id,worktree:e.worktree,projectId:n,column:e.column,mergeDetails:e.mergeDetails,modifiedFiles:e.modifiedFiles}):f==="comments"?t.jsx(xM,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):f==="documents"?t.jsx(zM,{taskId:e.id,addToast:h,projectId:n,onTaskUpdated:m,canEdit:Sn}):typeof f=="string"&&f.startsWith("plugin-")?t.jsx("div",{className:"detail-section",children:t.jsx(Oo,{slotId:"task-detail-tab",projectId:n})}):f==="stats"?t.jsx("div",{className:"detail-section",children:t.jsx(OM,{tokenUsage:k.tokenUsage,loading:y,task:k})}):f==="routing"?t.jsx("div",{className:"detail-section",children:t.jsx(IM,{task:e,settings:Rt,addToast:h,onTaskUpdated:m})}):t.jsxs(t.Fragment,{children:[e.column==="done"&&e.summary&&t.jsxs("div",{className:"detail-section detail-summary",children:[t.jsx("h4",{children:"Summary"}),t.jsx("div",{className:"markdown-body",children:t.jsx(ci,{remarkPlugins:[di],children:e.summary})})]}),t.jsx(vM,{task:e}),e.sourceIssue&&t.jsxs("div",{className:"detail-section detail-source-section",children:[t.jsx("h4",{children:"Source Issue"}),t.jsxs("dl",{className:"detail-source-grid",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Provider"}),t.jsx("dd",{children:e.sourceIssue.provider})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Repository"}),t.jsx("dd",{children:e.sourceIssue.repository})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Issue Identifier"}),t.jsx("dd",{children:e.sourceIssue.externalIssueId})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"URL"}),t.jsx("dd",{children:e.sourceIssue.url?t.jsx("a",{className:"detail-source-link",href:e.sourceIssue.url,target:"_blank",rel:"noopener noreferrer",children:e.sourceIssue.url}):t.jsx("span",{className:"detail-source-empty",children:"(none)"})})]})]})]}),t.jsx("div",{className:"detail-section detail-agent-section",children:t.jsxs("div",{className:"detail-meta-row",children:[t.jsxs("div",{className:"detail-meta-left",children:[Mi.length>0&&t.jsx("span",{className:"detail-provider-icons","data-testid":"detail-provider-icons",children:Mi.map(X=>t.jsx(An,{provider:X,size:"sm"},X))}),t.jsxs("span",{className:"detail-meta-label",children:[t.jsx(gn,{size:14,style:{verticalAlign:"middle",marginRight:6}}),"Agent"]})]}),t.jsxs("div",{className:"detail-agent-actions",children:[Tr?t.jsxs("span",{className:"detail-agent-chip",children:[t.jsx(gn,{size:14}),Tr,t.jsx("button",{className:"detail-agent-clear",onClick:()=>void Kn(),title:"Unassign agent",children:t.jsx(Ot,{size:12})})]}):t.jsx("button",{className:"btn btn-sm",onClick:()=>{q?G(!1):Ms()},children:"Assign Agent"}),q&&t.jsxs("div",{className:"agent-picker-dropdown",children:[me&&t.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!me&&T.filter(X=>X.state!=="terminated").map(X=>t.jsxs("button",{className:`agent-picker-item${e.assignedAgentId===X.id?" selected":""}`,onClick:()=>void bs(X.id),children:[t.jsx(gn,{size:14}),t.jsx("span",{className:"agent-picker-name",children:X.name}),t.jsx("span",{className:"agent-picker-role",children:X.role})]},X.id)),!me&&T.filter(X=>X.state!=="terminated").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"}),k.steps&&k.steps.length>0?t.jsxs("div",{className:"step-progress-wrapper",children:[t.jsx("div",{className:"step-progress-bar",children:k.steps.map((X,He)=>t.jsx("div",{className:`step-progress-segment step-progress-segment--${X.status}`,"data-tooltip":`${X.name} (${X.status})`,style:{backgroundColor:WM(X.status)}},He))}),t.jsxs("span",{className:"step-progress-label",children:[k.steps.filter(X=>X.status==="done").length,"/",k.steps.length," step",k.steps.length===1?"":"s"]})]}):t.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),t.jsxs("div",{className:"detail-section",children:[!ne&&t.jsx("div",{className:"detail-spec-edit-trigger",children:t.jsx("button",{className:"btn btn-sm",onClick:Yo,children:"Edit"})}),ne?t.jsxs("div",{className:"spec-editor-edit-mode",children:[t.jsx("textarea",{className:"spec-editor-textarea",value:le,onChange:X=>ve(X.target.value),onKeyDown:mi,disabled:ae,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:Ei,disabled:ae,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void _a(),disabled:le===(k.prompt||"")||ae,children:ae?"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:ee,onChange:X=>Ee(X.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:U,rows:4,maxLength:2e3}),t.jsxs("div",{className:"spec-editor-revision-actions",children:[t.jsxs("span",{className:"spec-editor-char-count",children:[ee.length,"/2000"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void _i(),disabled:!ee.trim()||U,children:U?"Requesting…":"Request AI Revision"})]})]})]}):y?t.jsx("div",{className:"spec-loading",children:"Loading specification…"}):k.prompt?t.jsx("div",{className:"markdown-body",children:t.jsx(ci,{remarkPlugins:[di],children:k.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"}),A.length>0?t.jsx("div",{className:"detail-attachments-grid",children:A.map(X=>{const He=Qs(`/api/tasks/${e.id}/attachments/${X.filename}`);return t.jsxs("div",{className:"detail-attachment-card",children:[t.jsx("a",{className:"detail-attachment-link",href:He,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{src:He,alt:X.originalName,className:"detail-attachment-image"})}),t.jsxs("div",{className:"detail-attachment-meta",children:[X.originalName," (",GM(X.size),")"]}),t.jsx("button",{className:"detail-attachment-delete",onClick:()=>zn(X.filename),title:"Delete attachment",children:"×"})]},X.filename)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no attachments)"}),t.jsx("input",{className:"detail-hidden-file-input",ref:Y,type:"file",accept:"image/*",onChange:Ln}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Y.current?.click(),disabled:F,children:F?"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(X=>{const He=s.find(It=>It.id===X),ct=He?.title||He?.description||X;return t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>zs(X),onKeyDown:It=>{(It.key==="Enter"||It.key===" ")&&(It.preventDefault(),zs(X))},role:"link",tabIndex:0,title:`Click to view ${X}`,children:[t.jsx("span",{className:"detail-dep-id",children:X}),t.jsx("span",{className:"detail-dep-label",children:Gm(ct,40)})]}),t.jsx("button",{className:"dep-remove-btn",onClick:It=>ei(It,X),title:`Remove dependency ${X}`,children:"×"})]},X)})}):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:()=>{I&&Q(""),O(X=>!X)},children:"Add Dependency"}),I&&(()=>{const X=J.toLowerCase(),He=X?Rr.filter(ct=>ct.id.toLowerCase().includes(X)||ct.title&&ct.title.toLowerCase().includes(X)||ct.description&&ct.description.toLowerCase().includes(X)):Rr;return t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:J,onChange:ct=>Q(ct.target.value),onClick:ct=>ct.stopPropagation()}),He.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):He.map(ct=>t.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{Gn(ct.id),O(!1)},children:[t.jsx("span",{className:"dep-dropdown-id",children:ct.id}),t.jsx("span",{className:"dep-dropdown-title",children:Gm(ct.title||ct.description||ct.id,30)})]},ct.id))]})})()]})]}),e.column==="in-review"&&t.jsx(pM,{taskId:e.id,projectId:n,prInfo:e.prInfo,automationStatus:e.status??null,autoMerge:Rt?.autoMerge??!1,prAuthAvailable:g??!1,onPrCreated:X=>{e.prInfo=X,h(`PR #${X.number} created`,"success")},onPrUpdated:X=>{e.prInfo=X},addToast:h})]})]})]}),t.jsx("div",{className:"modal-actions",children:Ie?t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"modal-edit-hint",children:[t.jsx("kbd",{children:"Ctrl+Enter"})," to save · ",t.jsx("kbd",{children:"Escape"})," to cancel"]}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("button",{className:"btn btn-sm",onClick:pn,disabled:At,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:bn,disabled:At,children:At?"Saving…":"Save"})]}):t.jsxs(t.Fragment,{children:[e.column==="triage"&&e.status==="awaiting-approval"&&k.prompt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:at,children:"Approve Plan"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:We,children:"Reject Plan"})]}),e.column==="triage"&&e.status!=="awaiting-approval"&&!R&&t.jsx("button",{className:"btn btn-sm btn-danger",onClick:ns,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(e.column!=="triage"||e.status==="awaiting-approval"||R)&&t.jsxs("div",{className:"detail-actions-dropdown",ref:De,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{te(X=>!X),B(!1)},"aria-haspopup":"menu","aria-expanded":ge,children:["Actions",t.jsx(qt,{size:12})]}),ge&&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:()=>rn(ns),children:"Delete"}),d&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>rn(oe),children:"Duplicate"}),(e.column==="done"||e.column==="in-review")&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>rn(fn),children:"Refine"}),t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>rn(mt),children:"Respecify"}),R&&u&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>rn(Si),children:"Retry"}),e.column!=="done"&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>rn(_e),children:e.paused?"Unpause":"Pause"})]})]}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("div",{className:"detail-move-dropdown",ref:j,children:e.column==="in-review"?t.jsxs("div",{className:"detail-move-actions-in-review",children:[t.jsxs("div",{children:[t.jsxs("button",{ref:V,className:"btn btn-primary btn-sm detail-move-btn",onClick:Os,onKeyDown:ti,disabled:!Tn,"aria-label":Tn?`Move to ${_n[Tn]}`:void 0,"aria-haspopup":as?"menu":void 0,"aria-expanded":as?$t:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",Tn?_n[Tn]:""]}),as&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(qt,{size:12})})]}),$t&&as&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:ni,children:Aa.map(X=>t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>tn(X),onKeyDown:ni,children:X==="in-progress"?"Back to In Progress":`Move to ${_n[X]}`},X))})]}),$r?t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:$r}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:On,children:"Merge & Close"})]}):t.jsxs("div",{children:[t.jsxs("button",{ref:V,className:"btn btn-primary btn-sm detail-move-btn",onClick:Os,onKeyDown:ti,disabled:!Tn,"aria-label":Tn?`Move to ${_n[Tn]}`:void 0,"aria-haspopup":as?"menu":void 0,"aria-expanded":as?$t:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",Tn?_n[Tn]:""]}),as&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(qt,{size:12})})]}),$t&&as&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:ni,children:Aa.map(X=>t.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>tn(X),onKeyDown:ni,children:["Move to ",_n[X]]},X))})]})})]})}),Fe&&t.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:Un,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal detail-refine-modal",onClick:X=>X.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:Un,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"detail-body",children:[t.jsx("p",{className:"detail-refine-help",children:"Describe what needs to be refined or improved..."}),t.jsx("textarea",{className:"detail-refine-textarea",value:Ze,onChange:X=>Xe(X.target.value),placeholder:"Enter your feedback here...",rows:6,maxLength:2e3,autoFocus:!0}),t.jsxs("div",{className:"detail-refine-input-group",children:[t.jsxs("div",{className:"detail-refine-char-count",children:[Ze.length,"/2000 characters"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:xs,disabled:!Ze.trim()||Qe,children:Qe?"Creating...":"Create Refinement Task"})]})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:Un,disabled:Qe,children:"Cancel"})})]})})]})})}const ZM=640;function eA({isOpen:e,onClose:n,onImport:s,tasks:i,projectId:r}){const[o,l]=a.useState(""),[c,u]=a.useState(""),[d,m]=a.useState(""),[h,g]=a.useState(!1),[p,f]=a.useState("issues"),[x,v]=a.useState([]),[b,y]=a.useState(null),[S,k]=a.useState([]),[R,N]=a.useState(null),[M,C]=a.useState(null),[z,A]=a.useState(!1),[P,F]=a.useState([]),[W,$]=a.useState(!1),[_,I]=a.useState(""),O=a.useRef(!1),J=a.useRef(null);Xs(J,e,"fusion:github-modal-size");const Q=wi(n),[E,D]=a.useState(!1),[T,w]=a.useState("list"),q=a.useRef(null),G=new Set;for(const be of i){const Me=be.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);Me&&G.add(Me[1]);const Be=be.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);Be&&G.add(Be[1])}a.useEffect(()=>{if(e)return l(""),u(""),m(""),v([]),y(null),k([]),N(null),f("issues"),C(null),A(!1),F([]),$(!0),I(""),q.current=null,O.current=!0,ay().then(be=>{if(O.current)if(F(be),$(!1),be.length===1){const Me=be[0];l(Me.owner),u(Me.repo),I(Me.name)}else be.length>1&&(l(""),u(""),I(""))}).catch(()=>{O.current&&$(!1)}),()=>{O.current=!1}},[e]);const me=a.useCallback(be=>{if(I(be),be==="")l(""),u("");else{const Me=P.find(Be=>Be.name===be);Me&&(l(Me.owner),u(Me.repo))}},[P]),ce=a.useCallback(async()=>{if(!o.trim()||!c.trim()){C("Repository must be selected");return}g(!0),C(null),v([]),y(null);try{const be=d.split(",").map(Be=>Be.trim()).filter(Boolean),Me=await ty(o.trim(),c.trim(),30,be.length>0?be:void 0);v(Me),Me.length===0&&C("No open issues found")}catch(be){C(ke(be)||"Failed to fetch issues")}finally{g(!1)}},[o,c,d]),ae=a.useCallback(async()=>{if(!o.trim()||!c.trim()){C("Repository must be selected");return}g(!0),C(null),k([]),N(null);try{const be=await sy(o.trim(),c.trim(),30);k(be),be.length===0&&C("No open pull requests found")}catch(be){C(ke(be)||"Failed to fetch pull requests")}finally{g(!1)}},[o,c]);a.useEffect(()=>{if(!e||!o.trim()||!c.trim()||h||z)return;const be={owner:o.trim(),repo:c.trim(),labels:d.trim(),tab:p};q.current?.owner===be.owner&&q.current?.repo===be.repo&&q.current?.labels===be.labels&&q.current?.tab===be.tab||(q.current=be,p==="issues"?ce():ae())},[o,c,d,p,e,h,z,ce,ae]),a.useEffect(()=>{if(!e)return;const be=Me=>{Me.key==="Escape"&&n()};return document.addEventListener("keydown",be),()=>document.removeEventListener("keydown",be)},[e,n]),a.useEffect(()=>{if(!e)return;const be=()=>{D(window.innerWidth<=ZM)};return be(),window.addEventListener("resize",be),()=>window.removeEventListener("resize",be)},[e]);const pe=a.useCallback(be=>{y(be),E&&w("preview")},[E]),U=a.useCallback(be=>{N(be),E&&w("preview")},[E]),Ne=a.useCallback(()=>{w("list")},[]),ne=a.useCallback(async()=>{if(p==="issues"){if(b===null)return;A(!0),C(null);try{const be=await ny(o.trim(),c.trim(),b,r);s(be),y(null),E&&T==="preview"&&w("list")}catch(be){const Me=ke(be);Me?.includes("already imported")?C(Me):C(Me||"Failed to import issue")}finally{A(!1)}}else{if(R===null)return;A(!0),C(null);try{const be=await iy(o.trim(),c.trim(),R,r);s(be),N(null),E&&T==="preview"&&w("list")}catch(be){const Me=ke(be);Me?.includes("already imported")?C(Me):C(Me||"Failed to import pull request")}finally{A(!1)}}},[p,b,R,o,c,s,E,T]),xe=x.find(be=>be.number===b),le=S.find(be=>be.number===R);if(!e)return null;const ve=P.length>0,ee=P.length===1,Ee=x.filter(be=>G.has(be.html_url)).length,Fe=S.filter(be=>G.has(be.html_url)).length,Ke=M==="No open issues found",Ze=M==="No open pull requests found",Xe=p==="issues"?Ke:Ze,Qe=!!M&&!Ke&&x.length===0&&!h,it=!!M&&!Ze&&S.length===0&&!h,Ie=p==="issues"?Qe:it,Ge=h||x.length>0||Ke||Qe,se=h||S.length>0||Ze||it,ye=p==="issues"?Ge:se,Z=!!M&&x.length>0&&!Ke,Te=!!M&&S.length>0&&!Ze,ze=p==="issues"?Z:Te;return t.jsx("div",{className:"modal-overlay open",...Q,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg github-import-modal",ref:J,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:()=>{f("issues"),N(null)},disabled:h||z,children:[t.jsx(Ro,{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:()=>{f("pulls"),y(null)},disabled:h||z,children:[t.jsx(hs,{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:W?t.jsxs("div",{className:"github-import-toolbar__loading",role:"status","aria-live":"polite",children:[t.jsx(ot,{size:16,className:"spin"}),t.jsx("span",{children:"Detecting…"})]}):ve?ee?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:P[0].name}),t.jsxs("span",{className:"github-import-remote-pill__repo",children:[P[0].owner,"/",P[0].repo]})]}):t.jsxs("div",{className:"github-import-remote-select",children:[t.jsx("label",{htmlFor:"gh-remote",className:"visually-hidden",children:"Repository"}),t.jsxs("select",{id:"gh-remote",value:_,onChange:be=>me(be.target.value),disabled:h||z,"aria-label":"Select Git remote",children:[t.jsx("option",{value:"",children:"Select remote…"}),P.map(be=>t.jsxs("option",{value:be.name,children:[be.name," (",be.owner,"/",be.repo,")"]},be.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:d,onChange:be=>m(be.target.value),onKeyDown:be=>be.key==="Enter"&&ce(),disabled:h||z||!ve,"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"?ce:ae,disabled:h||z||!o.trim()||!c.trim(),"aria-label":h?`Loading ${p}`:`Load ${p} from repository`,title:h?"Loading…":`Load ${p}`,children:[h?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Nn,{size:14}),t.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!W&&!ve&&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"})]}),ze&&t.jsx("div",{className:"form-error github-import-banner",role:"alert",children:M}),t.jsxs("div",{className:"github-import-workspace",children:[t.jsxs("section",{className:`github-import-list-pane ${E?"mobile":""} ${T==="list"?"active":""}`,"data-testid":"github-import-list-pane","aria-labelledby":"github-import-results-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[t.jsx("h4",{id:"github-import-results-heading",children:p==="issues"?"Issues":"Pull Requests"}),p==="issues"&&x.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[x.length," issue",x.length===1?"":"s"]}),t.jsxs("span",{children:[Ee," 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:[Fe," imported"]})]})]}),t.jsxs("div",{className:"github-import-pane-content",children:[!ye&&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(ot,{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."})]})]}),Ie&&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:M})]})}),Xe&&t.jsx("div",{className:"github-import-state github-import-state--empty",role:"status",children:t.jsxs("div",{children:[t.jsxs("strong",{children:["No open ",p==="issues"?"issues":"pull requests"," found"]}),t.jsx("span",{children:p==="issues"?"Try a different label filter or choose another repository.":"Choose another repository."})]})}),p==="issues"&&x.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:x.map(be=>{const Me=G.has(be.html_url);return t.jsxs("div",{className:`issue-item ${b===be.number?"selected":""} ${Me?"imported":""}`,onClick:()=>!Me&&pe(be.number),children:[t.jsx("input",{type:"radio",name:"issue",checked:b===be.number,onChange:()=>pe(be.number),disabled:Me,"aria-label":`Select issue #${be.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",be.number]}),t.jsx("span",{className:"issue-title",children:be.title})]}),be.labels.length>0&&t.jsx("span",{className:"issue-labels",children:be.labels.map(Be=>t.jsx("span",{className:"label-chip",children:Be.name},Be.name))})]}),Me&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},be.number)})}),p==="pulls"&&S.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:S.map(be=>{const Me=G.has(be.html_url);return t.jsxs("div",{className:`issue-item ${R===be.number?"selected":""} ${Me?"imported":""}`,onClick:()=>!Me&&U(be.number),children:[t.jsx("input",{type:"radio",name:"pull",checked:R===be.number,onChange:()=>U(be.number),disabled:Me,"aria-label":`Select pull request #${be.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",be.number]}),t.jsx("span",{className:"issue-title",children:be.title})]}),t.jsxs("span",{className:"pull-branch-info",children:[be.headBranch," → ",be.baseBranch]})]}),Me&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},be.number)})})]})]}),t.jsxs("section",{className:`github-import-preview-pane ${E?"mobile":""} ${T==="preview"?"active":""}`,"data-testid":"github-import-preview-pane","aria-labelledby":"github-import-preview-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[E&&t.jsxs("button",{className:"github-import-back-button",onClick:Ne,"data-testid":"github-import-back-button","aria-label":`Back to ${p==="issues"?"issues":"pull requests"} list`,children:[t.jsx(wa,{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"&&xe?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Issue #",xe.number]}),t.jsx("div",{className:"preview-title",children:xe.title}),t.jsx("div",{className:"preview-body",children:xe.body?xe.body.slice(0,200)+(xe.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"&&le?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Pull Request #",le.number]}),t.jsx("div",{className:"preview-title",children:le.title}),t.jsxs("div",{className:"preview-branch",children:[t.jsx("strong",{children:"Branch:"})," ",le.headBranch," → ",le.baseBranch]}),t.jsx("div",{className:"preview-body",children:le.body?le.body.slice(0,200)+(le.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:z,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:ne,disabled:(p==="issues"?b===null:R===null)||z,children:z?t.jsx(ot,{size:14,className:"spin"}):"Import"})]})]})})}const tA=["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 nA(e,n){return e&&n?`${e}/${n}`:""}function sA(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 iA({isOpen:e,onClose:n,onTaskCreated:s,onTasksCreated:i,tasks:r,initialPlan:o,projectId:l,resumeSessionId:c}){const[u,d]=a.useState(""),[m,h]=a.useState({type:"initial"}),[g,p]=a.useState(null),[f,x]=a.useState([]),[v,b]=a.useState([]),[y,S]=a.useState(null),k=a.useRef(!1),R=a.useRef(!1),[N,M]=a.useState(""),[C,z]=a.useState(!0),[A,P]=a.useState(!1),[F,W]=a.useState(!1),[$,_]=a.useState(null),[I,O]=a.useState(0),J=a.useRef(null),Q=a.useRef(null),E=a.useRef(null),D=a.useRef(null),[T,w]=a.useState(c??null),q=a.useMemo(()=>Wi(),[]),{isLockedByOther:G,takeControl:me,isLoading:ce}=qo(e?T:null),{activeTabMap:ae,broadcastUpdate:pe,broadcastCompleted:U,broadcastLock:Ne,broadcastUnlock:ne,broadcastHeartbeat:xe}=Sa(),[le,ve]=a.useState(void 0),[ee,Ee]=a.useState(void 0),[Fe,Ke]=a.useState([]),[Ze,Xe]=a.useState(!1),[Qe,it]=a.useState(null),[Ie,Ge]=a.useState([]),[se,ye]=a.useState([]),Z=a.useRef(null),[Te,ze]=a.useState([]),[be,Me]=a.useState(!1),[Be,lt]=a.useState(c??null),[je,ie]=a.useState(!!c),[Ae,he]=a.useState(null),Re=a.useRef(!1),Je=a.useRef(null);Xs(Q,e,"fusion:planning-modal-size"),a.useEffect(()=>{const B=Je.current;if(!B)return;B.scrollHeight-B.scrollTop-B.clientHeight<32&&(B.scrollTop=B.scrollHeight)},[N]),a.useEffect(()=>{if(m.type!=="loading"){_(null),O(0);return}const B=Date.now();_(B),O(0);const ge=setInterval(()=>{O(Math.max(0,Math.floor((Date.now()-B)/1e3)))},1e3);return()=>clearInterval(ge)},[m.type]);const $e=a.useCallback(()=>{d(""),h({type:"initial"}),p(null),x([]),b([]),S(null),M(""),P(!1),W(!1),ve(void 0),Ee(void 0),D.current=null,w(null)},[]),de=nA(le,ee),re=a.useCallback((B,ge)=>{if(!B||!ge)return"Using default";const te=Fe.find(j=>j.provider===B&&j.id===ge);return te?`${te.provider}/${te.id}`:`${B}/${ge}`},[Fe]),ue=a.useCallback(async()=>{Xe(!0),it(null);try{const B=await cs();Ke(B.models),Ge(B.favoriteProviders),ye(B.favoriteModels)}catch(B){it(ke(B)||"Failed to load models")}finally{Xe(!1)}},[]),Pe=a.useCallback(B=>{Ge(ge=>{const te=ge,V=te.includes(B)?te.filter(De=>De!==B):[B,...te];return sn({favoriteProviders:V,favoriteModels:se}).catch(()=>{Ge(te)}),V})},[se]),Se=a.useCallback(B=>{ye(ge=>{const te=ge,V=te.includes(B)?te.filter(De=>De!==B):[B,...te];return sn({favoriteProviders:Ie,favoriteModels:V}).catch(()=>{ye(te)}),V})},[Ie]),fe=a.useCallback(B=>{E.current?.close();const ge=ik(B,l,{onThinking:te=>{M(j=>j+te),pe({sessionId:B,status:"generating",needsInput:!1,owningTabId:q,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onQuestion:te=>{P(!1),W(!1),ea(l),h({type:"question",session:{sessionId:B,currentQuestion:te,summary:null}}),M(""),pe({sessionId:B,status:"awaiting_input",needsInput:!0,owningTabId:q,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onSummary:te=>{P(!1),W(!1),ea(l),h({type:"summary",session:{sessionId:B,currentQuestion:null,summary:te},summary:te}),S(te),M(""),pe({sessionId:B,status:"complete",needsInput:!1,owningTabId:q,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onError:te=>{const j=te||"Session failed while contacting the AI.";P(!0),(async()=>{try{const V=await oi(B);if(V&&(V.status==="generating"||V.status==="awaiting_input")){fe(B);return}}catch{}P(!1),W(!1),p(null),h(V=>V.type==="question"||V.type==="summary"||V.type==="error"?{type:"error",session:V.session,errorMessage:j}:{type:"error",session:{sessionId:B,currentQuestion:null,summary:null},errorMessage:j}),M(""),D.current=B,pe({sessionId:B,status:"error",needsInput:!1,owningTabId:q,type:"planning",title:u.trim()||"Planning session",projectId:l??null}),U({sessionId:B,status:"error"})})()},onComplete:()=>{P(!1),W(!1),D.current=null,U({sessionId:B,status:"complete"})},onConnectionStateChange:te=>{P(te==="reconnecting")}});E.current=ge},[U,pe,u,l,q]),tt=a.useCallback(async B=>{const ge=B??u;if(ge.trim()){p(null),M(""),b([]),x([]),P(!1),h({type:"loading"});try{const te=le&&ee?{planningModelProvider:le,planningModelId:ee}:void 0,{sessionId:j}=await Uy(ge.trim(),l,te);D.current=j,w(j),lt(j),fe(j),x([])}catch(te){P(!1),p(ke(te)||"Failed to start planning session"),h({type:"initial"}),D.current=null,w(null)}}},[fe,u,ee,le,l]);a.useEffect(()=>{e&&m.type==="initial"&&J.current?.focus()},[e,m.type]),a.useEffect(()=>{e&&ue()},[e,ue]),a.useEffect(()=>{if(e&&o&&!k.current&&m.type==="initial"){d(o);const B=setTimeout(()=>{k.current=!0,tt(o)},0);return()=>clearTimeout(B)}else if(e&&!o&&!k.current&&!R.current&&m.type==="initial"){R.current=!0;const B=YN(l);B&&d(B)}},[e,o,m.type,tt,l]);const ut=a.useCallback(async B=>{E.current?.close(),E.current=null,p(null),M(""),x([]),b([]),S(null),W(!1),h({type:"loading"});try{const ge=await oi(B);if(!ge){lt(null),ie(!1),h({type:"initial"});return}D.current=B,w(B);const te=fa(ge.conversationHistory);if(b(te),x(te.map(j=>j.response).filter(j=>!!(j&&typeof j=="object"&&!Array.isArray(j)))),ge.status==="awaiting_input"&&ge.currentQuestion){ea(l);const j=JSON.parse(ge.currentQuestion);h({type:"question",session:{sessionId:B,currentQuestion:j,summary:null}}),ge.thinkingOutput&&M(ge.thinkingOutput),fe(B)}else if(ge.status==="complete"&&ge.result){ea(l);const j=JSON.parse(ge.result);h({type:"summary",session:{sessionId:B,currentQuestion:null,summary:j},summary:j}),S(j)}else ge.status==="generating"?(h({type:"loading"}),ge.thinkingOutput&&M(ge.thinkingOutput),fe(B)):ge.status==="error"&&h({type:"error",session:{sessionId:B,currentQuestion:null,summary:null},errorMessage:ge.error||"Session failed"})}catch{p("Failed to load session"),h({type:"initial"})}},[fe,l]);a.useEffect(()=>{!e||!c||D.current!==c&&(lt(c),ie(!0),ut(c))},[e,c,ut]),a.useEffect(()=>{e&&Be&&(c&&c===Be||E.current?.isConnected()||ut(Be))},[e]);const vt=a.useCallback(async()=>{Me(!0);try{const ge=(await Zc(l)).filter(te=>te.type==="planning").sort((te,j)=>Date.parse(j.updatedAt)-Date.parse(te.updatedAt));ze(ge)}catch{}finally{Me(!1)}},[l]);a.useEffect(()=>{e&&vt()},[e,vt]),a.useEffect(()=>{if(!e)return;const B=l?`?projectId=${encodeURIComponent(l)}`:"",ge=j=>{try{const V=JSON.parse(j.data);if(V.type!=="planning")return;ze(De=>{const nt=De.findIndex(Pt=>Pt.id===V.id);return(nt>=0?[...De.slice(0,nt),V,...De.slice(nt+1)]:[V,...De]).sort((Pt,Rt)=>Date.parse(Rt.updatedAt)-Date.parse(Pt.updatedAt))})}catch{}},te=j=>{try{const V=JSON.parse(j.data);ze(De=>De.filter(nt=>nt.id!==V))}catch{}};return Ls(`/api/events${B}`,{events:{"ai_session:updated":ge,"ai_session:deleted":te},onReconnect:()=>{vt()}})},[e,l,vt]);const gt=a.useCallback(B=>{if(Be===B){ie(!0);return}lt(B),ie(!0),ut(B)},[ut,Be]),dt=a.useCallback(()=>{E.current?.close(),E.current=null,$e(),lt(null),ie(!0)},[$e]),wt=a.useCallback(()=>{ie(!1)},[]),Mt=a.useCallback(async B=>{const ge=j=>j==="generating"||j==="awaiting_input",te=Te.find(j=>j.id===B);if(te&&ge(te.status))try{await np(B,l,q)}catch{}try{await up(B)}catch{}U({sessionId:B,status:"complete",timestamp:Date.now()}),ze(j=>j.filter(V=>V.id!==B)),Be===B&&(E.current?.close(),E.current=null,$e(),lt(null),ie(!1)),he(null)},[U,Te,l,$e,Be,q]);a.useEffect(()=>{e||(k.current=!1,R.current=!1,P(!1),W(!1),w(null))},[e]),a.useEffect(()=>{if(!e){Z.current&&(ne(Z.current,q),Z.current=null);return}if(T&&Z.current!==T){Z.current&&ne(Z.current,q),Ne(T,q),Z.current=T;return}!T&&Z.current&&(ne(Z.current,q),Z.current=null)},[Ne,ne,e,T,q]),a.useEffect(()=>{if(!e||!T||Z.current!==T)return;xe(q);const B=setInterval(()=>{xe(q)},3e4);return()=>{clearInterval(B)}},[xe,e,T,q]),a.useEffect(()=>()=>{E.current?.close(),E.current=null,Z.current&&(ne(Z.current,q),Z.current=null)},[ne,q]),a.useEffect(()=>{if(!e)return;const B=()=>{E.current?.close(),E.current=null};return window.addEventListener("beforeunload",B),()=>window.removeEventListener("beforeunload",B)},[e]);const yt=a.useCallback(()=>{u&&m.type==="initial"&&JN(u,l),E.current?.close(),E.current=null,P(!1),W(!1),n()},[u,n,l,m.type]);a.useEffect(()=>{if(!e)return;const B=ge=>{ge.key==="Escape"&&yt()};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[e,yt]);const Et=a.useCallback(async B=>{if(m.type!=="question")return;const{session:ge}=m,te=ge.sessionId,j=ge.currentQuestion;if(!j){p("No active question in session");return}p(null),x(V=>[...V,B]),b(V=>[...V,{question:j,response:B}]),h({type:"loading"}),M("");try{await By(te,B,l,q)}catch(V){p(ke(V)||"Failed to submit response"),h({type:"question",session:ge})}},[l,q,m]),Nt=a.useCallback(async()=>{const B=D.current;if(B){try{await qy(B,l,q)}catch{}E.current?.close(),E.current=null,P(!1),W(!1),h({type:"error",session:{sessionId:B,currentQuestion:null,summary:null},errorMessage:"Generation stopped by user. You can retry or start a new session."}),M("")}},[l,q]),Tt=a.useCallback(async()=>{if(m.type!=="error")return;const B=m.session;p(null),W(!0),M(""),h({type:"loading"}),fe(B.sessionId);try{D.current=B.sessionId,w(B.sessionId),await Hy(B.sessionId,l,q)}catch(ge){let te=ge;if((ke(ge)||"").includes("not in an error state"))try{const V=await oi(B.sessionId);if(!V)throw new Error("Failed to refresh planning session.");if(D.current=V.id,w(V.id),V.status==="generating")M(V.thinkingOutput??""),h({type:"loading"});else if(V.status==="awaiting_input"){if(!V.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const De=JSON.parse(V.currentQuestion);ea(l),h({type:"question",session:{sessionId:V.id,currentQuestion:De,summary:null}}),E.current?.isConnected()||fe(V.id)}else if(V.status==="complete"){if(!V.result)throw new Error("Planning session is complete but has no result.");const De=JSON.parse(V.result);ea(l),h({type:"summary",session:{sessionId:V.id,currentQuestion:null,summary:De},summary:De}),S(De)}else V.status==="error"&&h({type:"error",session:{sessionId:V.id,currentQuestion:null,summary:null},errorMessage:V.error||"Retry failed. Please try again."});P(!1);return}catch(V){te=V}E.current?.close(),E.current=null,h({type:"error",session:B,errorMessage:ke(te)||"Retry failed. Please try again."}),P(!1)}finally{W(!1)}},[fe,l,q,m]),Ht=a.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const B=m.session.sessionId,ge=await Vy(B,y??void 0,l);s(ge),lt(null),ze(te=>te.filter(j=>j.id!==B)),U({sessionId:B,status:"complete",timestamp:Date.now()}),yt()}catch(B){p(ke(B)||"Failed to create task"),h({type:"summary",session:m.session,summary:m.summary})}}},[U,y,m,l,s,yt]),Ut=a.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const B=await Wy(m.session.sessionId,y??void 0,l);w(B.sessionId),h({type:"breakdown",sessionId:B.sessionId,subtasks:B.subtasks,dirty:!1})}catch(B){p(ke(B)||"Failed to start breakdown"),h({type:"summary",session:m.session,summary:m.summary})}}},[y,m,l]),Vt=a.useCallback(async()=>{if(m.type==="breakdown"){p(null),h({type:"creating"});try{const B=m.sessionId,ge=await Ky(B,m.subtasks,l);i(ge.tasks),ze(te=>te.filter(j=>j.id!==B)),U({sessionId:B,status:"complete",timestamp:Date.now()}),d(""),h({type:"initial"}),p(null),x([]),b([]),S(null),M(""),ve(void 0),Ee(void 0),D.current=null,w(null),lt(null),n()}catch(B){p(ke(B)||"Failed to create tasks"),h({type:"breakdown",sessionId:m.sessionId,subtasks:m.subtasks,dirty:m.dirty})}}},[U,m,i,n,l]),zt=a.useCallback(()=>{if(m.type==="question"&&f.length>0){const B=f.slice(0,-1);x(B),h({type:"question",session:m.session})}},[m,f]),Ct=()=>m.type==="question"?Math.min(f.length+1,3):3,At=T?ae.get(T):null,kt=At&&At.tabId!==q,Kt=!!(kt&&!At.stale),$t=G&&(!kt||At.stale);return e?t.jsx("div",{className:"modal-overlay open",onMouseDown:B=>{Re.current=B.target===B.currentTarget},onClick:B=>{B.target===B.currentTarget&&Re.current&&yt(),Re.current=!1},role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",ref:Q,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[je&&t.jsx("button",{className:"modal-back planning-mobile-back",onClick:wt,"aria-label":"Back to sessions",title:"Back to sessions",children:t.jsx(Ao,{size:18})}),t.jsx(Ys,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Planning Mode"})]}),t.jsx("div",{className:"modal-header-actions",children:t.jsx("button",{className:"modal-close",onClick:yt,"aria-label":"Close",children:t.jsx(Ot,{size:20})})})]}),t.jsxs("div",{className:`planning-modal-body planning-modal-body--split ${je?"planning-modal-body--show-detail":"planning-modal-body--show-list"}`,children:[t.jsx(cA,{sessions:Te,loading:be,selectedSessionId:Be,pendingDeleteId:Ae,onSelectSession:gt,onNewSession:dt,onRequestDelete:he,onConfirmDelete:B=>void Mt(B),onCancelDelete:()=>he(null)}),t.jsxs("div",{className:"planning-detail",children:[g&&t.jsx("div",{className:"form-error planning-error",children:g}),A&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Kt&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),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(qn,{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:J,id:"initial-plan",rows:4,className:"planning-textarea",placeholder:"e.g., Build a user authentication system with login, signup, and password reset...",value:u,onChange:B=>d(B.target.value),onKeyDown:B=>{B.key==="Enter"&&!B.shiftKey&&u.trim()&&(B.preventDefault(),tt())}})]}),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:tA.map((B,ge)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>d(B),children:B.length>40?B.slice(0,40)+"...":B},ge))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"planning-modal-model",className:"form-label",children:["Planning Model",Ze&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx($n,{id:"planning-modal-model",label:"Planning Model",value:de,onChange:B=>{const{provider:ge,modelId:te}=sA(B);ve(ge),Ee(te)},models:Fe,disabled:Ze,favoriteProviders:Ie,onToggleFavorite:Pe,favoriteModels:se,onToggleModelFavorite:Se}),Qe&&t.jsxs("div",{className:"form-hint form-hint-error",children:[Qe," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{ue()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${le&&ee?"model-badge-custom":"model-badge-default"}`,children:re(le,ee)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>tt(),disabled:!u.trim(),children:[t.jsx(Ys,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),m.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(ot,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:N?"AI is thinking...":"Generating next question..."}),$&&t.jsxs("div",{className:"planning-elapsed",children:["Thinking… (",I,"s)"]}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>z(!C),type:"button",children:C?"Hide thinking":"Show thinking"}),t.jsx("div",{className:"planning-loading-actions",children:t.jsxs("button",{className:"btn planning-stop-btn",type:"button",onClick:()=>void Nt(),children:[t.jsx(Vg,{size:14}),t.jsx("span",{className:"icon-ml-6",children:"Stop"})]})}),C&&N&&t.jsx("div",{className:"planning-thinking-output",ref:Je,children:t.jsx("pre",{children:N})})]})]}),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(Es,{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 Tt(),disabled:F,children:[F?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Nn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:F?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:yt,disabled:F,children:"Dismiss"})]})]})]})}),m.type==="creating"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(ot,{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(aA,{question:m.session.currentQuestion,progress:Ct(),historyEntries:v,onSubmit:Et,onBack:f.length>0?zt:void 0})}),m.type==="summary"&&y&&t.jsx(rA,{summary:y,historyEntries:v,onSummaryChange:S,tasks:r,onCreateTask:Ht,onBreakIntoTasks:Ut,onRefine:()=>{h({type:"question",session:m.session})},isLoading:!1}),m.type==="breakdown"&&t.jsx(lA,{subtasks:m.subtasks,dirty:m.dirty,isLoading:!1,onUpdateSubtasks:B=>h({...m,subtasks:B,dirty:!0}),onCreateTasks:Vt,onBack:()=>{const ge={sessionId:m.sessionId,currentQuestion:null,summary:y??null};y&&h({type:"summary",session:ge,summary:y})}})]}),G&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Io,{size:16}),t.jsx("span",{children:$t?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),$t&&t.jsx("button",{type:"button",onClick:()=>{me()},disabled:ce,className:"btn btn-primary session-lock-take-control",children:ce?"Taking control...":"Take Control"})]})})]})]})}):null}function aA({question:e,progress:n,historyEntries:s,onSubmit:i,onBack:r}){const[o,l]=a.useState({}),[c,u]=a.useState(""),d=a.useCallback(()=>{e.type==="text"?i({[e.id]:c}):e.type==="confirm"?i({[e.id]:o[e.id]===!0}):i(o)},[e,o,c,i]);a.useEffect(()=>{l({}),u("")},[e.id]);const m=()=>{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(Es,{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(h=>t.jsx("div",{className:`planning-progress-step ${h<=n?"active":""}`},h))}),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:h=>u(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&c.trim()&&(h.preventDefault(),d())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(h=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:h.id,checked:o[e.id]===h.id,onChange:()=>l({[e.id]:h.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:h.label}),h.description&&t.jsx("span",{className:"planning-option-desc",children:h.description})]})]},h.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(h=>{const g=o[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:h.id,checked:g.includes(h.id),onChange:p=>{const f=p.target.checked?[...g,h.id]:g.filter(x=>x!==h.id);l({[e.id]:f})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:h.label}),h.description&&t.jsx("span",{className:"planning-option-desc",children:h.description})]})]},h.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(dn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!1?"selected":""}`,onClick:()=>l({[e.id]:!1}),children:[t.jsx(Ot,{size:18}),"No"]})]})]})]})]})]}),t.jsxs("div",{className:"planning-actions",children:[r&&t.jsxs("button",{className:"btn",onClick:r,children:[t.jsx(wa,{size:16,className:"icon-mr-4"}),"Back"]}),t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:d,disabled:!m(),children:["Continue",t.jsx(br,{size:16,className:"icon-ml-4"})]})]})]})}function rA({summary:e,historyEntries:n,onSummaryChange:s,tasks:i,onCreateTask:r,onBreakIntoTasks:o,onRefine:l,isLoading:c}){const[u,d]=a.useState(!1),[m,h]=a.useState(e.suggestedDependencies),g=p=>{const f=m.includes(p)?m.filter(x=>x!==p):[...m,p];h(f),s({...e,suggestedDependencies:f})};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(Es,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(dn,{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:()=>d(!u),children:u?"Collapse":"Expand"})]}),t.jsx("textarea",{className:`planning-textarea ${u?"expanded":""}`,rows:u?10:4,value:e.description,onChange:p=>s({...e,description:p.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Size"}),t.jsxs("select",{className:"planning-size-select",value:e.suggestedSize,onChange:p=>s({...e,suggestedSize:p.target.value}),disabled:c,children:[t.jsx("option",{value:"S",children:"S (Small)"}),t.jsx("option",{value:"M",children:"M (Medium)"}),t.jsx("option",{value:"L",children:"L (Large)"})]})]}),i.length>0&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Dependencies"}),t.jsx("div",{className:"planning-deps-list",children:i.map(p=>t.jsxs("label",{className:`planning-dep-chip ${m.includes(p.id)?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:m.includes(p.id),onChange:()=>g(p.id)}),t.jsx("span",{className:"planning-dep-id",children:p.id}),t.jsx("span",{className:"planning-dep-title",children:p.title||p.description.slice(0,30)})]},p.id))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Key Deliverables"}),t.jsx("ul",{className:"planning-deliverables",children:e.keyDeliverables.map((p,f)=>t.jsx("li",{children:p},f))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:l,disabled:c,children:[t.jsx(wa,{size:16,className:"icon-mr-4"}),"Refine Further"]}),t.jsxs("div",{className:"planning-summary-actions-right",children:[t.jsx("button",{className:"btn",onClick:o,disabled:c,title:"Break the plan into multiple tasks with dependencies",children:c?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Po,{size:16,className:"icon-mr-8"}),"Break into Tasks"]})}),t.jsx("button",{className:"btn btn-primary",onClick:r,disabled:c,children:c?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:16,className:"spin icon-mr-8"}),"Creating..."]}):t.jsxs(t.Fragment,{children:[t.jsx(dn,{size:16,className:"icon-mr-8"}),"Create Task"]})})]})]})]})}function Ym(e){const n=new Map(e.map(o=>[o.id,o.dependsOn])),s=new Set,i=new Set,r=o=>{if(s.has(o))return!0;if(i.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),i.add(o),!1};return e.some(o=>r(o.id))}function oA(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function lA({subtasks:e,dirty:n,isLoading:s,onUpdateSubtasks:i,onCreateTasks:r,onBack:o}){const[l,c]=a.useState(null),[u,d]=a.useState(null),[m,h]=a.useState(null),g=a.useRef([]),p=a.useMemo(()=>e.length===0||e.some(M=>!M.title.trim())?!0:Ym(e),[e]),f=a.useCallback((M,C)=>{i(e.map(z=>z.id===M?{...z,...C}:z))},[e,i]),x=a.useCallback(()=>{i([...e,oA(e.length+1)])},[e,i]),v=a.useCallback(M=>{i(e.filter(C=>C.id!==M).map(C=>({...C,dependsOn:C.dependsOn.filter(z=>z!==M)})))},[e,i]),b=a.useCallback((M,C)=>{if(C<0||C>=e.length)return;const z=[...e],[A]=z.splice(M,1);z.splice(C,0,A),i(z)},[e,i]),y=a.useCallback(M=>C=>{c(M),C.dataTransfer.setData("text/plain",M),C.dataTransfer.effectAllowed="move"},[]),S=a.useCallback(()=>{c(null),d(null),h(null)},[]),k=a.useCallback(M=>C=>{if(C.preventDefault(),M===l)return;const z=C.currentTarget.getBoundingClientRect(),A=z.top+z.height/2,P=C.clientY<A?"before":"after";d(M),h(P)},[l]),R=a.useCallback(M=>C=>{C.preventDefault();const z=C.dataTransfer.getData("text/plain");if(!z||z===M){S();return}const A=e.findIndex(_=>_.id===z),P=e.findIndex(_=>_.id===M);if(A===-1||P===-1){S();return}const F=[...e],[W]=F.splice(A,1);let $=P;m==="after"&&A<P&&$--,m==="after"&&$++,F.splice($,0,W),i(F),S()},[e,m,i,S]),N=a.useCallback(M=>{const C=M.currentTarget.getBoundingClientRect(),z=M.clientX,A=M.clientY;(z<C.left||z>C.right||A<C.top||A>C.bottom)&&(d(null),h(null))},[]);return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Po,{size:24,className:"icon-triage"}),t.jsx("h4",{children:"Break into Tasks"}),t.jsx("p",{className:"text-muted",children:"Review and edit the subtasks generated from your plan. Adjust titles, descriptions, sizes, and dependencies before creating."})]}),t.jsxs("div",{className:"planning-summary-form",children:[e.map((M,C)=>{const z=l===M.id,A=u===M.id,P=["task-detail-section","subtask-item",z?"subtask-item-dragging":"",A?"subtask-item-drop-target":"",A&&m==="before"?"subtask-item-drop-before":"",A&&m==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:P,"data-testid":`subtask-item-${C}`,draggable:!s,onDragStart:y(M.id),onDragEnd:S,onDragOver:k(M.id),onDrop:R(M.id),onDragLeave:N,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(Jc,{size:16}),t.jsx("strong",{children:M.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>b(C,C-1),disabled:s||C===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(Li,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>b(C,C+1),disabled:s||C===e.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(xr,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>v(M.id),disabled:s,children:[t.jsx(Xt,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:F=>{g.current[C]=F},value:M.title,onChange:F=>f(M.id,{title:F.target.value}),onKeyDown:F=>{F.key==="Enter"&&(F.preventDefault(),C<e.length-1&&g.current[C+1]?.focus())},disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:M.description,onChange:F=>f(M.id,{description:F.target.value}),disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:M.suggestedSize,onChange:F=>f(M.id,{suggestedSize:F.target.value}),disabled:s,children:[t.jsx("option",{value:"S",children:"S"}),t.jsx("option",{value:"M",children:"M"}),t.jsx("option",{value:"L",children:"L"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[e.slice(0,C).filter(F=>F.id!==M.id).map(F=>{const W=M.dependsOn.includes(F.id);return t.jsxs("label",{className:`planning-dep-chip ${W?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:W,onChange:()=>{const $=W?M.dependsOn.filter(_=>_!==F.id):[...M.dependsOn,F.id];f(M.id,{dependsOn:$})},disabled:s}),t.jsx("span",{className:"planning-dep-id",children:F.id}),t.jsx("span",{className:"planning-dep-title",children:F.title||"Untitled"})]},F.id)}),C===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),C>0&&e.slice(0,C).filter(F=>F.id!==M.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},M.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:x,disabled:s,children:[t.jsx(Zt,{size:16,className:"icon-mr-6"})," Add subtask"]}),Ym(e)&&t.jsx("div",{className:"form-error planning-error",children:"Dependencies contain a cycle. Remove circular references before creating tasks."})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:o,disabled:s,children:[t.jsx(wa,{size:16,className:"icon-mr-4"}),"Back to Summary"]}),t.jsx("button",{className:"btn btn-primary",onClick:r,disabled:s||p,children:s?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]})}function cA({sessions:e,loading:n,selectedSessionId:s,pendingDeleteId:i,onSelectSession:r,onNewSession:o,onRequestDelete:l,onConfirmDelete:c,onCancelDelete:u}){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:o,type:"button",children:[t.jsx(ib,{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(d=>{const m=d.id===s,h=i===d.id;return t.jsxs("div",{className:`planning-sidebar-item ${m?"selected":""} ${h?"pending-delete":""}`,children:[t.jsxs("button",{type:"button",className:"planning-sidebar-item-button",onClick:()=>r(d.id),children:[t.jsx(dA,{status:d.status}),t.jsxs("span",{className:"planning-sidebar-item-body",children:[t.jsx("span",{className:"planning-sidebar-item-title",children:d.title||"Untitled session"}),t.jsxs("span",{className:"planning-sidebar-item-meta",children:[t.jsx(uA,{status:d.status}),t.jsx("span",{"aria-hidden":!0,children:" · "}),t.jsx("span",{children:mA(d.updatedAt)})]})]})]}),h?t.jsxs("div",{className:"planning-sidebar-confirm",children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>c(d.id),children:"Delete"}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:u,children:"Cancel"})]}):t.jsx("button",{type:"button",className:"planning-sidebar-item-delete",onClick:g=>{g.stopPropagation(),l(d.id)},"aria-label":"Delete session",title:"Delete session",children:t.jsx(Xt,{size:14})})]},d.id)})]})]})}function dA({status:e}){switch(e){case"generating":return t.jsx(ot,{size:14,className:"spin planning-sidebar-status-icon planning-sidebar-status-generating"});case"awaiting_input":return t.jsx(mc,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-awaiting"});case"complete":return t.jsx(dn,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-complete"});case"error":return t.jsx(Xn,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-error"});default:return t.jsx(yi,{size:14,className:"planning-sidebar-status-icon"})}}function uA({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 mA(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 i=Math.floor(s/60);if(i<60)return`${i}m ago`;const r=Math.floor(i/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 hA(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function Qm(e){const n=new Map(e.map(o=>[o.id,o.dependsOn])),s=new Set,i=new Set,r=o=>{if(s.has(o))return!0;if(i.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),i.add(o),!1};return e.some(o=>r(o.id))}function pA({isOpen:e,onClose:n,initialDescription:s,onTasksCreated:i,parentTaskId:r,projectId:o,resumeSessionId:l}){const[c,u]=a.useState({type:"initial"}),[d,m]=a.useState([]),[h,g]=a.useState([]),[p,f]=a.useState(""),[x,v]=a.useState(!0),[b,y]=a.useState(!1),[S,k]=a.useState(!1),[R,N]=a.useState(s),[M,C]=a.useState(null),[z,A]=a.useState(!1),[P,F]=a.useState(null),[W,$]=a.useState(null),[_,I]=a.useState(null),O=a.useRef(null),J=a.useRef([]),Q=a.useRef(!1),E=a.useRef(null),D=c.type==="generating"||c.type==="editing"||c.type==="creating"||c.type==="error"?c.sessionId:null,T=a.useMemo(()=>Wi(),[]),{isLockedByOther:w,takeControl:q,isLoading:G}=qo(e?D:null),{activeTabMap:me,broadcastUpdate:ce,broadcastCompleted:ae,broadcastLock:pe,broadcastUnlock:U,broadcastHeartbeat:Ne}=Sa(),ne=a.useMemo(()=>d.length===0||d.some(ie=>!ie.title.trim())?!0:Qm(d),[d]),xe=c.type==="generating"||c.type==="editing"||c.type==="error",le=D?me.get(D):null,{confirm:ve}=Ds(),ee=le&&le.tabId!==T,Ee=!!(ee&&!le.stale),Fe=w&&(!ee||le.stale),Ke=a.useCallback(()=>{R&&QN(R,o),O.current?.close(),O.current=null,u({type:"initial"}),m([]),g([]),f(""),v(!0),y(!1),k(!1),C(null),A(!1),Q.current=!1},[R,o]),Ze=a.useCallback(()=>{O.current?.close(),O.current=null,n()},[n]),Xe=a.useCallback(async()=>{if(!((z||c.type==="editing"||c.type==="creating")&&!await ve({title:"Discard Changes",message:"Close subtask breakdown? Unsaved changes will be lost.",danger:!0}))){if(D)try{await ap(D,o,T)}catch{}Ke(),n()}},[z,n,Ke,D,T,c.type,o,ve]),Qe=a.useCallback(ie=>{O.current?.close(),O.current=yk(ie,o,{onThinking:Ae=>{f(he=>he+Ae),ce({sessionId:ie,status:"generating",needsInput:!1,owningTabId:T,type:"subtask",title:R.trim()||"Subtask breakdown",projectId:o??null})},onSubtasks:Ae=>{y(!1),k(!1),bl(o),m(Ae),u({type:"editing",sessionId:ie}),A(!1),ce({sessionId:ie,status:"awaiting_input",needsInput:!0,owningTabId:T,type:"subtask",title:R.trim()||"Subtask breakdown",projectId:o??null})},onError:Ae=>{const he=Ae||"Session failed while contacting the AI.";y(!1),k(!1),C(null),u({type:"error",sessionId:ie,errorMessage:he}),ce({sessionId:ie,status:"error",needsInput:!1,owningTabId:T,type:"subtask",title:R.trim()||"Subtask breakdown",projectId:o??null}),ae({sessionId:ie,status:"error"})},onComplete:()=>{ae({sessionId:ie,status:"complete"})},onConnectionStateChange:Ae=>{y(Ae==="reconnecting")}})},[ae,ce,R,o,T]),it=a.useCallback(async()=>{if(R.trim()){C(null),g([]),f(""),y(!1);try{const{sessionId:ie}=await xk(R.trim(),o);u({type:"generating",sessionId:ie}),Qe(ie)}catch(ie){C(ke(ie)||"Failed to start subtask breakdown"),u({type:"initial"})}}},[Qe,R,o]);a.useEffect(()=>{if(!e){Ke();return}if(e&&s&&!Q.current)N(s),Q.current=!0,it();else if(e&&!s&&!Q.current){const ie=XN(o);ie&&N(ie)}},[e,s,it,Ke]),a.useEffect(()=>{!e||!l||c.type!=="initial"||(async()=>{try{const ie=await oi(l);if(!ie)return;const Ae=fa(ie.conversationHistory);if(g(Ae),ie.status==="generating"||ie.status==="awaiting_input")f(ie.thinkingOutput??""),u({type:"generating",sessionId:l}),Qe(l);else if(ie.status==="complete"&&ie.result){bl(o);const he=JSON.parse(ie.result);m(he),u({type:"editing",sessionId:l})}else ie.status==="error"&&(C(null),u({type:"error",sessionId:l,errorMessage:ie.error??"Session encountered an error"}))}catch(ie){C(ke(ie)||"Failed to resume session")}})()},[Qe,e,l,c.type,o]),a.useEffect(()=>{if(!e){E.current&&(U(E.current,T),E.current=null);return}if(D&&E.current!==D){E.current&&U(E.current,T),pe(D,T),E.current=D;return}!D&&E.current&&(U(E.current,T),E.current=null)},[pe,U,e,D,T]),a.useEffect(()=>{if(!e||!D||E.current!==D)return;Ne(T);const ie=setInterval(()=>{Ne(T)},3e4);return()=>{clearInterval(ie)}},[Ne,e,D,T]),a.useEffect(()=>()=>{O.current?.close(),E.current&&(U(E.current,T),E.current=null)},[U,T]),a.useEffect(()=>{if(!e)return;const ie=Ae=>{Ae.key==="Escape"&&(Ae.preventDefault(),Xe())};return document.addEventListener("keydown",ie),()=>document.removeEventListener("keydown",ie)},[e,Xe]);const Ie=a.useCallback((ie,Ae)=>{m(he=>he.map(Re=>Re.id===ie?{...Re,...Ae}:Re)),A(!0)},[]),Ge=a.useCallback(()=>{m(ie=>[...ie,hA(ie.length+1)]),A(!0)},[]),se=a.useCallback(ie=>{m(Ae=>Ae.filter(he=>he.id!==ie).map(he=>({...he,dependsOn:he.dependsOn.filter(Re=>Re!==ie)}))),A(!0)},[]),ye=a.useCallback(ie=>Ae=>{F(ie),Ae.dataTransfer.setData("text/plain",ie),Ae.dataTransfer.effectAllowed="move"},[]),Z=a.useCallback(()=>{F(null),$(null),I(null)},[]),Te=a.useCallback(ie=>Ae=>{if(Ae.preventDefault(),ie===P)return;const he=Ae.currentTarget.getBoundingClientRect(),Re=he.top+he.height/2,Je=Ae.clientY<Re?"before":"after";$(ie),I(Je)},[P]),ze=a.useCallback(ie=>Ae=>{Ae.preventDefault();const he=Ae.dataTransfer.getData("text/plain");if(!he||he===ie){F(null),$(null),I(null);return}m(Re=>{const Je=Re.findIndex(Pe=>Pe.id===he),$e=Re.findIndex(Pe=>Pe.id===ie);if(Je===-1||$e===-1)return Re;const de=[...Re],[re]=de.splice(Je,1);let ue=$e;return _==="after"&&Je<$e&&ue--,_==="after"&&ue++,de.splice(ue,0,re),de}),A(!0),F(null),$(null),I(null)},[_]),be=a.useCallback(ie=>{const Ae=ie.currentTarget.getBoundingClientRect(),he=ie.clientX,Re=ie.clientY;(he<Ae.left||he>Ae.right||Re<Ae.top||Re>Ae.bottom)&&($(null),I(null))},[]),Me=a.useCallback((ie,Ae)=>{Ae<0||Ae>=d.length||(m(he=>{const Re=[...he],[Je]=Re.splice(ie,1);return Re.splice(Ae,0,Je),Re}),A(!0))},[d.length]),Be=a.useCallback(ie=>{J.current[ie+1]?.focus()},[]),lt=a.useCallback(async()=>{if(!(!D||ne)){C(null),u({type:"creating",sessionId:D});try{const ie=await kk(D,d,r,o);i(ie.tasks),Ke(),n()}catch(ie){C(ke(ie)||"Failed to create tasks"),u({type:"editing",sessionId:D})}}},[ne,n,i,r,o,Ke,D,d]),je=a.useCallback(async()=>{if(c.type!=="error")return;const ie=c.sessionId;C(null),k(!0),f(""),u({type:"generating",sessionId:ie}),Qe(ie);try{await bk(ie,o,T)}catch(Ae){let he=Ae;if((ke(Ae)||"").includes("not in an error state"))try{const Je=await oi(ie);if(!Je)throw new Error("Failed to refresh subtask session.");if(g(fa(Je.conversationHistory)),Je.status==="generating"||Je.status==="awaiting_input")f(Je.thinkingOutput??""),u({type:"generating",sessionId:Je.id}),O.current?.isConnected()||Qe(Je.id);else if(Je.status==="complete"){if(!Je.result)throw new Error("Subtask session is complete but has no result.");bl(o);const $e=JSON.parse(Je.result);m($e),u({type:"editing",sessionId:Je.id}),A(!1)}else Je.status==="error"&&u({type:"error",sessionId:Je.id,errorMessage:Je.error??"Retry failed. Please try again."});y(!1);return}catch(Je){he=Je}O.current?.close(),O.current=null,u({type:"error",sessionId:ie,errorMessage:ke(he)||"Retry failed. Please try again."}),y(!1)}finally{k(!1)}},[Qe,o,T,c]);return e?t.jsx("div",{className:"modal-overlay open",onClick:ie=>ie.target===ie.currentTarget&&void Xe(),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(Po,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Subtask Breakdown"})]}),t.jsxs("div",{className:"modal-header-actions",children:[xe&&t.jsx("button",{className:"modal-send-to-background",onClick:Ze,title:"Send to background","aria-label":"Send to background",children:t.jsx(yr,{size:16})}),t.jsx("button",{className:"modal-close",onClick:()=>void Xe(),"aria-label":"Close",children:t.jsx(Ot,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[M&&t.jsx("div",{className:"form-error planning-error",children:M}),b&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Ee&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),c.type==="initial"&&t.jsx("div",{className:"planning-initial",children:t.jsxs("div",{className:"planning-view-scroll",children:[t.jsx("p",{className:"text-muted",children:"Preparing to break this task into subtasks."}),t.jsx("pre",{className:"planning-thinking-output",children:R})]})}),c.type==="generating"&&t.jsxs("div",{className:"planning-loading",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Es,{entries:h,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsx(ot,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:"AI is generating subtasks..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>v(!x),type:"button",children:x?"Hide thinking":"Show thinking"}),x&&p&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:p})})]})]}),c.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Es,{entries:h,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:c.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void je(),disabled:S,children:[S?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Nn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:S?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:()=>void Xe(),disabled:S,children:"Cancel"})]})]})]})}),(c.type==="editing"||c.type==="creating")&&t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Es,{entries:h}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(dn,{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:[d.map((ie,Ae)=>{const he=P===ie.id,Re=W===ie.id,Je=["task-detail-section","subtask-item",he?"subtask-item-dragging":"",Re?"subtask-item-drop-target":"",Re&&_==="before"?"subtask-item-drop-before":"",Re&&_==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:Je,"data-testid":`subtask-item-${Ae}`,draggable:c.type!=="creating",onDragStart:ye(ie.id),onDragEnd:Z,onDragOver:Te(ie.id),onDrop:ze(ie.id),onDragLeave:be,children:[t.jsxs("div",{className:"detail-title-row subtask-item-header subtask-item-header--between",children:[t.jsxs("div",{className:"subtask-drag-handle",title:"Drag to reorder",children:[t.jsx(Jc,{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:()=>Me(Ae,Ae-1),disabled:c.type==="creating"||Ae===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(Li,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Me(Ae,Ae+1),disabled:c.type==="creating"||Ae===d.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(xr,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>se(ie.id),disabled:c.type==="creating",children:[t.jsx(Xt,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:$e=>{J.current[Ae]=$e},value:ie.title,onChange:$e=>Ie(ie.id,{title:$e.target.value}),onKeyDown:$e=>{$e.key==="Enter"&&($e.preventDefault(),Be(Ae))},disabled:c.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:8,value:ie.description,onChange:$e=>Ie(ie.id,{description:$e.target.value}),disabled:c.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:$e=>Ie(ie.id,{suggestedSize:$e.target.value}),disabled:c.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:[d.slice(0,Ae).filter($e=>$e.id!==ie.id).map($e=>{const de=ie.dependsOn.includes($e.id);return t.jsxs("label",{className:`planning-dep-chip ${de?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:de,onChange:()=>{const re=de?ie.dependsOn.filter(ue=>ue!==$e.id):[...ie.dependsOn,$e.id];Ie(ie.id,{dependsOn:re})},disabled:c.type==="creating"}),t.jsx("span",{className:"planning-dep-id",children:$e.id}),t.jsx("span",{className:"planning-dep-title",children:$e.title||"Untitled"})]},$e.id)}),Ae===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),Ae>0&&d.slice(0,Ae).filter($e=>$e.id!==ie.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},ie.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:Ge,disabled:c.type==="creating",children:[t.jsx(Zt,{size:16,className:"icon-mr-6"})," Add subtask"]}),Qm(d)&&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 Xe(),disabled:c.type==="creating",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:()=>void lt(),disabled:c.type==="creating"||ne,children:c.type==="creating"?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]}),w&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Io,{size:16}),t.jsx("span",{children:Fe?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Fe&&t.jsx("button",{type:"button",onClick:()=>{q()},disabled:G,className:"btn btn-primary session-lock-take-control",children:G?"Taking control...":"Take Control"})]})})]})]})}):null}const fA=5,gA=1e3,xA=45e3;function no(){return{scrollback:null,connected:null,data:[]}}function bA(e,n){const[s,i]=a.useState("disconnected"),r=a.useRef(0),o=a.useRef(e),l=a.useRef(n),c=o.current!==e||l.current!==n;c&&(o.current=e,l.current=n,r.current++);const u=a.useRef(null),d=a.useRef(0),m=a.useRef(null),h=a.useRef(null),g=a.useRef(!1),p=a.useRef(new Set),f=a.useRef(new Set),x=a.useRef(new Set),v=a.useRef(new Set),b=a.useRef(new Set),y=a.useRef(no()),S=a.useCallback($=>{p.current.add($);const _=y.current;return _.data.length>0&&(_.data.forEach(I=>$(I)),_.data=[]),()=>p.current.delete($)},[]),k=a.useCallback($=>(f.current.add($),()=>f.current.delete($)),[]),R=a.useCallback($=>{x.current.add($);const _=y.current;return _.connected&&($(_.connected),_.connected=null),()=>x.current.delete($)},[]),N=a.useCallback($=>{v.current.add($);const _=y.current;return _.scrollback&&($(_.scrollback),_.scrollback=null),()=>v.current.delete($)},[]),M=a.useCallback($=>(b.current.add($),()=>b.current.delete($)),[]),C=a.useCallback($=>{const _=u.current;_?.readyState===WebSocket.OPEN&&_.send(JSON.stringify({type:"input",data:$}))},[]),z=a.useCallback(($,_)=>{const I=u.current;I?.readyState===WebSocket.OPEN&&I.send(JSON.stringify({type:"resize",cols:$,rows:_}))},[]),A=a.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),u.current&&(u.current.onopen=null,u.current.onmessage=null,u.current.onclose=null,u.current.onerror=null,u.current.close(),u.current=null),y.current=no()},[]),P=a.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),u.current&&(g.current=!0,u.current.close(),u.current=null),y.current=no()},[]),F=a.useCallback(()=>{if(!e){i("disconnected");return}if(u.current?.readyState===WebSocket.OPEN)return;u.current&&(g.current=!0,u.current.close()),g.current=!1,i("connecting");const $=r.current;let I=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(e)}`;n&&(I+=`&projectId=${encodeURIComponent(n)}`);const O=new WebSocket(Qs(I));u.current=O,O.onopen=()=>{if(r.current!==$){O.close();return}y.current=no(),i("connected"),d.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===$&&O.readyState===WebSocket.OPEN&&O.send(JSON.stringify({type:"ping"}))},xA)},O.onmessage=J=>{if(r.current===$)try{const Q=JSON.parse(J.data),E=y.current;switch(Q.type){case"data":Q.data&&(p.current.size===0&&E.data.push(Q.data),p.current.forEach(D=>D(Q.data)));break;case"scrollback":Q.data&&(E.scrollback=Q.data,v.current.forEach(D=>D(Q.data)));break;case"connected":Q.shell&&Q.cwd&&(E.connected={shell:Q.shell,cwd:Q.cwd},x.current.forEach(D=>D({shell:Q.shell,cwd:Q.cwd})));break;case"exit":Q.exitCode!==void 0&&f.current.forEach(D=>D(Q.exitCode));break;case"ping":O.readyState===WebSocket.OPEN&&O.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},O.onclose=J=>{if(r.current!==$)return;if(u.current=null,h.current&&(clearInterval(h.current),h.current=null),g.current){i("disconnected");return}if(J.code===4e3||J.code===4004){i("disconnected"),J.code===4004&&b.current.forEach(D=>D());return}if(d.current++,d.current>fA){i("disconnected");return}const Q=gA*Math.pow(2,d.current-1);i("reconnecting");const E=r.current;m.current=setTimeout(()=>{r.current===E&&(g.current||F())},Math.min(Q,16e3))},O.onerror=()=>{}},[e,n]),W=a.useCallback(()=>{d.current=0,P(),F()},[P,F]);return a.useEffect(()=>(c&&(A(),d.current=0,i("disconnected")),e?F():i("disconnected"),P),[e,n,c,F,P,A]),{connectionStatus:s,sendInput:C,resize:z,onData:S,onExit:k,onConnect:R,onScrollback:N,reconnect:W,onSessionInvalid:M}}const Vf="kb-terminal-tabs",vA=15e3,yA=15e3;function Xm(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function Zm(e){if(typeof window>"u")return[];try{const n=Dn(Vf,e);if(n)return JSON.parse(n)}catch{}return[]}function Yl(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function eh(e,n,s){let i;const r=new Promise((o,l)=>{i=setTimeout(()=>l(new Error(`${s} timed out after ${n}ms`)),n)});return Promise.race([e,r]).finally(()=>clearTimeout(i))}function kA(e){const[n,s]=a.useState(()=>Zm(e)),[i,r]=a.useState(!1),[o,l]=a.useState(!0),[c,u]=a.useState(null),[d,m]=a.useState(0),h=a.useRef(0);a.useEffect(()=>{h.current+=1,s(Zm(e)),r(!1),l(!0),u(null)},[e]),a.useEffect(()=>{try{os(Vf,JSON.stringify(n),e)}catch{}},[e,n]),a.useEffect(()=>{let R=!1;const N=h.current;return(async()=>{if(!R)try{const C=await eh(py(e),vA,"listTerminalSessions");if(R||N!==h.current)return;const z=new Set(C.map(A=>A.id));l(!0),s(A=>{if(R||N!==h.current)return A;const F=A.map(_=>({..._,_verified:z.has(_.sessionId)})).filter(_=>_._verified);if(F.length===0)return[];const W=F.map(({_verified:_,...I})=>I);return W.find(_=>_.isActive)?W:W.map((_,I)=>({..._,isActive:I===0}))}),r(!0)}catch(C){if(R||N!==h.current)return;const z=Yl(C);z||console.warn("Failed to validate terminal sessions with server:",C),l(!z),r(!0)}})(),()=>{R=!0}},[e]),a.useEffect(()=>{if(n.length===0&&i&&o){const R=h.current,N=setTimeout(()=>{eh(Fr(void 0,void 0,void 0,e),yA,"createTerminalSession").then(M=>{if(R!==h.current)return;const C={id:Xm(),sessionId:M.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(z=>z.length>0?z:[...z.map(P=>({...P,isActive:!1})),C]),u(null)}).catch(M=>{if(R!==h.current)return;Yl(M)||console.error(M);const C=M instanceof Error?M.message:typeof M=="string"?M:"Failed to create terminal session";u(C)})},0);return()=>clearTimeout(N)}},[i,o,n.length,d]);const g=a.useCallback(async()=>{const R=await Fr(void 0,void 0,void 0,e),N={id:Xm(),sessionId:R.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(M=>[...M.map(z=>({...z,isActive:!1})),N]),N},[n.length]),p=a.useCallback(async()=>g(),[g]),f=a.useCallback(R=>{s(N=>{const M=N.find(P=>P.id===R);if(!M)return N;Dd(M.sessionId,e).catch(P=>{console.warn(`Failed to kill terminal session ${M.sessionId}:`,P)});const C=N.findIndex(P=>P.id===R),z=M.isActive,A=N.filter(P=>P.id!==R);if(A.length===0)return[];if(z){const P=Math.min(C,A.length-1);return A.map((F,W)=>({...F,isActive:W===P}))}return A})},[]),x=a.useCallback(R=>{s(N=>{let M=!1;const C=N.map(z=>z.id===R?(M=!0,{...z,isActive:!0}):{...z,isActive:!1});return M?C:N})},[]),v=a.useCallback((R,N)=>{s(M=>M.map(C=>C.id===R?{...C,title:N}:C))},[]),b=a.useCallback(async()=>{s(M=>{const C=M.find(z=>z.isActive);return C&&Dd(C.sessionId,e).catch(z=>{console.warn(`Failed to kill old session ${C.sessionId}:`,z)}),M});const R=n.find(M=>M.isActive);if(!R)return;const N=await Fr(void 0,void 0,void 0,e);s(M=>M.map(C=>C.id===R.id?{...C,sessionId:N.sessionId}:C))},[n]),y=a.useCallback(async()=>{const R=n.find(N=>N.isActive);if(R)try{const N=await Fr(void 0,void 0,void 0,e);s(M=>M.map(C=>C.id===R.id?{...C,sessionId:N.sessionId}:C)),u(null)}catch(N){Yl(N)||console.error(N);const M=N instanceof Error?N.message:typeof N=="string"?N:"Failed to create terminal session";u(M)}},[n]),S=n.find(R=>R.isActive)??null,k=a.useCallback(()=>{u(null),h.current+=1,m(R=>R+1)},[]);return{tabs:n,activeTab:S,isReady:i,bootstrapError:c,createTab:p,closeTab:f,setActiveTab:x,updateTabTitle:v,restartActiveTab:b,retryBootstrap:k,replaceActiveTabSession:y}}const jA=1e4,wA=[500,1500,3e3],Wf="kb-terminal-font-size",tr=14,NA=8,SA=32;function CA(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 EA(e){return`\x1B${e}`}const _A=[{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 nr(e){return Math.min(SA,Math.max(NA,e))}function MA(){if(typeof window>"u")return tr;try{const e=window.localStorage.getItem(Wf);if(!e)return tr;const n=Number.parseInt(e,10);return Number.isFinite(n)?nr(n):tr}catch{return tr}}function AA(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 RA(e){return new Promise(n=>setTimeout(n,e))}async function TA(e,n=wA){let s;for(let i=0;i<=n.length;i+=1)try{return await e()}catch(r){if(!AA(r))throw r;s===void 0&&(s=r);const o=n[i];if(o===void 0)throw s??r;const l=r instanceof Error?r.message:String(r);console.warn(`[TerminalModal] Dynamic xterm import failed (attempt ${i+1}/${n.length+1}). Retrying in ${o}ms...`,l),await RA(o)}throw s??new Error("Dynamic import failed")}function th(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}function PA(){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 i=IA()-e.offsetTop-e.height;return i>=30&&i>80?i:0}let Ql=null;function IA(){return Ql===null&&(Ql=window.innerHeight),Ql}function $A({isOpen:e,onClose:n,initialCommand:s,projectId:i}){const[r,o]=a.useState(null),[l,c]=a.useState(null),[u,d]=a.useState(!1),[m,h]=a.useState(null),[g,p]=a.useState(0),[f,x]=a.useState(0),[v,b]=a.useState(null),[y,S]=a.useState(()=>MA()),[k,R]=a.useState(!1),[N,M]=a.useState(null),C=a.useRef(null),z=a.useRef(null),A=a.useRef(!1);Xs(z,e,"fusion:terminal-modal-size");const P=a.useRef(null),F=a.useRef(null),W=a.useRef(!1),$=a.useRef(!1),_=a.useRef(null),I=a.useRef(()=>{}),O=a.useRef(null),J=a.useRef(0),Q=a.useRef(y),E=a.useRef(null),D=a.useRef(i);J.current=f,Q.current=y;const T=a.useCallback(he=>{if(he&&$.current!==he)return;const Re=F.current,Je=P.current,$e=_.current;if(!(!Re||!Je)&&!(he&&$.current!==he))try{Re.fit(),$e&&$e(Je.cols,Je.rows)}catch{}},[]);a.useEffect(()=>{e&&p(he=>he+1)},[e]),a.useEffect(()=>{if(!e||!th())return;const he=window.visualViewport;if(!he)return;const Re=()=>{const Je=PA();x(Je),b(he.height),Je>0&&z.current?.scrollIntoView&&z.current.scrollIntoView({block:"end",behavior:"smooth"}),E.current!==null&&(cancelAnimationFrame(E.current),E.current=null);const $e=typeof $.current=="string"?$.current:void 0;E.current=requestAnimationFrame(()=>{E.current=null,T($e)})};return Re(),he.addEventListener("resize",Re),he.addEventListener("scroll",Re),()=>{he.removeEventListener("resize",Re),he.removeEventListener("scroll",Re),E.current!==null&&(cancelAnimationFrame(E.current),E.current=null),x(0),b(null)}},[T,e]),a.useEffect(()=>{if(!e)return;const he=z.current;if(!he||typeof ResizeObserver>"u")return;let Re=null;const Je=new ResizeObserver(()=>{Re!==null&&cancelAnimationFrame(Re),Re=requestAnimationFrame(()=>{Re=null;const $e=typeof $.current=="string"?$.current:void 0;T($e)})});return Je.observe(he),()=>{Je.disconnect(),Re!==null&&cancelAnimationFrame(Re)}},[T,e]);const{tabs:w,activeTab:q,isReady:G,bootstrapError:me,createTab:ce,closeTab:ae,setActiveTab:pe,updateTabTitle:U,restartActiveTab:Ne,retryBootstrap:ne,replaceActiveTabSession:xe}=kA(i),{connectionStatus:le,sendInput:ve,resize:ee,onData:Ee,onConnect:Fe,onExit:Ke,onScrollback:Ze,reconnect:Xe,onSessionInvalid:Qe}=bA(q?.sessionId??null,i);_.current=ee,I.current=ve,a.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Wf,String(y))}catch{}},[y]);const it=a.useCallback(()=>{const he=P.current;if(he)try{F.current?.fit(),ee(he.cols,he.rows)}catch{}},[ee]);a.useEffect(()=>{if(!e||!G)return;const he=q?.sessionId;if(!he)return;const Re=D.current!==i;if(Re&&(D.current=i),$.current===he&&P.current&&!Re)return;P.current&&($.current!==he||Re)&&(P.current.dispose(),P.current=null,F.current=null,$.current=!1,O.current&&(window.removeEventListener("resize",O.current),O.current=null),d(!1),h(null));let Je=!0,$e;return(async()=>{const re=TA(()=>Promise.all([nn(()=>import("./vendor-xterm-DzcZoU0P.js").then(fe=>fe.x),__vite__mapDeps([0,1,2])),nn(()=>import("./addon-fit-C7jRorKK.js").then(fe=>fe.a),__vite__mapDeps([3,1])),nn(()=>import("./addon-web-links-CkJwd4cQ.js").then(fe=>fe.a),__vite__mapDeps([4,1]))])),ue=new Promise((fe,tt)=>{$e=setTimeout(()=>{tt(new Error("xterm initialization timed out"))},jA)});let Pe,Se;try{const[{Terminal:fe},{FitAddon:tt},{WebLinksAddon:ut}]=await Promise.race([re,ue]);if(!Je||!C.current||P.current)return;Pe=new fe({cursorBlink:!0,cursorStyle:"block",fontSize:Q.current,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',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}),Se=new tt,Pe.loadAddon(Se);const vt=new ut;if(Pe.loadAddon(vt),!th())try{const{WebglAddon:wt}=await nn(async()=>{const{WebglAddon:yt}=await import("./addon-webgl-BjvOw43o.js").then(Et=>Et.a);return{WebglAddon:yt}},__vite__mapDeps([5,1])),Mt=new wt;Mt.onContextLoss(()=>{Mt.dispose()}),Pe.loadAddon(Mt)}catch{}Pe.open(C.current),$e&&clearTimeout($e);const gt=C.current?.querySelector(".xterm-helper-textarea");if(gt&>.focus(),C.current)try{C.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{Se.fit();const wt=C.current?.querySelector(".xterm-helper-textarea");wt&&wt.focus()},50),P.current=Pe,F.current=Se,$.current=he,J.current>0&&(E.current!==null&&(cancelAnimationFrame(E.current),E.current=null),E.current=requestAnimationFrame(()=>{E.current=null,T(he)})),Pe.onData(wt=>{$.current===he&&I.current(wt)});const dt=()=>{if($.current===he&&F.current&&P.current)try{F.current.fit();const{cols:wt,rows:Mt}=P.current;_.current?.(wt,Mt)}catch{}};window.addEventListener("resize",dt),O.current&&window.removeEventListener("resize",O.current),O.current=dt,d(!0),h(null)}catch(fe){if($e&&clearTimeout($e),!Je)return;const tt=fe instanceof Error?fe.message:"xterm initialization failed";h(tt)}})(),()=>{Je=!1,$e&&clearTimeout($e)}},[T,e,G,q?.sessionId,i]),a.useEffect(()=>{e||(P.current&&(P.current.dispose(),P.current=null),F.current=null,$.current=!1,O.current&&(window.removeEventListener("resize",O.current),O.current=null),d(!1),h(null),W.current=!1,o(null),c(null),R(!1),M(null))},[e]),a.useEffect(()=>{if(!u||!P.current||!q)return;const he=q.sessionId,Re=ue=>{$.current===he&&P.current?.write(ue)},Je=Ee(ue=>{Re(ue)}),$e=Ze(ue=>{Re(ue)}),de=Fe(ue=>{U(q.id,ue.shell.split("/").pop()||ue.shell)}),re=Ke(ue=>{$.current===he&&(c(ue),P.current?.write(`\r
|
|
653
|
+
\x1B[33m[Process exited with code ${ue}]\x1B[0m\r
|
|
654
|
+
`))});return()=>{Je(),$e(),de(),re()}},[u,q?.sessionId,q?.id,q,le,Ee,Ze,Fe,Ke,U]),a.useEffect(()=>{le==="connected"&&s&&W.current!==s&&q&&(W.current=s,setTimeout(()=>{ve(s+`
|
|
655
|
+
`)},500))},[le,s,ve,q,g]),a.useEffect(()=>{if(!u||!P.current)return;P.current.options.fontSize=y,E.current!==null&&(cancelAnimationFrame(E.current),E.current=null);const he=requestAnimationFrame(()=>{E.current=null,it()});return E.current=he,()=>{E.current===he&&(cancelAnimationFrame(he),E.current=null)}},[y,u,it]),a.useEffect(()=>{if(!e)return;const he=Re=>{if(!(!Re.ctrlKey&&!Re.metaKey)){if(Re.code==="Equal"||Re.code==="NumpadAdd"){Re.preventDefault(),S(Je=>nr(Je+1));return}if(Re.code==="Minus"||Re.code==="NumpadSubtract"){Re.preventDefault(),S(Je=>nr(Je-1));return}if(Re.code==="Digit0"||Re.code==="Numpad0"){Re.preventDefault(),S(tr);return}}};return window.addEventListener("keydown",he),()=>window.removeEventListener("keydown",he)},[e,it]),a.useEffect(()=>{if(!e)return;const he=Re=>{Re.key==="Escape"&&n()};return document.addEventListener("keydown",he),()=>document.removeEventListener("keydown",he)},[e,n]),a.useEffect(()=>{le==="connected"&&P.current&&setTimeout(()=>{if(!P.current||!C.current)return;const he=C.current.querySelector(".xterm-helper-textarea");he&&he.focus();try{C.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[le]);const Ie=a.useCallback(()=>{if(!C.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;P.current?.focus();const Re=C.current.querySelector(".xterm-helper-textarea");if(!Re)return;Re.autocapitalize="off",Re.autocomplete="off",Re.autocorrect="off",Re.spellcheck=!1,Re.setAttribute("inputmode","text");try{Re.focus({preventScroll:!0})}catch{Re.focus()}const Je=Re.value.length;Re.setSelectionRange(Je,Je)},[]);a.useEffect(()=>Qe(()=>{P.current?.clear(),c(null),W.current=!1,P.current&&(P.current.dispose(),P.current=null),F.current=null,$.current=!1,O.current&&(window.removeEventListener("resize",O.current),O.current=null),d(!1),h(null),xe().catch(Re=>{console.error("Failed to replace invalid terminal session:",Re)})}),[Qe,xe]);const Ge=a.useCallback(he=>{he.target===he.currentTarget&&(A.current=!0)},[]),se=a.useCallback(he=>{A.current&&he.target===he.currentTarget&&n(),A.current=!1},[n]),ye=a.useCallback(()=>{P.current?.clear()},[]),Z=a.useCallback(async()=>{P.current?.clear(),c(null),W.current=!1;try{await Ne()}catch(he){o(ke(he)||"Failed to restart terminal session")}},[Ne]),Te=a.useCallback(()=>{P.current&&(P.current.dispose(),P.current=null),F.current=null,$.current=!1,O.current&&(window.removeEventListener("resize",O.current),O.current=null),h(null),d(!1)},[]),ze=a.useCallback(()=>{window.location.reload()},[]),be=a.useCallback(()=>{S(he=>nr(he+1))},[]),Me=a.useCallback(()=>{S(he=>nr(he-1))},[]),Be=a.useCallback(he=>{M(Re=>Re===he?null:he)},[]),lt=a.useCallback(he=>{if(N==="ctrl"){ve(CA(he)),M(null);return}if(N==="alt"){ve(EA(he)),M(null);return}ve(he)},[ve,N]),je=a.useCallback(he=>{ve(he),M(null)},[ve]);if(!e)return null;const ie=()=>{switch(le){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}},Ae=!G||!q&&!me;return t.jsx("div",{className:"modal-overlay open",onMouseDown:Ge,onMouseUp:se,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:f>0?{"--overlay-padding-top":"0px"}:void 0,children:t.jsxs("div",{ref:z,className:"modal terminal-modal","data-testid":"terminal-modal",style:f>0?{"--keyboard-overlap":`${f}px`,"--vv-height":v?`${v}px`:void 0}:void 0,children:[t.jsxs("div",{className:"terminal-header",children:[t.jsxs("div",{className:"terminal-tabs","data-testid":"terminal-tabs",children:[w.map(he=>t.jsxs("div",{className:`terminal-tab ${he.isActive?"terminal-tab--active":""}`,onClick:()=>pe(he.id),title:he.title,role:"tab","aria-selected":he.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:he.title}),w.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:Re=>{Re.stopPropagation(),ae(he.id)},title:"Close tab",children:"×"})]},he.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:ce,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(ri,{size:16}),ie()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[le==="disconnected"&&q&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:Xe,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(Nn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:Z,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(Nn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:ye,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[t.jsx(Xt,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:()=>R(he=>!he),"data-testid":"terminal-shortcut-toggle",title:"Shortcuts","aria-pressed":k,children:[t.jsx(Hx,{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(Ot,{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:[Ae&&!me&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),me&&!q&&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: ",me]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:ne,"data-testid":"terminal-retry-btn",children:[t.jsx(Nn,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:ze,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(Nn,{size:14}),"Refresh page"]})]})]})}),m&&q&&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:Te,"data-testid":"terminal-reinit-btn",children:[t.jsx(Nn,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:ze,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(Nn,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:C,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:Ie,onTouchStart:Ie},q?.sessionId)]}),k&&t.jsxs("div",{className:"terminal-shortcut-panel","data-testid":"terminal-shortcut-panel",children:[t.jsxs("div",{className:"terminal-shortcut-modifier-row",children:[t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${N==="ctrl"?"is-active":""}`,"data-testid":"terminal-modifier-ctrl",onClick:()=>Be("ctrl"),"aria-pressed":N==="ctrl",children:"Ctrl"}),t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${N==="alt"?"is-active":""}`,"data-testid":"terminal-modifier-alt",onClick:()=>Be("alt"),"aria-pressed":N==="alt",children:"Alt"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>je("\x1B"),children:"ESC"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>je(" "),children:"Tab"})]}),_A.map(he=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>lt(he.key),title:he.description,children:he.label},he.label))]}),t.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[t.jsxs("span",{className:`terminal-connection-status ${le}`,children:[le==="connected"&&"Connected",le==="connecting"&&"Connecting...",le==="reconnecting"&&"Reconnecting...",le==="disconnected"&&"Disconnected"]}),l!==null&&t.jsxs("span",{className:"terminal-exit-code","data-testid":"terminal-exit-code",children:["Exit: ",l]}),t.jsxs("span",{className:"terminal-font-size-controls",children:[t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:Me,"data-testid":"terminal-font-size-decrease","aria-label":"Decrease terminal font size",children:t.jsx(lb,{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:be,"data-testid":"terminal-font-size-increase","aria-label":"Increase terminal font size",children:t.jsx(Zt,{size:14})})]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • ⌨ Shortcuts panel • Esc close"})]})]})})}const Va={name:"",command:""};function nh(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function DA(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function LA({isOpen:e,onClose:n,addToast:s,projectId:i,onRunScript:r}){const[o,l]=a.useState({}),[c,u]=a.useState(!0),[d,m]=a.useState(!1),[h,g]=a.useState(null),[p,f]=a.useState(Va),[x,v]=a.useState(!1),[b,y]=a.useState(null),[S,k]=a.useState(null),R=wi(n),N=a.useCallback(async()=>{try{u(!0);const I=await hr(i);l(I)}catch(I){s(ke(I)||"Failed to load scripts","error")}finally{u(!1)}},[s,i]);a.useEffect(()=>{e&&N()},[e,N]);const M=a.useCallback(()=>{m(!0),g(null),f(Va),k(null)},[]),C=a.useCallback((I,O)=>{g(I),m(!1),f({name:I,command:O}),k(null)},[]),z=a.useCallback(()=>{g(null),m(!1),f(Va),k(null)},[]),A=a.useCallback(I=>{f(O=>({...O,name:I})),I&&!nh(I)?k("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):k(null)},[]),P=a.useCallback(async()=>{const I=p.name.trim(),O=p.command.trim();if(!I){s("Script name is required","error");return}if(!nh(I)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!O){s("Script command is required","error");return}v(!0);try{await fk(I,O,i),s(h?"Script updated":"Script created","success"),g(null),m(!1),f(Va),k(null),await N()}catch(J){const Q=ke(J);Q?.includes("already exists")?s("A script with this name already exists","error"):s(Q||"Failed to save script","error")}finally{v(!1)}},[p,h,s,N,i]),F=a.useCallback(async I=>{try{await gk(I,i),s("Script deleted","success"),y(null),h===I&&(g(null),f(Va)),await N()}catch(O){s(ke(O)||"Failed to delete script","error")}},[h,s,N,i]),W=a.useCallback((I,O)=>{r&&r(I,O)},[r]);if(!e)return null;const $=d||h!==null,_=Object.entries(o).map(([I,O])=>({name:I,command:O}));return t.jsx("div",{className:"modal-overlay open",...R,"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(ri,{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(ot,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),"Loading scripts..."]}):$?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:I=>A(I.target.value),placeholder:"e.g., build, test, lint",disabled:x||h!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:S?"var(--color-error)":void 0}}),S&&t.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:S}),t.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",marginTop:"4px"},children:"Letters, numbers, hyphens, and underscores only"})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"script-command",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Command"}),t.jsx("textarea",{id:"script-command",className:"input",value:p.command,onChange:I=>f(O=>({...O,command:I.target.value})),placeholder:"e.g., npm run build",rows:3,disabled:x,"data-testid":"script-command-input",style:{width:"100%",resize:"vertical",fontFamily:"monospace"}})]}),t.jsxs("div",{className:"scripts-modal-form-actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end"},children:[t.jsx("button",{className:"btn btn-secondary",onClick:z,disabled:x,"data-testid":"script-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:P,disabled:x||!!S,"data-testid":"script-save-btn",children:x?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:14,className:"spin",style:{marginRight:"6px"}}),"Saving..."]}):h?"Update":"Create"})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"scripts-modal-list-header",style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[t.jsx("div",{style:{fontSize:"13px",color:"var(--text-muted)"},children:_.length===0?"No scripts defined":`${_.length} script${_.length===1?"":"s"}`}),t.jsxs("button",{className:"btn btn-primary",onClick:M,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx(Zt,{size:14}),"Add Script"]})]}),_.length===0?t.jsxs("div",{style:{textAlign:"center",padding:"32px",color:"var(--text-muted)",fontSize:"14px",border:"1px dashed var(--border)",borderRadius:"8px"},"data-testid":"empty-state",children:[t.jsx(ri,{size:32,style:{margin:"0 auto 12px",opacity:.5}}),t.jsx("div",{children:"No scripts defined yet."}),t.jsx("div",{style:{marginTop:"4px",fontSize:"12px"},children:"Add scripts to quickly run common commands from the dashboard."})]}):t.jsx("div",{className:"scripts-modal-list",style:{display:"flex",flexDirection:"column",gap:"8px"},children:_.map(I=>t.jsx("div",{className:"script-card","data-testid":`script-${I.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:I.name})}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:I.command,children:DA(I.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:()=>W(I.name,I.command),title:"Run script","aria-label":`Run ${I.name}`,"data-testid":`run-script-${I.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[t.jsx(xn,{size:12}),"Run"]}),t.jsx("button",{className:"btn-icon",onClick:()=>C(I.name,I.command),title:"Edit","aria-label":`Edit ${I.name}`,"data-testid":`edit-script-${I.name}`,children:t.jsx(Zt,{size:14,style:{transform:"rotate(45deg)"}})}),b===I.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>F(I.name),title:"Confirm delete","aria-label":`Confirm delete ${I.name}`,"data-testid":`confirm-delete-script-${I.name}`,style:{color:"var(--color-error)"},children:t.jsx(Xt,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>y(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${I.name}`,children:t.jsx(Ot,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>y(I.name),title:"Delete","aria-label":`Delete ${I.name}`,"data-testid":`delete-script-${I.name}`,children:t.jsx(Xt,{size:14})})]})]})},I.name))})]})})]})})}function zA(e,n,s){const[i,r]=a.useState([]),[o,l]=a.useState("."),[c,u]=a.useState(!1),[d,m]=a.useState(null),[h,g]=a.useState(0),p=a.useCallback(()=>{g(x=>x+1)},[]),f=a.useCallback(x=>{l(x),m(null)},[]);return a.useEffect(()=>{l("."),m(null),r([])},[e]),a.useEffect(()=>{if(!n||!e)return;let x=!1;async function v(){u(!0),m(null);try{const b=await Ty(e,o==="."?void 0:o,s);x||r(b.entries)}catch(b){x||(m(ke(b)||"Failed to load files"),r([]))}finally{x||u(!1)}}return v(),()=>{x=!0}},[e,o,n,h,s]),{entries:i,currentPath:o,setPath:f,loading:c,error:d,refresh:p}}function FA(e,n,s,i){const[r,o]=a.useState(""),[l,c]=a.useState(""),[u,d]=a.useState(null),[m,h]=a.useState(!1),[g,p]=a.useState(!1),[f,x]=a.useState(null),v=a.useCallback(S=>{o(S),x(null)},[]);a.useEffect(()=>{if(!e||!n){o(""),c(""),d(null),x(null);return}let S=!1;async function k(){h(!0),x(null);try{const R=await Py(e,n,i);S||(o(R.content),c(R.content),d(R.mtime))}catch(R){S||(x(ke(R)||"Failed to load file"),o(""),c(""),d(null))}finally{S||h(!1)}}return k(),()=>{S=!0}},[e,n,s,i]);const b=r!==l,y=a.useCallback(async()=>{if(!(!e||!n||!b)){p(!0),x(null);try{const S=await Iy(e,n,r,i);c(r),d(S.mtime)}catch(S){throw x(ke(S)||"Failed to save file"),S}finally{p(!1)}}},[e,n,r,b,i]);return{content:r,setContent:v,originalContent:l,loading:m,saving:g,error:f,save:y,hasChanges:b,mtime:u}}const OA=1e4;function UA(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function BA(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function HA(e){const[n,s]=a.useState("Project Root"),[i,r]=a.useState([]),[o,l]=a.useState(!0),[c,u]=a.useState(null);return a.useEffect(()=>{let d=!1;async function m(){try{const g=await Ry(e);if(d)return;s(UA(g.project)),r(g.tasks.map(BA)),u(null)}catch(g){d||u(ke(g)||"Failed to load workspaces")}finally{d||l(!1)}}m();const h=window.setInterval(()=>{m()},OA);return()=>{d=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:i,loading:o,error:c}}function qA(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function VA(e){return e?new Date(e).toLocaleDateString():""}function sh(e,n){return e==="."?n:`${e}/${n}`}const Wa={visible:!1,x:0,y:0,entry:null,entryFullPath:""},Xl={type:null,entry:null,entryFullPath:""},WA=200,KA=500,ih=10;function GA({x:e,y:n,entry:s,onAction:i,onClose:r}){const o=a.useRef(null),[l,c]=a.useState({x:e,y:n});a.useEffect(()=>{const m=o.current;if(!m)return;const h=m.getBoundingClientRect(),g=window.visualViewport,p=g?.width&&g.width>0?g.width:window.innerWidth,f=g?.height&&g.height>0?g.height:window.innerHeight,x=g?.offsetLeft??0,v=g?.offsetTop??0,b=8;let y=e-x,S=n-v;y+h.width>p-b&&(y=p-b-h.width),S+h.height>f-b&&(S=f-b-h.height),y<b&&(y=b),S<b&&(S=b),c({x:y+x,y:S+v})},[e,n]),a.useEffect(()=>{const m=h=>{h.key==="Escape"&&r()};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[r]);const u=s.type==="directory",d=[{id:"copy",label:"Copy",icon:Fi,disabled:!1},{id:"move",label:"Move",icon:ub,disabled:!1},{id:"rename",label:"Rename",icon:Yn,disabled:!1},...u?[{id:"download-zip",label:"Download as ZIP",icon:Mo,disabled:!1}]:[{id:"download",label:"Download",icon:sx,disabled:!1}],{id:"divider",label:"",icon:Fi,disabled:!0},{id:"delete",label:"Delete",icon:Xt,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:d.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:()=>i(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 JA({type:e,entry:n,entryFullPath:s,onConfirm:i,onCancel:r,loading:o,error:l}){const c=a.useRef(null),u=e==="rename"?n.name:"",[d,m]=a.useState(u);a.useEffect(()=>{setTimeout(()=>c.current?.focus(),50)},[]),a.useEffect(()=>{if(e==="rename"&&c.current){const f=n.name.lastIndexOf(".");f>0?c.current.setSelectionRange(0,f):c.current.select()}},[e,n.name]);const h=f=>{f.key==="Enter"&&d.trim()&&i(d.trim()),f.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:f=>f.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:()=>i(""),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:f=>f.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:d,onChange:f=>m(f.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:()=>i(d.trim()),disabled:o||!d.trim(),children:o?`${p.confirm}ing...`:p.confirm})]})]})})}function YA({entries:e,currentPath:n,onSelectFile:s,onNavigate:i,loading:r,error:o,onRetry:l,workspace:c,onRefresh:u,projectId:d}){const[m,h]=a.useState(Wa),[g,p]=a.useState(Xl),[f,x]=a.useState(!1),[v,b]=a.useState(null),[y,S]=a.useState(!1),[k,R]=a.useState(null),N=a.useRef(null),M=a.useRef(null),C=a.useRef(null),z=a.useRef(!1),A=a.useCallback(()=>{N.current!==null&&(window.clearTimeout(N.current),N.current=null),M.current!==null&&(window.clearTimeout(M.current),M.current=null)},[]),P=a.useCallback(()=>{A(),C.current=null,S(!1),R(null)},[A]);a.useEffect(()=>()=>{A()},[A]);const F=a.useCallback((D,T,w,q)=>{h({visible:!0,x:D,y:T,entry:w,entryFullPath:q})},[]),W=a.useCallback((D,T,w)=>{if(D.touches.length!==1)return;const q=D.touches[0];q&&(P(),C.current={x:q.clientX,y:q.clientY},M.current=window.setTimeout(()=>{S(!0),R(w)},WA),N.current=window.setTimeout(()=>{const G=C.current;G&&(z.current=!0,S(!1),R(null),A(),F(G.x,G.y,T,w))},KA))},[P,A,F]),$=a.useCallback(D=>{const T=C.current,w=D.touches[0];!T||!w||(Math.abs(w.clientX-T.x)>ih||Math.abs(w.clientY-T.y)>ih)&&P()},[P]),_=a.useCallback(()=>{P()},[P]);a.useEffect(()=>{if(!m.visible)return;const D=document.querySelector(".file-browser-list"),T=()=>{z.current=!1,P(),h(Wa)};return D?.addEventListener("scroll",T),()=>D?.removeEventListener("scroll",T)},[P,m.visible]),a.useEffect(()=>{if(!m.visible)return;const D=T=>{T.key==="Escape"&&(z.current=!1,h(Wa))};return document.addEventListener("keydown",D),()=>document.removeEventListener("keydown",D)},[m.visible]);const I=a.useCallback((D,T)=>{D.preventDefault(),D.stopPropagation(),P(),z.current=!1,F(D.clientX,D.clientY,T,sh(n,T.name))},[P,n,F]),O=a.useCallback(D=>{if(!m.entry)return;z.current=!1;const T=m.entry,w=m.entryFullPath;if(h(Wa),D==="download"){if(!c)return;const q=tp(c,w,d);window.open(Qs(q),"_blank");return}if(D==="download-zip"){if(!c)return;const q=Oy(c,w,d);window.open(Qs(q),"_blank");return}p({type:D,entry:T,entryFullPath:w}),b(null)},[m,c,d]),J=a.useCallback(async D=>{if(!(!g.type||!g.entry||!c)){x(!0),b(null);try{switch(g.type){case"copy":await Dy(c,g.entryFullPath,D,d);break;case"move":await Ly(c,g.entryFullPath,D,d);break;case"rename":await Fy(c,g.entryFullPath,D,d);break;case"delete":await zy(c,g.entryFullPath,d);break}p(Xl),u?.()}catch(T){b(ke(T)||"Operation failed")}finally{x(!1)}}},[g,c,u,d]),Q=a.useCallback(()=>{p(Xl),b(null)},[]),E=a.useCallback((D,T)=>{if(z.current){z.current=!1;return}m.visible||(D.type==="directory"?i(T):s(T))},[m.visible,i,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(ot,{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:()=>{const D=n.split("/").filter(Boolean);D.pop(),i(D.length===0?".":D.join("/"))},children:[t.jsx(hn,{size:16,style:{transform:"rotate(-90deg)"}}),"Up one level"]}),t.jsx("span",{className:"file-browser-path",children:n==="."?"Root":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 T=sh(n,D.name),w=y&&k===T;return t.jsxs("div",{className:`file-node file-node--${D.type} ${w?"file-node--long-pressing":""}`,onClick:()=>E(D,T),onContextMenu:q=>I(q,D),onTouchStart:q=>W(q,D,T),onTouchMove:$,onTouchEnd:_,onTouchCancel:_,children:[t.jsx("div",{className:"file-node-icon",children:D.type==="directory"?t.jsx(In,{size:16}):t.jsx(Bh,{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:qA(D.size)}),D.mtime&&t.jsx("div",{className:"file-node-time",children:VA(D.mtime)})]},D.name)})}),m.visible&&m.entry&&t.jsx(GA,{x:m.x,y:m.y,entry:m.entry,onAction:O,onClose:()=>{z.current=!1,h(Wa)}}),g.type&&g.entry&&t.jsx(JA,{type:g.type,entry:g.entry,entryFullPath:g.entryFullPath,onConfirm:J,onCancel:Q,loading:f,error:v})]})}function QA(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function XA({content:e,onChange:n,readOnly:s,filePath:i}){const[r,o]=a.useState(!1),[l,c]=a.useState(!0),u=QA(i),d=u&&(s?!0:r),m=a.useCallback(()=>{o(!1)},[]),h=a.useCallback(()=>{o(!0)},[]),g=a.useCallback(()=>{c(p=>!p)},[]);return t.jsxs("div",{className:"file-editor-container",children:[u?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 ${d?"":"btn-primary"}`,onClick:m,disabled:!d,"aria-label":"Edit mode",children:[t.jsx(Uh,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${d?"btn-primary":""}`,onClick:h,disabled:d,"aria-label":"Preview mode",children:[t.jsx(da,{size:14}),"Preview"]})]}),!s&&t.jsx("button",{className:`btn btn-sm ${l?"btn-primary":""}`,onClick:g,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(ho,{size:14})})]}):!s&&t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsx("div",{className:"file-editor-mode-toggle"}),t.jsx("button",{className:`btn btn-sm ${l?"btn-primary":""}`,onClick:g,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(ho,{size:14})})]}),d?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(ci,{remarkPlugins:[di],children:e})}):t.jsx("textarea",{className:`file-editor-textarea ${l?"file-editor-textarea--wrap":""}`,value:e,onChange:p=>n(p.target.value),readOnly:s,spellCheck:!1,"aria-label":i?`Editor for ${i}`:"File editor"})]})}function ZA(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function eR({currentWorkspace:e,projectName:n,workspaces:s,onSelect:i}){const[r,o]=a.useState(!1),l=a.useMemo(()=>e==="project"?n||"Project Root":s.find(u=>u.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(Ed,{size:14}):t.jsx(fc,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(qt,{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:()=>{i("project"),o(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(Ed,{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:()=>{i(c.id),o(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(fc,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:ZA(c.title)})]},c.id))]})]})]})}const tR=768,Kf=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),nR=new Set([...Kf,".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 ah(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return nR.has(n)}function sR(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return Kf.has(n)}function iR({initialWorkspace:e="project",onClose:n,onWorkspaceChange:s,projectId:i}){const{projectName:r,workspaces:o}=HA(i),l=a.useRef(null);Xs(l,!0,"fusion:files-modal-size");const c=wi(n),[u,d]=a.useState(e),[m,h]=a.useState(null),[g,p]=a.useState(!1),[f,x]=a.useState("list"),{entries:v,currentPath:b,setPath:y,loading:S,error:k,refresh:R}=zA(u,!0,i),{content:N,setContent:M,originalContent:C,loading:z,saving:A,error:P,save:F,hasChanges:W,mtime:$}=FA(u,m,!0,i);a.useEffect(()=>{d(e)},[e]),a.useEffect(()=>{const w=()=>{p(window.innerWidth<=tR)};return w(),window.addEventListener("resize",w),()=>window.removeEventListener("resize",w)},[]),a.useEffect(()=>{m||x("list")},[m]),a.useEffect(()=>{const w=q=>{q.key==="Escape"&&n(),(q.metaKey||q.ctrlKey)&&q.key==="s"&&(q.preventDefault(),W&&!A&&F())};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[n,W,A,F]);const _=a.useCallback(w=>{h(w),g&&x("editor")},[g]),I=a.useCallback(()=>{x("list")},[]),O=a.useCallback(()=>{M(C)},[C,M]),J=a.useCallback(w=>{d(w),h(null),x("list"),s?.(w)},[s]),E=`Files — ${a.useMemo(()=>u==="project"?"Project":o.find(w=>w.id===u)?.id??u,[u,o])}`,D=a.useMemo(()=>!m||!sR(m)?null:tp(u,m,i),[m,u,i]),T=w=>{const q=new Blob([w]).size;return q<1024?`${q} B`:`${(q/1024).toFixed(1)} KB`};return t.jsx("div",{className:"modal-overlay open",...c,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal file-browser-modal",ref:l,children:[t.jsxs("div",{className:"modal-header file-browser-modal-header",children:[t.jsxs("div",{className:"file-browser-header-title",children:[t.jsx(In,{size:18}),t.jsx("span",{children:E}),m&&t.jsx("span",{className:"file-browser-header-path",children:m})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsx(eR,{currentWorkspace:u,projectName:r,workspaces:o,onSelect:J}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Ot,{size:20})})]})]}),t.jsxs("div",{className:"file-browser-body",children:[t.jsx("div",{className:`file-browser-sidebar ${g?"mobile":""} ${f==="list"?"active":""}`,children:t.jsx(YA,{entries:v,currentPath:b,onSelectFile:_,onNavigate:y,loading:S,error:k,onRetry:R,workspace:u,onRefresh:R,projectId:i})}),t.jsx("div",{className:`file-browser-content ${g?"mobile":""} ${f==="editor"?"active":""}`,children:m?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"file-browser-toolbar",children:[t.jsxs("div",{className:"file-browser-file-info",children:[g&&f==="editor"&&t.jsxs("button",{className:"file-browser-back-button",onClick:I,"aria-label":"Back to file list",children:[t.jsx(wa,{size:16}),t.jsx("span",{children:"Back"})]}),m,ah(m)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(jx,{size:12}),"Binary file — read only"]}),$&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date($).toLocaleString()]}),z&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!D&&W&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:O,disabled:A,children:[t.jsx(wb,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void F(),disabled:A,children:[t.jsx(Kh,{size:14}),A?"Saving...":"Save"]})]})})]}),P&&!D&&t.jsx("div",{className:"file-browser-error-banner",children:P}),D?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:D,alt:m??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(XA,{content:N,onChange:M,filePath:m,readOnly:ah(m)})}),!D&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:T(N)}),W&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(In,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}function aR(e={}){const{pollInterval:n=3e4,autoRefresh:s=!0}=e,[i,r]=a.useState({providers:[],loading:!0,error:null,lastUpdated:null}),o=a.useRef(null),l=a.useRef(null),c=a.useCallback(async(d=!1)=>{l.current&&l.current.abort(),l.current=new AbortController,d&&r(m=>({...m,loading:!0,error:null}));try{const{providers:m}=await Gv();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:ke(m)||"Failed to fetch usage data"}))}},[]);a.useEffect(()=>{c()},[c]),a.useEffect(()=>{if(s)return o.current=setInterval(()=>{c(!1)},n),()=>{o.current&&(clearInterval(o.current),o.current=null)}},[s,n,c]),a.useEffect(()=>()=>{l.current&&l.current.abort(),o.current&&clearInterval(o.current)},[]);const u=a.useCallback(()=>c(!0),[c]);return{providers:i.providers,loading:i.loading,error:i.error,lastUpdated:i.lastUpdated,refresh:u}}function rR(e){const n=new Date(e),s=new Date,i=n.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit",hour12:!0});if(n.toDateString()===s.toDateString())return i;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"})} ${i}`:`${n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}, ${i}`}function oR(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const Gf="kb-usage-hidden-windows";function rh(e){const n=Dn(Gf,e);if(!n)return{};try{const s=JSON.parse(n);return!s||typeof s!="object"?{}:Object.entries(s).reduce((i,[r,o])=>{if(Array.isArray(o)){const l=o.filter(c=>typeof c=="string");l.length>0&&(i[r]=l)}return i},{})}catch{return{}}}function lR(e,n){os(Gf,JSON.stringify(e),n)}function Jf(e,n,s){return s[e]?.includes(n)??!1}function cR({window:e,viewMode:n,isHidden:s,onToggleHidden:i}){const r=oR(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`,u=o?`${Math.round(e.percentUsed)}% used`:`${Math.round(e.percentLeft)}% left`;let d=e.resetText;if(!d&&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?d=`resets in ${y}d ${S}h`:y>0?d=`resets in ${y}d`:b>0?d=`resets in ${b}h`:d=`resets in ${Math.floor(v/6e4)}m`}}const m=e.pace,h=m!==void 0;let g=0;h&&(g=o?100-m.percentElapsed:m.percentElapsed);const p=m?.status==="ahead",f=m?.status==="behind",x=m?.status==="on-track";return t.jsxs("div",{className:`usage-window ${s?"usage-window--hidden":""}`,children:[t.jsxs("div",{className:"usage-window-header",children:[t.jsx("span",{className:"usage-window-label",children:e.label}),t.jsxs("div",{className:"usage-window-header-controls",children:[!s&&t.jsx("span",{className:"usage-window-percentage",children:c}),!s&&t.jsx("button",{className:"btn-icon usage-window-hide-btn",onClick:i,"aria-label":`Hide ${e.label}`,"data-testid":"usage-window-hide-btn",children:t.jsx(da,{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:`${g}%`},"aria-hidden":"true","data-testid":"pace-marker"})]}),t.jsxs("div",{className:"usage-window-footer",children:[t.jsx("span",{className:"usage-window-left",children:u}),t.jsxs("span",{className:"usage-window-reset-group",children:[d&&t.jsx("span",{className:"usage-window-reset",children:d}),e.resetAt&&t.jsx("span",{className:"usage-window-reset-at",children:rR(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(Yc,{size:14,className:"pace-icon pace-ahead"}),t.jsx("span",{className:"pace-text pace-ahead",children:m.message})]}),f&&t.jsxs(t.Fragment,{children:[t.jsx(Vb,{size:14,className:"pace-icon pace-behind"}),t.jsx("span",{className:"pace-text pace-behind",children:m.message})]}),x&&t.jsxs(t.Fragment,{children:[t.jsx(dn,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:m.message})]})]})]})}function dR(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 uR({provider:e,viewMode:n,hiddenWindows:s,onToggleWindow:i,onShowAllHidden:r}){const o=s[e.name]?.length??0,l=()=>{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","data-provider":e.name,"data-status":e.status,children:[t.jsxs("div",{className:"usage-provider-header",children:[t.jsxs("div",{className:"usage-provider-info",children:[t.jsx(An,{provider:dR(e.name),size:"md"}),t.jsx("span",{className:"usage-provider-name",children:e.name}),o>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 (",o,")"]})]}),t.jsx("div",{className:"usage-provider-actions",children:l()})]}),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((c,u)=>{const d=Jf(e.name,c.label,s);return t.jsx(cR,{window:c,viewMode:n,isHidden:d,onToggleHidden:()=>i(e.name,c.label)},`${e.name}-${c.label}-${u}`)})}):e.status==="ok"?t.jsx("div",{className:"usage-provider-empty",children:"No usage data available"}):null]})}function mR(){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 hR({isOpen:e,onClose:n,projectId:s,anchorRect:i}){const{providers:r,loading:o,error:l,lastUpdated:c,refresh:u}=aR({autoRefresh:e}),[d,m]=a.useState(!1),[h,g]=a.useState(()=>typeof window<"u"?window.innerWidth>=769:!1),[p,f]=a.useState("used"),[x,v]=a.useState(()=>rh(s)),b=a.useRef(null),y=a.useRef(e),S=a.useRef(!1);a.useEffect(()=>{e||(S.current=!1)},[e]),a.useEffect(()=>{r.length>0&&(S.current=!0)},[r.length]),a.useEffect(()=>{if(typeof window>"u")return;const _=()=>{g(window.innerWidth>=769)};return window.addEventListener("resize",_),()=>window.removeEventListener("resize",_)},[]),a.useEffect(()=>{!y.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&u(),y.current=e},[e,c,u]),a.useEffect(()=>{const _=Dn("kb-usage-view-mode",s);if(_==="used"||_==="remaining"){f(_);return}f("used")},[s]);const k=a.useCallback(_=>{f(_),os("kb-usage-view-mode",_,s)},[s]);a.useEffect(()=>{v(rh(s))},[s]),a.useEffect(()=>{lR(x,s)},[x,s]);const R=a.useCallback((_,I)=>{v(O=>{if(Jf(_,I,O)){const J=(O[_]??[]).filter(Q=>Q!==I);if(J.length===0){const{[_]:Q,...E}=O;return E}return{...O,[_]:J}}return{...O,[_]:[...O[_]??[],I]}})},[]),N=a.useCallback(_=>{v(I=>{if(!I[_])return I;const{[_]:O,...J}=I;return J})},[]),M=a.useCallback(async()=>{m(!0),await u(),m(!1)},[u]);a.useEffect(()=>{if(!e)return;const _=I=>{I.key==="Escape"&&n()};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[e,n]);const C=a.useCallback(_=>{_.target===_.currentTarget&&n()},[n]);if(!e)return null;const z=!!(i&&h),F=z?Math.min((i?.bottom??0)+8,window.innerHeight-12):void 0,W=z?Math.max(window.innerWidth-(i?.right??0),0):void 0,$=t.jsxs("div",{className:`usage-modal${z?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:z?{position:"fixed",top:F,right:W}:void 0,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Cs,{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 ${p==="used"?"active":""}`,onClick:()=>k("used"),"aria-pressed":p==="used","data-testid":"usage-view-toggle-used",children:"Used"}),t.jsx("button",{className:`usage-view-toggle-btn ${p==="remaining"?"active":""}`,onClick:()=>k("remaining"),"aria-pressed":p==="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(Ot,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:b,children:(o||!S.current&&!l)&&r.length===0?t.jsx(mR,{}):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:M,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:r.map(_=>t.jsx(uR,{provider:_,viewMode:p,hiddenWindows:x,onToggleWindow:R,onShowAllHidden:N},_.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:M,disabled:o||d,"data-testid":"usage-refresh-btn",children:[t.jsx(Nn,{size:14,className:d?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]});return z?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"usage-popover-backdrop",onClick:n,"data-testid":"usage-modal-overlay"}),$]}):t.jsx("div",{className:"modal-overlay open",onClick:C,"data-testid":"usage-modal-overlay",children:$})}function Yf(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),i=n%60;if(s<60)return i>0?`${s}m ${i}s`:`${s}m`;const r=Math.floor(s/60),o=s%60;return o>0?`${r}h ${o}m`:`${r}h`}function Co(e){const n=Date.now(),s=new Date(e).getTime(),i=n-s;if(i<0){const r=Math.abs(i);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 i<6e4?"just now":i<36e5?`${Math.floor(i/6e4)}m ago`:i<864e5?`${Math.floor(i/36e5)}h ago`:`${Math.floor(i/864e5)}d ago`}const pR={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},Qf={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},fR={cron:zh,webhook:Jh,api:Fh,manual:Pn},gR={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},xR={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function bR({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(dn,{size:12}):t.jsx(vr,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:Yf(n)})]})}function vR({result:e,index:n}){const[s,i]=a.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:()=>i(!s),"aria-expanded":s,"aria-label":`Run #${n+1}: ${e.success?"succeeded":"failed"} ${Co(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(dn,{size:12}):t.jsx(vr,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:Co(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:Qf[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:Yf(r)}),s?t.jsx(li,{size:12}):t.jsx(qt,{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 yR({routine:e,onEdit:n,onDelete:s,onRun:i,onToggle:r,running:o,lastRunOutput:l}){const[c,u]=a.useState(!1),{confirm:d}=Ds(),m=a.useCallback(async()=>{await d({title:"Delete Routine",message:`Delete routine "${e.name}"? This cannot be undone.`,danger:!0})&&s(e)},[e,s,d]),h=pR[e.trigger.type],g=fR[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(g,{size:10}),Qf[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(To,{size:10}):t.jsx(In,{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:()=>i(e),disabled:o,title:o?"Running…":"Run now","aria-label":o?"Running…":`Run ${e.name} now`,children:o?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(xn,{size:14})}),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(Gs,{size:14}):t.jsx(xn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(Yn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:m,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(Xt,{size:14})})]})]}),t.jsxs("div",{className:"routine-card-meta",children:[e.steps&&e.steps.length>0?t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(Ui,{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(yi,{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:gR[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:xR[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:Co(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:Co(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(bR,{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:()=>u(f=>!f),"aria-expanded":c,children:[c?t.jsx(li,{size:12}):t.jsx(qt,{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((f,x)=>t.jsx(vR,{result:f,index:x},`${f.startedAt}-${x}`)),e.runHistory.length>10&&t.jsxs("div",{className:"schedule-history-more",children:["…and ",e.runHistory.length-10," more"]})]})]})]})}function kR({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(ri,{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(Jx,{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(qn,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function Zl(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function jR(e){return e==="command"?{id:Zl(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:Zl(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:Zl(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function wR({step:e,onSave:n,onCancel:s}){const[i,r]=a.useState(e.name),[o,l]=a.useState(e.type),[c,u]=a.useState(e.command??""),[d,m]=a.useState(e.prompt??""),[h,g]=a.useState(e.modelProvider??""),[p,f]=a.useState(e.modelId??""),[x,v]=a.useState(e.taskTitle??""),[b,y]=a.useState(e.taskDescription??""),[S,k]=a.useState(e.taskColumn??"triage"),[R,N]=a.useState(e.timeoutMs),[M,C]=a.useState(e.continueOnFailure??!1),[z,A]=a.useState({}),[P,F]=a.useState([]),[W,$]=a.useState(!1),[_,I]=a.useState(null);a.useEffect(()=>{let D=!1;return $(!0),I(null),cs().then(T=>{D||F(T.models)}).catch(T=>{D||I(T instanceof Error?T.message:"Failed to load models")}).finally(()=>{D||$(!1)}),()=>{D=!0}},[]);const O=a.useCallback(()=>{const D={};return i.trim()||(D.name="Step name is required"),o==="command"&&!c.trim()&&(D.command="Command is required"),o==="ai-prompt"&&!d.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"),R!==void 0&&R<1e3&&(D.timeoutMs="Timeout must be at least 1 second (1000ms)"),A(D),Object.keys(D).length===0},[i,o,c,d,b,h,p,R]),J=h&&p?`${h}/${p}`:"",Q=a.useCallback(D=>{if(!D)g(""),f("");else{const T=D.indexOf("/");T!==-1&&(g(D.slice(0,T)),f(D.slice(T+1)))}},[]),E=a.useCallback(()=>{if(!O())return;const D={...e,name:i.trim(),type:o,command:o==="command"?c.trim():void 0,prompt:o==="ai-prompt"?d.trim():void 0,taskTitle:o==="create-task"&&x.trim()?x.trim():void 0,taskDescription:o==="create-task"&&b.trim()?b.trim():void 0,taskColumn:o==="create-task"?S:void 0,modelProvider:(o==="ai-prompt"||o==="create-task")&&h.trim()?h.trim():void 0,modelId:(o==="ai-prompt"||o==="create-task")&&p.trim()?p.trim():void 0,timeoutMs:R||void 0,continueOnFailure:M};o!=="ai-prompt"&&delete D.prompt,o!=="create-task"&&(delete D.taskTitle,delete D.taskDescription,delete D.taskColumn),n(D)},[O,n,e,i,o,c,d,x,b,S,h,p,R,M]);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:i,onChange:D=>r(D.target.value),"aria-invalid":!!z.name}),z.name&&t.jsx("small",{className:"field-error",children:z.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=>u(D.target.value),rows:2,"aria-invalid":!!z.command}),z.command&&t.jsx("small",{className:"field-error",children:z.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:d,onChange:D=>m(D.target.value),rows:3,"aria-invalid":!!z.prompt}),z.prompt&&t.jsx("small",{className:"field-error",children:z.prompt})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-model-${e.id}`,children:"Model (optional)"}),t.jsx($n,{id:`step-model-${e.id}`,label:"Model",models:P,value:J,onChange:Q,placeholder:"Use default",disabled:W}),_&&t.jsx("small",{className:"field-error",children:_}),t.jsx("small",{children:"AI model for this step. Uses default if not selected."})]})]}),o==="create-task"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-title-${e.id}`,children:"Task Title (optional)"}),t.jsx("input",{id:`step-task-title-${e.id}`,type:"text",placeholder:"e.g. Review weekly dependencies",value:x,onChange: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":!!z.taskDescription}),z.taskDescription&&t.jsx("small",{className:"field-error",children:z.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=>k(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($n,{id:`step-task-model-${e.id}`,label:"Model",models:P,value:J,onChange:Q,placeholder:"Use default",disabled:W}),_&&t.jsx("small",{className:"field-error",children:_}),z.modelProvider&&t.jsx("small",{className:"field-error",children:z.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:R??"",onChange:D=>N(D.target.value?Number(D.target.value):void 0),"aria-invalid":!!z.timeoutMs}),z.timeoutMs&&t.jsx("small",{className:"field-error",children:z.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:M,onChange:D=>C(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:E,children:"Save Step"})]})]})}function NR({steps:e,onChange:n,onEditingChange:s}){const[i,r]=a.useState(null);a.useEffect(()=>{s?.(i!==null)},[i,s]);const o=a.useCallback(d=>{const m=jR(d);n([...e,m]),r(m.id)},[e,n]),l=a.useCallback(d=>{n(e.filter(m=>m.id!==d)),i===d&&r(null)},[e,n,i]),c=a.useCallback((d,m)=>{const h=e.findIndex(f=>f.id===d);if(h<0)return;const g=m==="up"?h-1:h+1;if(g<0||g>=e.length)return;const p=[...e];[p[h],p[g]]=[p[g],p[h]],n(p)},[e,n]),u=a.useCallback(d=>{n(e.map(m=>m.id===d.id?d: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((d,m)=>t.jsx("div",{className:"step-card",children:i===d.id?t.jsx(wR,{step:d,onSave:u,onCancel:()=>r(null)}):t.jsxs("div",{className:"step-card-row",children:[t.jsx("div",{className:"step-card-drag",children:t.jsx(Jc,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(kR,{type:d.type}),t.jsx("span",{className:"step-card-name",children:d.name}),d.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(d.id,"up"),disabled:m===0,title:"Move up","aria-label":`Move ${d.name} up`,children:t.jsx(li,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(d.id,"down"),disabled:m===e.length-1,title:"Move down","aria-label":`Move ${d.name} down`,children:t.jsx(qt,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(d.id),title:"Edit","aria-label":`Edit ${d.name}`,children:t.jsx(Yn,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(d.id),title:"Delete","aria-label":`Delete ${d.name}`,children:t.jsx(Xt,{size:14})})]})]})},d.id))}),t.jsxs("div",{className:"steps-add-buttons",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("command"),children:[t.jsx(Zt,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx(Zt,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx(Zt,{size:14}),"Add Create Task Step"]})]})]})}const Xf={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},SR={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function CR(e){const n=e.trim();for(const[s,i]of Object.entries(Xf))if(i===n)return s;return"custom"}function ER(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function _R(e,n,s,i,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:i||void 0};case"api":return{type:"api",endpoint:r||"/api/routine/"+Math.random().toString(36).slice(2,10)};case"manual":return{type:"manual"}}}function MR(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 AR=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],RR=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function oh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function lh({routine:e,onSubmit:n,onCancel:s,scope:i,projectId:r,onScopeChange:o}){const l=!!e,c=e?MR(e):{triggerType:"cron",cronExpression:"0 * * * *",webhookPath:"",webhookSecret:"",endpoint:""},[u,d]=a.useState(e?.name??""),[m,h]=a.useState(e?.description??""),[g,p]=a.useState(c.triggerType),[f,x]=a.useState(c.cronExpression),[v,b]=a.useState(()=>c.triggerType!=="cron"?"custom":CR(c.cronExpression)),[y,S]=a.useState(c.webhookPath),[k,R]=a.useState(c.webhookSecret),[N,M]=a.useState(c.endpoint),[C,z]=a.useState(e?.executionPolicy??"queue"),[A,P]=a.useState(e?.catchUpPolicy??"run_one"),[F,W]=a.useState(e?.enabled??!0),$=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,_=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[I,O]=a.useState(e?.steps&&e.steps.length>0&&!$&&!_?"advanced":"simple"),[J,Q]=a.useState(()=>$?"ai-prompt":_?"create-task":"command"),[E,D]=a.useState(e?.command??""),[T,w]=a.useState(e?.steps??[]),[q,G]=a.useState(!1),[me,ce]=a.useState(e?.timeoutMs??3e5),[ae,pe]=a.useState($?e.steps?.[0]?.prompt??"":""),[U,Ne]=a.useState(_?e.steps?.[0]?.taskTitle??"":""),[ne,xe]=a.useState(_?e.steps?.[0]?.taskDescription??"":""),[le,ve]=a.useState(_?e.steps?.[0]?.taskColumn??"triage":"triage"),[ee,Ee]=a.useState($||_?e.steps?.[0]?.modelProvider??"":""),[Fe,Ke]=a.useState($||_?e.steps?.[0]?.modelId??"":""),[Ze,Xe]=a.useState([]),[Qe,it]=a.useState(!1),[Ie,Ge]=a.useState(null),[se,ye]=a.useState(i??"global"),[Z,Te]=a.useState({}),[ze,be]=a.useState(!1),Me=a.useRef(!0);a.useEffect(()=>()=>{Me.current=!1},[]),a.useEffect(()=>{i&&ye(i)},[i]),a.useEffect(()=>{let fe=!1;return it(!0),Ge(null),cs().then(tt=>{fe||Xe(tt.models)}).catch(tt=>{fe||Ge(tt instanceof Error?tt.message:"Failed to load models")}).finally(()=>{fe||it(!1)}),()=>{fe=!0}},[]);const Be=ee&&Fe?`${ee}/${Fe}`:"",lt=a.useCallback(fe=>{if(!fe){Ee(""),Ke("");return}const tt=fe.indexOf("/");tt!==-1&&(Ee(fe.slice(0,tt)),Ke(fe.slice(tt+1)))},[]),je=a.useCallback(()=>{const fe={};if(u.trim()||(fe.name="Name is required"),se==="project"&&!r&&(fe.scope="Project-specific entries require an active project."),g==="cron"&&v==="custom"&&(f.trim()?ER(f)||(fe.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):fe.cronExpression="Cron expression is required"),g==="webhook"&&!y.trim()&&(fe.webhookPath="Webhook path is required"),g==="api"&&!N.trim()&&(fe.endpoint="API endpoint is required"),I==="simple")J==="command"&&!E.trim()&&(fe.command="Command is required"),J==="ai-prompt"&&!ae.trim()&&(fe.prompt="Prompt is required"),J==="create-task"&&!ne.trim()&&(fe.taskDescription="Task description is required"),(ee.trim()&&!Fe.trim()||!ee.trim()&&Fe.trim())&&(fe.model="Both model provider and model ID must be set, or both must be empty");else{T.length===0&&(fe.steps="At least one step is required"),q&&(fe.stepsEditing="Please save or cancel all step edits before saving the routine");const tt=[];T.forEach((ut,vt)=>{ut.name?.trim()||tt.push(`Step ${vt+1}: Name is required`),ut.type==="command"&&!ut.command?.trim()&&tt.push(`Step ${vt+1}: Command is required`),ut.type==="ai-prompt"&&!ut.prompt?.trim()&&tt.push(`Step ${vt+1}: Prompt is required`),ut.type==="create-task"&&!ut.taskDescription?.trim()&&tt.push(`Step ${vt+1}: Task description is required`)}),tt.length>0&&(fe.steps=tt.join("; "))}return me<1e3&&(fe.timeoutMs="Timeout must be at least 1 second (1000ms)"),Te(fe),Object.keys(fe).length===0},[u,g,f,v,y,N,se,r,I,J,E,ae,ne,ee,Fe,T,q,me]),ie=a.useCallback(async fe=>{if(fe.preventDefault(),!!je()){be(!0);try{let tt=e?.scope??se??(r?"project":"global");tt==="project"&&!r&&(tt="global");const ut=_R(g,f,y,k,N);let vt,gt;I==="simple"?J==="command"?vt=E.trim()||void 0:J==="ai-prompt"?gt=[{id:oh(),type:"ai-prompt",name:u.trim(),prompt:ae.trim(),modelProvider:ee.trim()||void 0,modelId:Fe.trim()||void 0}]:gt=[{id:oh(),type:"create-task",name:u.trim(),taskTitle:U.trim()||void 0,taskDescription:ne.trim(),taskColumn:le,modelProvider:ee.trim()||void 0,modelId:Fe.trim()||void 0}]:gt=T;const dt={name:u.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:ut,command:vt,steps:gt,timeoutMs:me,executionPolicy:C,catchUpPolicy:A,enabled:F,scope:tt};await n(dt)}finally{Me.current&&be(!1)}}},[je,n,u,m,g,f,y,k,N,I,J,E,ae,ee,Fe,U,ne,le,T,me,C,A,F,se,r,e?.scope,e?.agentId]),Ae="routine-name-error",he="routine-cron-error",Re="routine-webhook-error",Je="routine-endpoint-error",$e="routine-command-error",de="routine-prompt-error",re="routine-task-description-error",ue="routine-model-error",Pe="routine-timeout-error",Se=a.useCallback(fe=>{b(fe),fe!=="custom"&&x(Xf[fe])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:ie,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:u,onChange:fe=>d(fe.target.value),"aria-invalid":!!Z.name,"aria-describedby":Z.name?Ae:void 0}),Z.name&&t.jsx("small",{id:Ae,className:"field-error",children:Z.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:fe=>h(fe.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${se==="global"?" active":""}`,onClick:()=>{ye("global"),o?.("global")},role:"radio","aria-checked":se==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:"Global scope",children:[t.jsx(To,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${se==="project"?" active":""}`,onClick:()=>{ye("project"),o?.("project")},role:"radio","aria-checked":se==="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(In,{size:12}),"Project"]})]}),t.jsx("small",{children:!r&&!e?.scope?"No active project. Routines will be created at global scope.":se==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),Z.scope&&t.jsx("small",{className:"field-error",children:Z.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${g==="cron"?" active":""}`,onClick:()=>p("cron"),role:"radio","aria-checked":g==="cron",children:[t.jsx(zh,{size:14}),"Cron"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="webhook"?" active":""}`,onClick:()=>p("webhook"),role:"radio","aria-checked":g==="webhook",children:[t.jsx(Jh,{size:14}),"Webhook"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="api"?" active":""}`,onClick:()=>p("api"),role:"radio","aria-checked":g==="api",children:[t.jsx(Fh,{size:14}),"API"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="manual"?" active":""}`,onClick:()=>p("manual"),role:"radio","aria-checked":g==="manual",children:[t.jsx(Pn,{size:14}),"Manual"]})]})]}),g==="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:fe=>Se(fe.target.value),children:Object.entries(SR).map(([fe,tt])=>t.jsx("option",{value:fe,children:tt},fe))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:f,onChange:fe=>x(fe.target.value),disabled:v!=="custom","aria-invalid":!!Z.cronExpression,"aria-describedby":Z.cronExpression?he:void 0}),Z.cronExpression?t.jsx("small",{id:he,className:"field-error",children:Z.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: ${f}`})]}),g==="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:fe=>S(fe.target.value),"aria-invalid":!!Z.webhookPath,"aria-describedby":Z.webhookPath?Re:void 0}),Z.webhookPath?t.jsx("small",{id:Re,className:"field-error",children:Z.webhookPath}):t.jsx("small",{children:"URL path for the webhook endpoint"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-secret",children:"Webhook Secret (optional)"}),t.jsx("input",{id:"routine-webhook-secret",type:"password",placeholder:"Optional — leave empty for unauthenticated webhooks",value:k,onChange:fe=>R(fe.target.value)}),t.jsx("small",{children:"HMAC secret for signature verification. Leave empty for unauthenticated webhooks."})]})]}),g==="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:N,onChange:fe=>M(fe.target.value),"aria-invalid":!!Z.endpoint,"aria-describedby":Z.endpoint?Je:void 0}),Z.endpoint?t.jsx("small",{id:Je,className:"field-error",children:Z.endpoint}):t.jsx("small",{children:"API endpoint path that triggers this routine"})]}),g==="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${I==="simple"?" active":""}`,onClick:()=>O("simple"),role:"radio","aria-checked":I==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${I==="advanced"?" active":""}`,onClick:()=>O("advanced"),role:"radio","aria-checked":I==="advanced",children:"Multi-Step"})]}),t.jsx("small",{children:I==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),I==="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${J==="command"?" active":""}`,onClick:()=>Q("command"),role:"radio","aria-checked":J==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${J==="ai-prompt"?" active":""}`,onClick:()=>Q("ai-prompt"),role:"radio","aria-checked":J==="ai-prompt",children:"AI Prompt"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${J==="create-task"?" active":""}`,onClick:()=>Q("create-task"),role:"radio","aria-checked":J==="create-task",children:"Create Task"})]})]}),J==="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:E,onChange:fe=>D(fe.target.value),"aria-invalid":!!Z.command,"aria-describedby":Z.command?$e:void 0}),Z.command?t.jsx("small",{id:$e,className:"field-error",children:Z.command}):t.jsx("small",{children:"Shell command to execute."})]}):J==="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:ae,onChange:fe=>pe(fe.target.value),rows:3,"aria-invalid":!!Z.prompt,"aria-describedby":Z.prompt?de:void 0}),Z.prompt?t.jsx("small",{id:de,className:"field-error",children:Z.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($n,{id:"routine-model",label:"Model",models:Ze,value:Be,onChange:lt,placeholder:"Use default",disabled:Qe}),Ie&&t.jsx("small",{className:"field-error",children:Ie}),Z.model&&t.jsx("small",{id:ue,className:"field-error",children:Z.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:U,onChange:fe=>Ne(fe.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:ne,onChange:fe=>xe(fe.target.value),rows:4,"aria-invalid":!!Z.taskDescription,"aria-describedby":Z.taskDescription?re:void 0}),Z.taskDescription?t.jsx("small",{id:re,className:"field-error",children:Z.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:le,onChange:fe=>ve(fe.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($n,{id:"routine-task-model",label:"Executor Model",models:Ze,value:Be,onChange:lt,placeholder:"Use default",disabled:Qe}),Ie&&t.jsx("small",{className:"field-error",children:Ie}),Z.model&&t.jsx("small",{id:ue,className:"field-error",children:Z.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(NR,{steps:T,onChange:w,onEditingChange:G}),Z.steps&&t.jsx("small",{className:"field-error",children:Z.steps}),Z.stepsEditing&&t.jsx("small",{className:"field-error",children:Z.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:me,onChange:fe=>ce(Number(fe.target.value)),"aria-invalid":!!Z.timeoutMs,"aria-describedby":Z.timeoutMs?Pe:void 0}),Z.timeoutMs?t.jsx("small",{id:Pe,className:"field-error",children:Z.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:C,onChange:fe=>z(fe.target.value),children:AR.map(fe=>t.jsx("option",{value:fe.value,children:fe.label},fe.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:A,onChange:fe=>P(fe.target.value),children:RR.map(fe=>t.jsx("option",{value:fe.value,children:fe.label},fe.value))}),t.jsx("small",{children:"What to do when a scheduled run is missed"})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:"routine-enabled",className:"checkbox-label",children:[t.jsx("input",{id:"routine-enabled",type:"checkbox",checked:F,onChange:fe=>W(fe.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:ze,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:ze,children:ze?"Saving…":l?"Save Changes":"Create Routine"})]})]})}const TR=3e4;function PR({onClose:e,addToast:n,projectId:s}){const[i,r]=a.useState(()=>s?"project":"global"),[o,l]=a.useState([]),[c,u]=a.useState("list"),[d,m]=a.useState(),[h,g]=a.useState(null),[p,f]=a.useState({}),x=a.useRef(null);Xs(x,!0,"fusion:automation-modal-size");const v=a.useMemo(()=>({scope:i,projectId:i==="project"?s:void 0}),[i,s]),b=a.useCallback(async()=>{try{const $=await ak(v);l($),f(_=>{const I={..._};for(const O of $){const J=I[O.id];if(!J||!O.lastRunResult)continue;const Q=O.lastRunResult;Q.success===J.success&&(Q.output||"")===J.output&&(Q.error||"")===(J.error||"")&&delete I[O.id]}return I})}catch($){n(ke($)||"Failed to load routines","error")}},[n,v]);a.useEffect(()=>{b()},[b]),a.useEffect(()=>{const $=setInterval(()=>{b()},TR);return()=>clearInterval($)},[b]),a.useEffect(()=>{const $=_=>{_.key==="Escape"&&(c!=="list"?(u("list"),m(void 0)):e())};return document.addEventListener("keydown",$),()=>document.removeEventListener("keydown",$)},[e,c]);const y=wi(e),S=a.useCallback(async $=>{try{await rk($,v),n("Routine created","success"),u("list"),await b()}catch(_){n(ke(_)||"Failed to create routine","error")}},[n,b,v]),k=a.useCallback($=>{m($),u("edit")},[]),R=a.useCallback(async $=>{if(d)try{await Bd(d.id,$,v),n("Routine updated","success"),u("list"),m(void 0),await b()}catch(_){n(ke(_)||"Failed to update routine","error")}},[d,n,b,v]),N=a.useCallback(async $=>{try{await ok($.id,v),n(`Deleted "${$.name}"`,"success"),await b()}catch(_){n(ke(_)||"Failed to delete routine","error")}},[n,b,v]),M=a.useCallback(async $=>{g($.id);try{const{result:_}=await lk($.id,v);f(I=>({...I,[$.id]:{output:_.output||"",error:_.error,success:_.success}})),_.success?n(`"${$.name}" completed successfully`,"success"):n(`"${$.name}" failed: ${_.error||"Unknown error"}`,"error"),await b()}catch(_){n(ke(_)||"Failed to run routine","error")}finally{g(null)}},[n,b,v]),C=a.useCallback(async $=>{try{await Bd($.id,{enabled:!$.enabled},v),n(`"${$.name}" ${$.enabled?"disabled":"enabled"}`,"success"),await b()}catch(_){n(ke(_)||"Failed to toggle routine","error")}},[n,b,v]),z=a.useCallback(()=>{u("list"),m(void 0)},[]);a.useEffect(()=>{c!=="list"&&f({})},[c]);const A=a.useCallback($=>{r($),u("list"),m(void 0),f({})},[]),P=()=>c==="create"?t.jsx(lh,{onSubmit:S,onCancel:z,scope:i,projectId:s}):c==="edit"&&d?t.jsx(lh,{routine:d,onSubmit:R,onCancel:z,scope:i,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(Pn,{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:()=>u("create"),children:[t.jsx(Zt,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map($=>t.jsx(yR,{routine:$,onEdit:k,onDelete:N,onRun:M,onToggle:C,running:h===$.id,lastRunOutput:p[$.id]??null},$.id))}),F=()=>P(),W=c==="list"&&o.length>0;return t.jsx("div",{className:"modal-overlay open",...y,children:t.jsxs("div",{ref:x,className:"modal modal-lg automation-modal",role:"dialog","aria-modal":"true","aria-labelledby":"schedules-modal-title",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(Pn,{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(Ot,{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${i==="global"?" active":""}`,onClick:()=>A("global"),"aria-pressed":i==="global",title:"Global (user-level) automations",children:[t.jsx(To,{size:14}),"Global"]}),t.jsxs("button",{type:"button",className:`scope-btn${i==="project"?" active":""}`,onClick:()=>A("project"),"aria-pressed":i==="project",title:"Project-scoped automations",children:[t.jsx(In,{size:14}),"Project"]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(Pn,{size:14}),o.length," automation",o.length===1?"":"s"]})]}),t.jsx("div",{className:"scheduling-toolbar-right",children:W&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>u("create"),"aria-label":"Create new automation",children:[t.jsx(Zt,{size:14}),"New Automation"]})})]}),t.jsx("div",{className:"schedule-modal-content",id:"scheduled-tasks-content",children:F()})]})})}const IR=3e4,Bc=new Map,ec=new Map;function ch(e){return e??"default"}function dh(e){const n=Bc.get(e);return n?Date.now()>=n.expiresAt?(Bc.delete(e),null):n:null}function $R(e,n){const s=e.some(r=>r.id!=="github"&&r.authenticated),i=e.some(r=>r.id==="github"&&r.authenticated)||(n?.authenticated??!1);return{hasAiProvider:s,hasGithub:i}}async function DR(e){const n=ec.get(e);if(n)return n;const s=mr().then(({providers:i,ghCli:r})=>{const l={...$R(i,r),ghCli:r,expiresAt:Date.now()+IR};return Bc.set(e,l),l}).finally(()=>{ec.delete(e)});return ec.set(e,s),s}function Zf(e){const n=ch(e),s=dh(n),[i,r]=a.useState(s?.hasAiProvider??!1),[o,l]=a.useState(s?.hasGithub??!1),[,c]=a.useState(s?.ghCli),[u,d]=a.useState(s==null),m=a.useRef(!!s);return a.useEffect(()=>{let h=!1;const g=ch(e),p=dh(g);if(p)return r(p.hasAiProvider),l(p.hasGithub),c(p.ghCli),d(!1),m.current=!0,()=>{h=!0};m.current=!1;async function f(){!m.current&&d(!0);try{const v=await DR(g);if(h)return;r(v.hasAiProvider),l(v.hasGithub),c(v.ghCli)}catch{}finally{h||(m.current=!0,d(!1))}}return f(),()=>{h=!0}},[e]),a.useMemo(()=>({hasAiProvider:i,hasGithub:o,loading:u,hasWarnings:!i||!o}),[i,o,u])}function eg({hasAiProvider:e,hasGithub:n,compact:s=!1,onDismiss:i}){if(e&&n)return null;const r=i?t.jsx("button",{type:"button",className:"setup-warning-banner__dismiss touch-target","aria-label":"Dismiss setup warning",onClick:i,children:t.jsx(Ot,{size:16,"aria-hidden":"true"})}):null;if(s)return t.jsxs("div",{className:`setup-warning-banner setup-warning-banner--compact${i?" 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${i?" 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 LR({isOpen:e,onClose:n,projectId:s,tasks:i,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const{confirm:u}=Ds(),[d,m]=a.useState(""),[h,g]=a.useState([]),[p,f]=a.useState([]),[x,v]=a.useState(!1),[b,y]=a.useState(""),[S,k]=a.useState(""),[R,N]=a.useState(""),[M,C]=a.useState(""),[z,A]=a.useState(""),[P,F]=a.useState("default"),[W,$]=a.useState(!1),[_,I]=a.useState([]),[O,J]=a.useState(!1),[Q,E]=a.useState(void 0),[D,T]=a.useState(ps),[w,q]=a.useState(void 0),[G,me]=a.useState(null),[ce,ae]=a.useState([]),[pe,U]=a.useState(!1),[Ne,ne]=a.useState(!1),xe=a.useRef(null),[le,ve]=a.useState(!1),[ee,Ee]=a.useState(""),Fe=a.useRef(null),{hasAiProvider:Ke,hasGithub:Ze,loading:Xe}=Zf(s),{nodes:Qe}=Bo(),it=a.useCallback(je=>{J(!0),I(je)},[]),Ie=a.useCallback(()=>{J(!1)},[]),Ge=a.useCallback(async()=>{if(ce.length>0){U(!0);return}ne(!0);try{const je=await Na(void 0,s);ae(je),U(!0)}catch(je){const ie=ke(je);o(ie?`Failed to load agents: ${ie}`:"Failed to load agents","error"),U(!1)}finally{ne(!1)}},[ce.length,s,o]);a.useEffect(()=>{if(!pe)return;const je=ie=>{xe.current&&!xe.current.contains(ie.target)&&U(!1)};return document.addEventListener("mousedown",je),()=>document.removeEventListener("mousedown",je)},[pe]),a.useEffect(()=>{if(!le)return;const je=ie=>{Fe.current&&!Fe.current.contains(ie.target)&&(ve(!1),Ee(""))};return document.addEventListener("mousedown",je),()=>document.removeEventListener("mousedown",je)},[le]);const se=i.filter(je=>!h.includes(je.id)).sort((je,ie)=>{const Ae=ie.createdAt.localeCompare(je.createdAt);if(Ae!==0)return Ae;const he=parseInt(je.id.slice(je.id.lastIndexOf("-")+1),10)||0;return(parseInt(ie.id.slice(ie.id.lastIndexOf("-")+1),10)||0)-he}),ye=ee?se.filter(je=>je.id.toLowerCase().includes(ee.toLowerCase())||je.title&&je.title.toLowerCase().includes(ee.toLowerCase())||je.description&&je.description.toLowerCase().includes(ee.toLowerCase())):se,Z=(je,ie)=>je.length>ie?je.slice(0,ie)+"…":je;a.useEffect(()=>{const je=d.trim()!==""||h.length>0||p.length>0||b!==""||S!==""||R!==""||M!==""||_.length>0||G!==null||Q!==void 0||D!==ps||w!==void 0;$(je)},[d,h,p,b,S,R,M,_,G,Q,D,w]);const Te=a.useCallback(async()=>{W&&!await u({title:"Discard Changes",message:"You have unsaved changes. Discard them?",danger:!0})||(p.forEach(je=>URL.revokeObjectURL(je.previewUrl)),f([]),m(""),g([]),y(""),k(""),N(""),C(""),A(""),F("default"),I([]),J(!1),me(null),U(!1),E(void 0),T(ps),q(void 0),$(!1),n())},[W,n,p,u]),ze=a.useCallback(async()=>{const je=d.trim();if(!(!je||x)){v(!0);try{const ie=b.indexOf("/"),Ae=S.indexOf("/"),he=R.indexOf("/"),Re=await r({title:void 0,description:je,column:"triage",dependencies:h.length?h:void 0,enabledWorkflowSteps:O?_.length>0?_:[]:void 0,...G?{assignedAgentId:G}:{},modelPresetId:P==="preset"&&z||void 0,modelProvider:b&&ie!==-1?b.slice(0,ie):void 0,modelId:b&&ie!==-1?b.slice(ie+1):void 0,validatorModelProvider:S&&Ae!==-1?S.slice(0,Ae):void 0,validatorModelId:S&&Ae!==-1?S.slice(Ae+1):void 0,planningModelProvider:R&&he!==-1?R.slice(0,he):void 0,planningModelId:R&&he!==-1?R.slice(he+1):void 0,thinkingLevel:M!==""?M:void 0,reviewLevel:Q,priority:D,nodeId:w});if(p.length>0){const Je=[];for(const $e of p)try{await ur(Re.id,$e.file,s)}catch{Je.push($e.file.name)}Je.length>0&&o(`Failed to upload: ${Je.join(", ")}`,"error")}p.forEach(Je=>URL.revokeObjectURL(Je.previewUrl)),f([]),m(""),g([]),y(""),k(""),N(""),C(""),A(""),F("default"),I([]),J(!1),me(null),U(!1),E(void 0),T(ps),q(void 0),o(`Created ${Re.id}`,"success"),n()}catch(ie){o(ke(ie)||"Failed to create task","error")}finally{v(!1)}}},[d,h,p,b,S,R,M,x,r,o,n,s,P,z,_,O,G,Q,D,w]),be=a.useCallback(je=>{je.key==="Escape"&&(je.preventDefault(),Te())},[Te]),Be=(G?ce.find(je=>je.id===G):void 0)?.name??G,lt=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:Fe,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>ve(je=>!je),disabled:x,"data-testid":"dep-trigger",children:h.length>0?`${h.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:ee,onChange:je=>Ee(je.target.value),onClick:je=>je.stopPropagation()}),ye.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):ye.map(je=>t.jsxs("div",{className:`dep-dropdown-item${h.includes(je.id)?" selected":""}`,onClick:()=>{g(h.includes(je.id)?h.filter(ie=>ie!==je.id):[...h,je.id]),ve(!1),Ee("")},onMouseDown:ie=>ie.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:je.id}),t.jsx("span",{className:"dep-dropdown-title",children:Z(je.title||je.description||je.id,30)})]},je.id))]})]}),h.length>0&&t.jsx("div",{className:"selected-deps",children:h.map(je=>t.jsxs("span",{className:"dep-chip",children:[je,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>g(h.filter(ie=>ie!==je)),disabled:x,children:"×"})]},je))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:xe,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{pe?U(!1):Ge()},disabled:x,"data-testid":"new-task-agent-button",children:[t.jsx(gn,{size:12,style:{verticalAlign:"middle"}}),Be?` ${Be}`:" Assign agent"]}),pe&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:je=>je.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),Ne&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!Ne&&ce.filter(je=>je.state!=="terminated").map(je=>t.jsxs("div",{className:`dep-dropdown-item${G===je.id?" selected":""}`,onMouseDown:ie=>ie.preventDefault(),onClick:()=>{me(je.id===G?null:je.id),U(!1)},"data-testid":`agent-option-${je.id}`,children:[t.jsx(gn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:je.role}),t.jsx("span",{className:"dep-dropdown-title",children:je.name})]},je.id)),!Ne&&ce.filter(je=>je.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),G&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:je=>je.preventDefault(),onClick:()=>{me(null),U(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:Te,onKeyDown:be,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:je=>je.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:Te,disabled:x,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!Xe&&t.jsx(eg,{hasAiProvider:Ke,hasGithub:Ze}),t.jsx(qf,{mode:"create",description:d,onDescriptionChange:m,dependencies:h,onDependenciesChange:g,executorModel:b,onExecutorModelChange:y,validatorModel:S,onValidatorModelChange:k,presetMode:P,onPresetModeChange:F,selectedPresetId:z,onSelectedPresetIdChange:A,selectedWorkflowSteps:_,onWorkflowStepsChange:it,onDefaultOnApplied:Ie,pendingImages:p,onImagesChange:f,tasks:i,projectId:s,disabled:x,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:Te,planningModel:R,onPlanningModelChange:N,thinkingLevel:M,onThinkingLevelChange:C,reviewLevel:Q,onReviewLevelChange:E,priority:D,onPriorityChange:T,nodeId:w,onNodeIdChange:q,nodeOptions:Qe,renderBelowPrimary:lt,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Te,disabled:x,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:ze,disabled:!d.trim()||x,children:x?"Creating...":"Create Task"})]})]})}):null}function ai(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 uh(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function zR(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function FR(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function OR(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function tc(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function UR(e){if(!e)return"Not yet";const n=new Date(e);return Number.isNaN(n.getTime())?"Not yet":n.toLocaleString()}function BR({isOpen:e,onClose:n,projectId:s}){const[i,r]=a.useState(null),[o,l]=a.useState(!1),[c,u]=a.useState(null),[d,m]=a.useState(!0),[h,g]=a.useState(90),[p,f]=a.useState(!1),[x,v]=a.useState(!1),[b,y]=a.useState(null),[S,k]=a.useState(null),[R,N]=a.useState(null),M=a.useCallback(async D=>{l(!0);try{const T=await Ik(s);r(T),u(null),N(Date.now()),D?.preserveKillResult||y(null)}catch(T){u(T instanceof Error?T.message:"Failed to load system stats")}finally{l(!1)}},[s]);a.useEffect(()=>{if(!e)return;M();const D=window.setInterval(()=>{M()},5e3);return()=>{window.clearInterval(D)}},[e,M]),a.useEffect(()=>{if(!e)return;(async()=>{try{const T=await Vi();m(T.vitestAutoKillEnabled??!0),g(T.vitestKillThresholdPct??90),k(null)}catch(T){k(T instanceof Error?T.message:"Failed to load vitest settings")}})()},[e]),a.useEffect(()=>{if(!e)return;const D=T=>{T.key==="Escape"&&n()};return document.addEventListener("keydown",D),()=>document.removeEventListener("keydown",D)},[e,n]);const C=a.useMemo(()=>{if(!i)return[];const D=i.systemStats,T=tc(zR(D.heapUsed,D.heapLimit)),w=tc(FR(D.rss,D.systemTotalMem));return[{label:"RSS",value:ai(D.rss),detail:uh(D.rss,D.systemTotalMem),className:w},{label:"Heap Used",value:ai(D.heapUsed),detail:`of ${ai(D.heapTotal)}`,className:T},{label:"Heap Limit",value:ai(D.heapLimit),detail:"V8 limit"},{label:"External",value:ai(D.external)},{label:"Array Buffers",value:ai(D.arrayBuffers)}]},[i]),z=a.useCallback(async D=>{m(D);try{await sn({vitestAutoKillEnabled:D}),k(null)}catch(T){k(T instanceof Error?T.message:"Failed to save vitest settings")}},[]),A=a.useCallback(async D=>{const T=Math.min(99,Math.max(50,Number.isFinite(D)?Math.round(D):90));g(T);try{await sn({vitestKillThresholdPct:T}),k(null)}catch(w){k(w instanceof Error?w.message:"Failed to save vitest settings")}},[]),P=a.useCallback(async()=>{if(!p){if(!x){v(!0);return}f(!0);try{const D=await $k(s);y(D),v(!1),await M({preserveKillResult:!0})}catch(D){u(D instanceof Error?D.message:"Failed to kill vitest processes")}finally{f(!1)}}},[x,p,M,s]);if(!e)return null;const F=i?.systemStats,W=o&&!!i,$=R?`Updated ${new Date(R).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`:"Waiting for first update",_=i?.taskStats,I=F?F.systemTotalMem-F.systemFreeMem:0,O=F?tc(OR(I,F.systemTotalMem)):"",J=i?.vitestProcessCount,Q=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":"",E=UR(i?.vitestLastAutoKillAt);return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"system-stats-modal-title",onClick:D=>{D.target===D.currentTarget&&n()},"data-testid":"system-stats-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg system-stats-modal","data-testid":"system-stats-modal",children:[t.jsxs("div",{className:"modal-header system-stats-modal__header",children:[t.jsxs("h2",{id:"system-stats-modal-title",className:"system-stats-modal__title",children:[t.jsx(dr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("div",{className:"system-stats-modal__header-actions",children:[t.jsxs("span",{className:"system-stats-modal__auto-refresh","aria-live":"polite",children:[t.jsx("span",{children:"Auto-refresh · 5s"}),t.jsx("span",{className:"system-stats-modal__auto-refresh-time",children:$})]}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void M(),title:"Refresh","aria-label":"Refresh system stats",children:t.jsx(Nn,{size:16,className:W?"system-stats-modal__refresh--spinning":void 0})}),t.jsx("button",{type:"button",className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Ot,{})})]})]}),o&&!i&&t.jsx("div",{className:"system-stats-modal__state",children:"Loading system stats…"}),c&&!i&&t.jsx("div",{className:"system-stats-modal__state system-stats-modal__state--error",role:"alert",children:c}),i&&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:C.map(D=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:D.label}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${D.className}`.trim(),children:D.value}),D.detail?t.jsx("span",{className:"system-stats-modal__detail",children:D.detail}):null]})]},D.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",children:[t.jsx("dt",{children:"Load Avg"}),t.jsx("dd",{children:F?.loadAvg.map(D=>D.toFixed(2)).join(" ")??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Cores"}),t.jsx("dd",{children:F?.cpuCount??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Platform"}),t.jsx("dd",{children:F?.platform??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Node"}),t.jsx("dd",{children:F?.nodeVersion??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"PID"}),t.jsx("dd",{children:F?.pid??"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"System memory stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"System"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Used"}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${O}`.trim(),children:F?ai(I):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:F?`${uh(I,F.systemTotalMem)} of ${ai(F.systemTotalMem)}`:""})]})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Free"}),t.jsx("dd",{children:F?ai(F.systemFreeMem):"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Task stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Tasks"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Total"}),t.jsx("dd",{children:_?.total??0})]}),Object.entries(_?.byColumn??{}).map(([D,T])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:D}),t.jsx("dd",{children:T})]},D))]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Agent stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Agents"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"idle"}),t.jsx("dd",{children:_?.agents.idle??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"active"}),t.jsx("dd",{children:_?.agents.active??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"running"}),t.jsx("dd",{children:_?.agents.running??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"error"}),t.jsx("dd",{children:_?.agents.error??0})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Vitest controls",children:[t.jsxs("h3",{className:"system-stats-modal__section-title system-stats-modal__section-title--with-icon",children:[t.jsx(Tb,{}),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:J??"—"})]})}),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 P(),disabled:p||J===0,children:[t.jsx(Db,{}),t.jsx("span",{children:x?"Confirm Kill?":"Kill Vitest Processes"})]})}),t.jsxs("label",{className:"system-stats-modal__toggle-row",children:[t.jsx("input",{type:"checkbox",checked:d,onChange:D=>{z(D.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:D=>{const T=Number.parseInt(D.target.value,10);A(Number.isNaN(T)?90:T)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:h,"aria-label":"Kill threshold (%)",onChange:D=>{const T=Number.parseInt(D.target.value,10);A(Number.isNaN(T)?90:T)},onBlur:()=>{A(h)}})]})]}),b&&t.jsxs("p",{className:Q,children:["Killed ",b.killed," processes"]}),t.jsxs("p",{className:"system-stats-modal__last-kill",children:["Last auto-kill: ",E]}),S&&t.jsx("p",{className:"system-stats-modal__kill-result system-stats-modal__kill-result--error",children:S})]})]})]}),c&&i&&t.jsxs("div",{className:"system-stats-modal__footer-error",children:["Latest refresh failed: ",c]})]})})}const HR=5e3;function qR(e={}){const{projectId:n,type:s,limit:i=50,autoRefresh:r=!0,useCentralFeed:o=!1}=e,[l,c]=a.useState([]),[u,d]=a.useState(!1),[m,h]=a.useState(null),[g,p]=a.useState(!1),f=a.useRef(null),x=a.useRef(void 0),v=a.useCallback(async()=>{try{d(!0),h(null);let S;o?S=await Jd({limit:i,projectId:n,type:s}):S=(await Hd({limit:i,type:s,projectId:n})).map(R=>({...R,projectId:n??"",projectName:""})),c(S),p(S.length===i),S.length>0&&(x.current=S[S.length-1].timestamp)}catch(S){h(S instanceof Error?S.message:"Failed to load activity log")}finally{d(!1)}},[i,n,s,o]),b=a.useCallback(async()=>{if(x.current)try{d(!0);let S;o?S=await Jd({limit:i,projectId:n,type:s,since:x.current}):S=(await Hd({limit:i,type:s,since:x.current,projectId:n})).map(R=>({...R,projectId:n??"",projectName:""})),c(k=>[...k,...S]),p(S.length===i),S.length>0&&(x.current=S[S.length-1].timestamp)}catch(S){h(S instanceof Error?S.message:"Failed to load more entries")}finally{d(!1)}},[i,n,s,o]),y=a.useCallback(()=>{c([]),p(!1),x.current=void 0},[]);return a.useEffect(()=>{v()},[v]),a.useEffect(()=>{if(r)return f.current=setInterval(()=>{v()},HR),()=>{f.current&&(clearInterval(f.current),f.current=null)}},[r,v]),{entries:l,loading:u,error:m,refresh:v,clear:y,hasMore:g,loadMore:b}}const nc={"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"},VR={"task:created":t.jsx(Zt,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(br,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(Nn,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(Ot,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(dn,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(vr,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(sr,{size:14,className:"activity-icon settings"})};function WR(e){const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),o=Math.floor(i/36e5),l=Math.floor(i/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 KR({isOpen:e,onClose:n,tasks:s,onOpenTaskDetail:i,projectId:r,projects:o=[],onProjectFilterChange:l,currentProject:c}){const[u,d]=a.useState("all"),[m,h]=a.useState(r||"all"),[g,p]=a.useState(!1);a.useEffect(()=>{h(r||"all")},[r]);const f=u==="all"?void 0:u,x=m==="all"?void 0:m,v=!c&&o.length>0,{entries:b,loading:y,error:S,refresh:k,hasMore:R}=qR({projectId:x,type:f,limit:100,autoRefresh:e,useCentralFeed:v}),N=b.map(P=>({id:P.id,timestamp:P.timestamp,type:P.type,taskId:P.taskId,taskTitle:P.taskTitle,details:P.details,metadata:P.metadata,projectId:P.projectId,projectName:P.projectName})),M=async()=>{try{await ck(),k(),p(!1)}catch{p(!1)}},C=P=>{i&&i(P)},z=P=>{h(P),l?.(P==="all"?void 0:P)};a.useEffect(()=>{if(!e)return;const P=F=>{F.key==="Escape"&&(g?p(!1):n())};return document.addEventListener("keydown",P),()=>document.removeEventListener("keydown",P)},[e,n,g]);const A=u!=="all"||m!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:P=>{P.target===P.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(cr,{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(In,{size:14}),t.jsxs("select",{value:m,onChange:P=>z(P.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map(P=>t.jsx("option",{value:P.id,children:P.name},P.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(uo,{size:14}),t.jsxs("select",{value:u,onChange:P=>d(P.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(nc).map(([P,F])=>t.jsx("option",{value:P,children:F},P))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>k(),title:"Refresh","data-testid":"activity-refresh",children:y?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Nn,{size:14})}),N.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:t.jsx(Xt,{size:14})})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",title:"Close","data-testid":"activity-close",children:"×"})]}),A&&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(P=>P.id===m)?.name||m]}),u!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",nc[u]]}),t.jsx("button",{className:"activity-log-clear-filters",onClick:()=>{d("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(Xn,{size:16}),t.jsx("span",{children:S})]}),N.length===0&&!y&&!S&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(cr,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:A?"No activity matches the current filters":"No activity recorded yet"}),A&&t.jsx("button",{className:"btn btn-secondary",onClick:()=>{d("all"),h("all"),l?.(void 0)},children:"Clear Filters"})]}),t.jsx("div",{className:"activity-log-list",children:N.map(P=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:VR[P.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:nc[P.type]}),t.jsx("span",{className:"activity-log-entry-time",children:WR(P.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[P.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>C(P.taskId),"data-testid":"activity-task-link",children:P.taskId}),P.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:P.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:P.details})]}),P.metadata&&Object.keys(P.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof P.metadata.from=="string"&&typeof P.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[P.metadata.from," → ",P.metadata.to]}),typeof P.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${P.metadata.merged?"success":"error"}`,children:P.metadata.merged?"Merged":"Not merged"})]})]})]},P.id))}),R&&!y&&t.jsx("button",{className:"activity-log-load-more",onClick:k,"data-testid":"activity-load-more",children:"Load More"}),y&&N.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(ot,{size:20,className:"spin"})})]}),g&&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:M,children:"Clear Log"})]})]})})]})}):null}const Ka=[{id:"status",label:"Status",icon:Wh},{id:"changes",label:"Changes",icon:Oh},{id:"commits",label:"Commits",icon:lr},{id:"branches",label:"Branches",icon:Js},{id:"worktrees",label:"Worktrees",icon:Dx},{id:"stashes",label:"Stashes",icon:Mo},{id:"remotes",label:"Remotes",icon:Hh}];function mh({status:e}){switch(e){case"added":case"untracked":return t.jsx(xx,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(Uh,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(px,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(Oi,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(vx,{size:14,className:"gm-file-icon"})}}function hh({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 GR(e){return a.useCallback(async(n,s)=>{try{await navigator.clipboard.writeText(n),e(`Copied ${s||"to clipboard"}`,"success")}catch{e("Failed to copy","error")}},[e])}function ba(e){if(!e)return"—";const n=new Date(e);if(isNaN(n.getTime()))return"—";const i=new Date().getTime()-n.getTime(),r=Math.floor(i/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 JR({isOpen:e,onClose:n,tasks:s,addToast:i,projectId:r}){const o=Ds(),[l,c]=a.useState("status"),[u,d]=a.useState(!1),[m,h]=a.useState(null),g=a.useRef(null);Xs(g,e,"fusion:git-modal-size");const p=wi(n),f=GR(i),[x,v]=a.useState(null),[b,y]=a.useState([]),[S,k]=a.useState(new Set),[R,N]=a.useState(""),[M,C]=a.useState(!1),[z,A]=a.useState(null),[P,F]=a.useState(!1),[W,$]=a.useState(null),[_,I]=a.useState(null),O=a.useRef(0),[J,Q]=a.useState([]),[E,D]=a.useState(null),[T,w]=a.useState(null),[q,G]=a.useState(!1),[me,ce]=a.useState(20),[ae,pe]=a.useState(""),[U,Ne]=a.useState([]),[ne,xe]=a.useState(""),[le,ve]=a.useState(""),[ee,Ee]=a.useState(""),[Fe,Ke]=a.useState(null),[Ze,Xe]=a.useState([]),[Qe,it]=a.useState(!1),[Ie,Ge]=a.useState(null),[se,ye]=a.useState(null),[Z,Te]=a.useState(!1),[ze,be]=a.useState([]),[Me,Be]=a.useState([]),[lt,je]=a.useState(""),[ie,Ae]=a.useState(null),[he,Re]=a.useState(null),[Je,$e]=a.useState(null),de=a.useCallback(async()=>{if(e){d(!0),h(null);try{switch(l){case"status":{const B=await Ps(r);v(B);break}case"changes":{const[B,ge]=await Promise.all([Ps(r),Xi(r)]);v(B),y(ge),k(new Set),I(null),A(null),$(null);break}case"commits":{const B=await fy(me,r);Q(B);break}case"branches":{const[B,ge]=await Promise.all([Pa(r),Ps(r)]);Ne(B),v(ge);break}case"worktrees":{const B=await vy(r);be(B);break}case"stashes":{const B=await Or(r);Be(B);break}case"remotes":{const B=await Ps(r);v(B);break}}}catch(B){h(ke(B)||"Failed to fetch git data"),i(ke(B)||"Failed to fetch git data","error")}finally{d(!1)}}},[l,e,me,i,r]);a.useEffect(()=>{e&&de()},[de,e]),a.useEffect(()=>{if(!e)return;const B=ge=>{if(ge.key==="Escape"){n();return}if((ge.key==="ArrowUp"||ge.key==="ArrowDown")&&ge.altKey){ge.preventDefault();const te=Ka.findIndex(j=>j.id===l);ge.key==="ArrowUp"&&te>0?c(Ka[te-1].id):ge.key==="ArrowDown"&&te<Ka.length-1&&c(Ka[te+1].id)}};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[e,n,l]);const re=a.useCallback(async B=>{try{await zd(B,r),i(`Staged ${B.length} file(s)`,"success");const ge=await Xi(r);y(ge),k(new Set),I(null),A(null),$(null)}catch(ge){i(ke(ge)||"Failed to stage files","error")}},[i,r]),ue=a.useCallback(async B=>{try{await My(B,r),i(`Unstaged ${B.length} file(s)`,"success");const ge=await Xi(r);y(ge),k(new Set),I(null),A(null),$(null)}catch(ge){i(ke(ge)||"Failed to unstage files","error")}},[i,r]),Pe=a.useCallback(async B=>{if(await o.confirm({title:"Discard Changes",message:`Discard changes to ${B.length} file(s)? This cannot be undone.`,danger:!0}))try{await Ay(B,r),i(`Discarded changes to ${B.length} file(s)`,"success");const[te,j]=await Promise.all([Xi(r),Ps(r)]);y(te),v(j),k(new Set),I(null),A(null),$(null)}catch(te){i(ke(te)||"Failed to discard changes","error")}},[i,r,confirm]),Se=a.useCallback(async B=>{if(B.preventDefault(),!!R.trim()){C(!0);try{const ge=await Fd(R.trim(),r);i(`Committed: ${ge.hash}`,"success"),N("");const[te,j]=await Promise.all([Xi(r),Ps(r)]);y(te),v(j),I(null),A(null),$(null)}catch(ge){i(ke(ge)||"Failed to commit","error")}finally{C(!1)}}},[R,i,r]),fe=a.useCallback(async()=>{if(R.trim()){C(!0);try{const B=b.filter(V=>!V.staged).map(V=>V.file);B.length>0&&await zd(B,r);const ge=await Fd(R.trim(),r);i(`Committed: ${ge.hash}`,"success"),N("");const[te,j]=await Promise.all([Xi(r),Ps(r)]);y(te),v(j),I(null),A(null),$(null)}catch(B){i(ke(B)||"Failed to commit","error")}finally{C(!1)}}},[R,b,i,r]),tt=a.useCallback(async(B,ge)=>{I({file:B,staged:ge}),F(!0),$(null);const te=O.current+1;O.current=te;try{const j=await _y(B,ge,r);if(O.current!==te)return;A(j)}catch(j){if(O.current!==te)return;const V=ke(j)||"Failed to load file diff";A(null),$(V),i(V,"error")}finally{O.current===te&&F(!1)}},[i,r]),ut=a.useCallback(B=>{k(ge=>{const te=new Set(ge);return te.has(B)?te.delete(B):te.add(B),te})},[]),vt=a.useCallback(async B=>{if(E===B){D(null),w(null);return}D(B),G(!0);try{const ge=await go(B,r);w(ge)}catch(ge){i(ke(ge)||"Failed to load diff","error"),w(null)}finally{G(!1)}},[E,i,r]),gt=a.useCallback(()=>{ce(B=>Math.min(B+20,100))},[]),dt=a.useMemo(()=>{if(!ae.trim())return J;const B=ae.toLowerCase();return J.filter(ge=>ge.message.toLowerCase().includes(B)||ge.author.toLowerCase().includes(B)||ge.shortHash.toLowerCase().includes(B))},[J,ae]),wt=a.useCallback(async B=>{if(B.preventDefault(),!!ne.trim()){d(!0);try{await yy(ne.trim(),le.trim()||void 0,r),i(`Created branch ${ne}`,"success"),xe(""),ve("");const ge=await Pa(r);Ne(ge)}catch(ge){i(ke(ge)||"Failed to create branch","error")}finally{d(!1)}}},[ne,le,i,r]),Mt=a.useCallback(async B=>{d(!0);try{await ky(B,r),i(`Switched to ${B}`,"success");const[ge,te]=await Promise.all([Ps(r),Pa(r)]);v(ge),Ne(te)}catch(ge){i(ke(ge)||"Failed to checkout branch","error")}finally{d(!1)}},[i,r]),yt=a.useCallback(async B=>{if(await o.confirm({title:"Delete Branch",message:`Delete branch "${B}"?`,danger:!0})){d(!0);try{await Ld(B,void 0,r),i(`Deleted branch ${B}`,"success");const te=await Pa(r);Ne(te)}catch(te){if(ke(te).includes("not fully merged")){if(await o.confirm({title:"Force Delete Branch",message:"Branch has unmerged commits. Force delete?",danger:!0}))try{await Ld(B,!0,r),i(`Force deleted branch ${B}`,"success");const V=await Pa(r);Ne(V)}catch(V){i(ke(V)||"Failed to delete branch","error")}}else i(ke(te)||"Failed to delete branch","error")}finally{d(!1)}}},[i,r,confirm]),Et=a.useMemo(()=>{if(!ee.trim())return U;const B=ee.toLowerCase();return U.filter(ge=>ge.name.toLowerCase().includes(B))},[U,ee]),Nt=a.useCallback(async B=>{if(Fe===B){Ke(null),Xe([]),Ge(null),ye(null);return}Ke(B),Xe([]),Ge(null),ye(null),it(!0);try{const ge=await by(B,10,r);Xe(ge)}catch{Xe([])}finally{it(!1)}},[Fe,r]),Tt=a.useCallback(async B=>{if(Ie===B){Ge(null),ye(null);return}Ge(B),ye(null),Te(!0);try{const ge=await go(B,r);ye(ge)}catch{ye(null)}finally{Te(!1)}},[Ie,r]),Ht=a.useCallback(()=>{Ke(null),Xe([]),Ge(null),ye(null)},[]),Ut=a.useCallback(async B=>{B.preventDefault(),Ae("create");try{await Sy(lt.trim()||void 0,r),i("Changes stashed","success"),je("");const ge=await Or(r);Be(ge)}catch(ge){i(ke(ge)||"Failed to stash changes","error")}finally{Ae(null)}},[lt,i,r]),Vt=a.useCallback(async(B,ge=!1)=>{Ae(`apply-${B}`);try{await Cy(B,ge,r),i(ge?"Stash popped":"Stash applied","success");const te=await Or(r);Be(te)}catch(te){i(ke(te)||"Failed to apply stash","error")}finally{Ae(null)}},[i,r]),zt=a.useCallback(async B=>{if(await o.confirm({title:"Drop Stash",message:`Drop stash@{${B}}? This cannot be undone.`,danger:!0})){Ae(`drop-${B}`);try{await Ey(B,r),i("Stash dropped","success");const te=await Or(r);Be(te)}catch(te){i(ke(te)||"Failed to drop stash","error")}finally{Ae(null)}}},[i,r,confirm]),Ct=a.useCallback(async()=>{Re("fetch");try{const B=await jy(void 0,r);$e(B),i(B.message||"Fetch completed",B.fetched?"success":"info");const ge=await Ps(r);v(ge)}catch(B){i(ke(B)||"Fetch failed","error")}finally{Re(null)}},[i,r]),At=a.useCallback(async()=>{Re("pull");try{const B=await wy(r);$e(B),B.conflict?i("Merge conflict detected. Resolve manually.","error"):i(B.message||"Pull completed","success");const ge=await Ps(r);v(ge)}catch(B){i(ke(B)||"Pull failed","error")}finally{Re(null)}},[i,r]),kt=a.useCallback(async()=>{Re("push");try{const B=await Ny(r);$e(B),i(B.message||"Push completed","success");const ge=await Ps(r);v(ge)}catch(B){i(ke(B)||"Push failed","error")}finally{Re(null)}},[i,r]),Kt=a.useMemo(()=>b.filter(B=>B.staged),[b]),$t=a.useMemo(()=>b.filter(B=>!B.staged),[b]);return e?t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal gm-modal",ref:g,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h3",{children:[t.jsx(fc,{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:de,disabled:u,title:"Refresh",children:t.jsx(Nn,{size:14,className:u?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Ot,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:Ka.map(B=>{const ge=B.icon;return t.jsxs("button",{role:"tab","aria-selected":l===B.id,className:`gm-nav-item${l===B.id?" active":""}`,onClick:()=>c(B.id),children:[t.jsx(ge,{size:16}),t.jsx("span",{className:"gm-nav-label",children:B.label})]},B.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[u&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(ot,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),m&&!u&&t.jsxs("div",{className:"gm-error",children:[t.jsx(Xn,{size:18}),t.jsx("span",{children:m}),t.jsx("button",{className:"btn btn-sm",onClick:de,children:"Retry"})]}),l==="status"&&!u&&x&&t.jsx(YR,{status:x,copyToClipboard:f}),l==="changes"&&!u&&t.jsx(QR,{status:x,stagedFiles:Kt,unstagedFiles:$t,selectedFiles:S,toggleFileSelection:ut,onStageFiles:re,onUnstageFiles:ue,onDiscardChanges:Pe,onSelectDiffFile:tt,selectedDiffTarget:_,changeDiff:z,loadingChangeDiff:P,changeDiffError:W,commitMessage:R,setCommitMessage:N,onCommit:Se,onStageAllAndCommit:fe,committing:M}),l==="commits"&&!u&&t.jsx(XR,{commits:dt,commitSearch:ae,setCommitSearch:pe,selectedCommit:E,commitDiff:T,loadingDiff:q,onCommitClick:vt,onLoadMore:gt,canLoadMore:J.length>=me&&me<100,copyToClipboard:f}),l==="branches"&&!u&&t.jsx(ZR,{branches:Et,branchSearch:ee,setBranchSearch:Ee,newBranchName:ne,setNewBranchName:xe,branchBase:le,setBranchBase:ve,onCreateBranch:wt,onCheckoutBranch:Mt,onDeleteBranch:yt,loading:u,allBranches:U,selectedBranch:Fe,branchCommits:Ze,loadingBranchCommits:Qe,expandedBranchCommit:Ie,branchCommitDiff:se,loadingBranchCommitDiff:Z,onSelectBranch:Nt,onBranchCommitClick:Tt,onCloseBranchDetails:Ht}),l==="worktrees"&&!u&&t.jsx(e4,{worktrees:ze}),l==="stashes"&&!u&&t.jsx(t4,{stashes:Me,stashMessage:lt,setStashMessage:je,onCreateStash:Ut,onApplyStash:Vt,onDropStash:zt,stashLoading:ie}),l==="remotes"&&!u&&t.jsx(n4,{status:x,remoteLoading:he,lastRemoteResult:Je,onFetch:Ct,onPull:At,onPush:kt,addToast:i,projectId:r,copyToClipboard:f})]})]})]})}):null}function YR({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(Js,{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(Fi,{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(Xn,{size:12}),"Modified"]}):t.jsxs(t.Fragment,{children:[t.jsx(dn,{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(Li,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx(xr,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(dn,{size:12}),"Up to date"]})]})]})]})]})}function QR({status:e,stagedFiles:n,unstagedFiles:s,selectedFiles:i,toggleFileSelection:r,onStageFiles:o,onUnstageFiles:l,onDiscardChanges:c,onSelectDiffFile:u,selectedDiffTarget:d,changeDiff:m,loadingChangeDiff:h,changeDiffError:g,commitMessage:p,setCommitMessage:f,onCommit:x,onStageAllAndCommit:v,committing:b}){const y=s.filter(k=>i.has(`unstaged:${k.file}`)),S=n.filter(k=>i.has(`staged:${k.file}`));return t.jsxs("div",{className:"gm-panel","data-testid":"changes-panel",children:[e&&t.jsxs("div",{className:"gm-changes-header",children:[t.jsxs("span",{className:"gm-branch-indicator",children:[t.jsx(Js,{size:14}),e.branch]}),e.isDirty&&t.jsx("span",{className:"gm-dirty-badge",children:"Modified"})]}),t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Unstaged Changes (",s.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[y.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(y.map(k=>k.file)),title:"Stage selected",children:[t.jsx(Zt,{size:12})," Stage (",y.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(y.map(k=>k.file)),title:"Discard selected",children:t.jsx(vr,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(k=>k.file)),title:"Stage all",children:"Stage All"})]})]}),t.jsx("div",{className:"gm-file-list",children:s.length===0?t.jsx("div",{className:"gm-empty",children:"No unstaged changes"}):s.map(k=>{const R=d?.file===k.file&&d.staged===!1;return t.jsxs("div",{className:`gm-file-item${R?" active":""}`,onClick:()=>u(k.file,!1),role:"button",tabIndex:0,onKeyDown:N=>{(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),u(k.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:N=>N.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`unstaged:${k.file}`),onChange:()=>r(`unstaged:${k.file}`)})}),t.jsx(mh,{status:k.status}),t.jsx("span",{className:"gm-file-name",title:k.file,children:k.file}),t.jsx(hh,{status:k.status}),t.jsx("button",{className:"gm-icon-btn",onClick:N=>{N.stopPropagation(),o([k.file])},title:"Stage file",children:t.jsx(Zt,{size:12})})]},`unstaged:${k.file}`)})})]}),t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Staged Changes (",n.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[S.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(S.map(k=>k.file)),title:"Unstage selected",children:["Unstage (",S.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(k=>k.file)),title:"Unstage all",children:"Unstage All"})]})]}),t.jsx("div",{className:"gm-file-list",children:n.length===0?t.jsx("div",{className:"gm-empty",children:"No staged changes"}):n.map(k=>{const R=d?.file===k.file&&d.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${R?" active":""}`,onClick:()=>u(k.file,!0),role:"button",tabIndex:0,onKeyDown:N=>{(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),u(k.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:N=>N.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`staged:${k.file}`),onChange:()=>r(`staged:${k.file}`)})}),t.jsx(mh,{status:k.status}),t.jsx("span",{className:"gm-file-name",title:k.file,children:k.file}),t.jsx(hh,{status:k.status}),t.jsx("button",{className:"gm-icon-btn",onClick:N=>{N.stopPropagation(),l([k.file])},title:"Unstage file",children:t.jsx(Ot,{size:12})})]},`staged:${k.file}`)})})]}),(d||h||m||g)&&t.jsxs("div",{className:"gm-diff-section",children:[d&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(Oh,{size:14}),t.jsxs("span",{children:[d.staged?"Staged":"Unstaged"," diff: "]}),t.jsx("code",{children:d.file})]}),h&&t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(ot,{size:16,className:"spin"}),"Loading diff..."]}),g&&!h&&t.jsx("div",{className:"gm-diff-error",children:g}),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("form",{className:"gm-commit-form",onSubmit:x,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:k=>f(k.target.value),rows:3,disabled:b}),t.jsxs("div",{className:"gm-commit-actions",children:[t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:b||!p.trim()||n.length===0,title:n.length===0?"No staged changes to commit":"Commit staged changes",children:[b?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Di,{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 XR({commits:e,commitSearch:n,setCommitSearch:s,selectedCommit:i,commitDiff:r,loadingDiff:o,onCommitClick:l,onLoadMore:c,canLoadMore:u,copyToClipboard:d}){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(oa,{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:ba(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:()=>d(m.hash,"commit hash"),title:"Copy full hash",children:t.jsx(Fi,{size:12})})}),i===m.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(ot,{size:16,className:"spin"}),"Loading diff..."]}):r?t.jsxs(t.Fragment,{children:[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))}),u&&t.jsx("button",{className:"gm-load-more",onClick:c,children:"Load more commits"})]})}function ZR({branches:e,branchSearch:n,setBranchSearch:s,newBranchName:i,setNewBranchName:r,branchBase:o,setBranchBase:l,onCreateBranch:c,onCheckoutBranch:u,onDeleteBranch:d,loading:m,allBranches:h,selectedBranch:g,branchCommits:p,loadingBranchCommits:f,expandedBranchCommit:x,branchCommitDiff:v,loadingBranchCommitDiff:b,onSelectBranch:y,onBranchCommitClick:S,onCloseBranchDetails:k}){return t.jsxs("div",{className:"gm-panel","data-testid":"branches-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Branches"}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(oa,{size:14}),t.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:R=>s(R.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:c,children:[t.jsx("input",{type:"text",placeholder:"New branch name",value:i,onChange:R=>r(R.target.value),disabled:m}),t.jsxs("select",{value:o,onChange:R=>l(R.target.value),disabled:m,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:"Base: HEAD"}),h.map(R=>t.jsx("option",{value:R.name,children:R.name},R.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:m||!i.trim(),children:[t.jsx(Zt,{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(R=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${R.isCurrent?" current":""}${g===R.name?" selected":""}`,onClick:()=>y(R.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[R.isCurrent&&t.jsx(Mn,{size:14,className:"gm-current-icon"}),R.name]}),R.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",R.remote]}),R.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:ba(R.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!R.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:N=>{N.stopPropagation(),u(R.name)},disabled:m,title:"Checkout",children:t.jsx(Js,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:N=>{N.stopPropagation(),d(R.name)},disabled:m,title:"Delete",children:t.jsx(Xt,{size:14})})]})})]}),g===R.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(lr,{size:14}),"Commits on ",R.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:k,title:"Close","data-testid":"close-branch-details",children:t.jsx(Ot,{size:14})})]}),f?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(ot,{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(N=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>S(N.hash),"data-testid":`branch-commit-${N.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:N.shortHash}),t.jsx("span",{className:"gm-commit-message",title:N.message,children:N.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:N.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:ba(N.date)}),N.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),x===N.hash&&t.jsx("div",{className:"gm-commit-diff",children:b?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(ot,{size:16,className:"spin"}),"Loading diff..."]}):v?t.jsxs(t.Fragment,{children:[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"})})]},N.hash))})]})]},R.name))})]})}function e4({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:n.path.split("/").pop()||n.path})]}),t.jsxs("div",{className:"gm-worktree-detail",children:[n.branch&&t.jsxs("span",{className:"gm-worktree-branch",children:[t.jsx(Js,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function t4({stashes:e,stashMessage:n,setStashMessage:s,onCreateStash:i,onApplyStash:r,onDropStash:o,stashLoading:l}){return t.jsxs("div",{className:"gm-panel","data-testid":"stashes-panel",children:[t.jsx("div",{className:"gm-panel-header",children:t.jsx("h4",{children:"Stashes"})}),t.jsxs("form",{className:"gm-create-form",onSubmit:i,children:[t.jsx("input",{type:"text",placeholder:"Stash message (optional)",value:n,onChange:c=>s(c.target.value),disabled:l!==null}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:l!==null,children:[l==="create"?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Mo,{size:14}),"Stash"]})]}),t.jsx("div",{className:"gm-stash-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:"No stashes"}):e.map(c=>t.jsxs("div",{className:"gm-stash-item",children:[t.jsxs("div",{className:"gm-stash-info",children:[t.jsxs("span",{className:"gm-stash-ref",children:["stash@",`{${c.index}}`]}),t.jsx("span",{className:"gm-stash-message",children:c.message}),t.jsxs("div",{className:"gm-stash-meta",children:[c.branch&&t.jsxs("span",{className:"gm-stash-branch",children:[t.jsx(Js,{size:12}),c.branch]}),t.jsx("span",{children:ba(c.date)})]})]}),t.jsxs("div",{className:"gm-stash-actions",children:[t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>r(c.index,!1),disabled:l!==null,title:"Apply stash (keep)",children:l===`apply-${c.index}`?t.jsx(ot,{size:14,className:"spin"}):"Apply"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>r(c.index,!0),disabled:l!==null,title:"Pop stash (apply and drop)",children:"Pop"}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>o(c.index),disabled:l!==null,title:"Drop stash",children:l===`drop-${c.index}`?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Xt,{size:14})})]})]},c.index))})]})}function n4({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:i,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:u}){const d=Z=>{try{return new URL(Z).hostname}catch{return Z.replace(/^git@/,"").split(":")[0]||Z}},[m,h]=a.useState([]),[g,p]=a.useState(!1),[f,x]=a.useState(null),[v,b]=a.useState(""),[y,S]=a.useState(""),[k,R]=a.useState(null),[N,M]=a.useState(""),[C,z]=a.useState(""),[A,P]=a.useState(!1),[F,W]=a.useState([]),[$,_]=a.useState(!1),[I,O]=a.useState(null),[J,Q]=a.useState([]),[E,D]=a.useState(!1),[T,w]=a.useState(null),q=m.find(Z=>Z.name===I),[G,me]=a.useState(null),[ce,ae]=a.useState(null),[pe,U]=a.useState(!1),[Ne,ne]=a.useState(null),[xe,le]=a.useState(null),[ve,ee]=a.useState(!1);a.useEffect(()=>{Ee()},[]),a.useEffect(()=>{e&&e.ahead>0?Fe():e&&e.ahead===0&&W([])},[e?.ahead]),a.useEffect(()=>{m.length>0&&!I&&O(m[0].name)},[m]),a.useEffect(()=>{I?Ke(I):(Q([]),w(null))},[I]),a.useEffect(()=>{I&&!m.find(Z=>Z.name===I)&&O(m.length>0?m[0].name:null)},[m,I]);const Ee=async()=>{p(!0);try{const Z=await ry(c);h(Z)}catch(Z){l(ke(Z)||"Failed to load remotes","error")}finally{p(!1)}},Fe=async()=>{_(!0);try{const Z=await gy(c);W(Z)}catch{W([])}finally{_(!1)}},Ke=async Z=>{D(!0),w(null);try{const Te=await xy(Z,void 0,10,c);Q(Te)}catch(Te){w(ke(Te)||"Failed to load remote commits"),Q([])}finally{D(!1)}},Ze=Ds(),Xe=async Z=>{if(Z.preventDefault(),!(!v.trim()||!y.trim())){x("add");try{await oy(v.trim(),y.trim(),c),l(`Remote '${v}' added successfully`,"success"),b(""),S(""),P(!1),await Ee()}catch(Te){l(ke(Te)||"Failed to add remote","error")}finally{x(null)}}},Qe=async Z=>{if(await Ze.confirm({title:"Remove Remote",message:`Are you sure you want to remove remote '${Z}'?`,danger:!0})){x(`remove-${Z}`);try{await ly(Z,c),l(`Remote '${Z}' removed`,"success"),await Ee()}catch(ze){l(ke(ze)||"Failed to remove remote","error")}finally{x(null)}}},it=async Z=>{if(C.trim()){x(`rename-${Z}`);try{await cy(Z,C.trim(),c),l(`Remote renamed to '${C.trim()}'`,"success"),R(null),z(""),await Ee()}catch(Te){l(ke(Te)||"Failed to rename remote","error")}finally{x(null)}}},Ie=async Z=>{if(N.trim()){x(`url-${Z}`);try{await dy(Z,N.trim(),c),l("Remote URL updated","success"),R(null),M(""),await Ee()}catch(Te){l(ke(Te)||"Failed to update remote URL","error")}finally{x(null)}}},Ge=a.useCallback(async(Z,Te)=>{if(Te==="ahead"){if(G===Z){me(null),ae(null);return}me(Z),ae(null),U(!0);try{const ze=await go(Z);ae(ze)}catch{ae(null)}finally{U(!1)}}else{if(Ne===Z){ne(null),le(null);return}ne(Z),le(null),ee(!0);try{const ze=await go(Z);le(ze)}catch{le(null)}finally{ee(!1)}}},[G,Ne]),se=Z=>{R(`url-${Z.name}`),M(Z.pushUrl||Z.fetchUrl)},ye=Z=>{R(`name-${Z.name}`),z(Z.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:()=>P(!A),disabled:f!==null,title:A?"Cancel":"Add Remote",children:A?t.jsx(Ot,{size:14}):t.jsx(Zt,{size:14})})]}),A&&t.jsxs("form",{className:"gm-remote-form",onSubmit:Xe,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:v,onChange:Z=>b(Z.target.value),disabled:f==="add",className:"gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:y,onChange:Z=>S(Z.target.value),disabled:f==="add",className:"gm-input gm-input-url"}),t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!v.trim()||!y.trim()||f==="add",children:[f==="add"?t.jsx(ot,{size:12,className:"spin"}):t.jsx(Zt,{size:12}),"Add"]})]}),g?t.jsxs("div",{className:"gm-loading",children:[t.jsx(ot,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(Z=>t.jsxs("div",{className:`gm-remote-selector-item${I===Z.name?" selected":""}`,onClick:()=>O(Z.name),role:"button",tabIndex:0,children:[t.jsxs("div",{className:"gm-remote-selector-info",children:[t.jsxs("span",{className:"gm-remote-selector-name",children:[Z.name,Z.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",children:d(Z.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:Te=>{Te.stopPropagation(),Qe(Z.name)},disabled:f!==null,title:"Remove remote",children:t.jsx(Xt,{size:14})})]},Z.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[I&&q?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:I}),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(Li,{size:14}),e.ahead," to push"]}),e.behind>0&&t.jsxs("div",{className:"gm-remote-indicator behind",children:[t.jsx(xr,{size:14}),e.behind," to pull"]})]})]}),t.jsxs("div",{className:"gm-remote-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:i,disabled:n!==null||g,children:[n==="fetch"?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Nn,{size:14}),"Fetch"]}),t.jsxs("button",{className:"btn btn-primary",onClick:r,disabled:n!==null||g,children:[n==="pull"?t.jsx(ot,{size:14,className:"spin"}):t.jsx(hs,{size:14}),"Pull"]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||g,children:[n==="push"?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Li,{size:14}),"Push"]})]})]}),t.jsxs("div",{className:"gm-remote-detail-card","data-testid":"remote-detail-card",children:[t.jsxs("div",{className:"gm-remote-detail-urls",children:[t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Fetch:"}),k===`url-${I}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:N,onChange:Z=>M(Z.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Ie(I),disabled:f===`url-${I}`,children:f===`url-${I}`?t.jsx(ot,{size:12,className:"spin"}):t.jsx(Mn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{R(null),M("")},title:"Cancel",children:t.jsx(Ot,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:q.fetchUrl,children:q.fetchUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(q.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(Fi,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>se(q),disabled:f!==null,title:"Edit remote URL",children:t.jsx(Yn,{size:14})})]})]}),q.pushUrl&&q.pushUrl!==q.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:q.pushUrl,children:q.pushUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(q.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(Fi,{size:14})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:k===`name-${I}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:C,onChange:Z=>z(Z.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>it(I),disabled:f===`rename-${I}`,children:f===`rename-${I}`?t.jsx(ot,{size:12,className:"spin"}):t.jsx(Mn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{R(null),z("")},title:"Cancel",children:t.jsx(Ot,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>ye(q),disabled:f!==null,title:"Edit remote name",children:t.jsx(Yn,{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(Li,{size:14}),"Commits to Push (",e.ahead,")"]})}),$?t.jsxs("div",{className:"gm-loading",children:[t.jsx(ot,{size:14,className:"spin"}),"Loading..."]}):F.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:F.map(Z=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Ge(Z.hash,"ahead"),role:"button",tabIndex:0,title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:Z.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:Z.message,children:Z.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:Z.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:ba(Z.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:G===Z.hash?t.jsx(qt,{size:14}):t.jsx(hn,{size:14})})]}),G===Z.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:pe?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(ot,{size:16,className:"spin"}),"Loading diff..."]}):ce?t.jsxs(t.Fragment,{children:[Z.message&&t.jsx("div",{className:"gm-commit-message-full",children:Z.message}),ce.stat&&t.jsx("pre",{className:"gm-diff-stat",children:ce.stat}),t.jsx("pre",{className:"gm-diff-patch",children:ce.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},Z.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(Wh,{size:14}),"Recent commits on ",I]})}),E?t.jsxs("div",{className:"gm-loading",children:[t.jsx(ot,{size:14,className:"spin"}),"Loading commits..."]}):T?t.jsxs("div",{className:"gm-error",children:[t.jsx(Xn,{size:14}),T]}):J.length===0?t.jsxs("div",{className:"gm-empty",children:["No commits found on ",I,". Try fetching first."]}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:J.map(Z=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Ge(Z.hash,"remote"),role:"button",tabIndex:0,title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:Z.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:Z.message,children:Z.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:Z.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:ba(Z.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:Ne===Z.hash?t.jsx(qt,{size:14}):t.jsx(hn,{size:14})})]}),Ne===Z.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:ve?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(ot,{size:16,className:"spin"}),"Loading diff..."]}):xe?t.jsxs(t.Fragment,{children:[Z.message&&t.jsx("div",{className:"gm-commit-message-full",children:Z.message}),xe.stat&&t.jsx("pre",{className:"gm-diff-stat",children:xe.stat}),t.jsx("pre",{className:"gm-diff-patch",children:xe.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},Z.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 Ga={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function s4(e,n){return e&&n?`${e}/${n}`:""}function i4(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 a4(e){switch(e){case"file-text":return Oi;case"check-circle":return dn;case"shield":return Ib;case"zap":return Pn;case"eye":return da;case"globe":return To;case"layout-grid":return Bi;default:return dn}}function r4(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 o4({isOpen:e,onClose:n,addToast:s,projectId:i}){const[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState(!0),[m,h]=a.useState(!0),[g,p]=a.useState("my-steps"),[f,x]=a.useState(null),[v,b]=a.useState(!1),[y,S]=a.useState(Ga),[k,R]=a.useState(!1),[N,M]=a.useState(!1),[C,z]=a.useState(null),[A,P]=a.useState(null),[F,W]=a.useState({}),[$,_]=a.useState([]),I=a.useRef(null);Xs(I,e,"fusion:workflow-steps-modal-size");const O=a.useCallback(async()=>{try{d(!0);const U=await zo(i);o(U)}catch(U){s(ke(U)||"Failed to load workflow steps","error")}finally{d(!1)}},[s,i]),J=a.useCallback(async()=>{try{const U=await hr(i);W(U||{})}catch{}},[i]),Q=a.useCallback(async()=>{try{const U=await cs();_(U.models||[])}catch{}},[]),E=a.useCallback(async()=>{try{h(!0);const U=await hk();c(U.templates)}catch(U){s(ke(U)||"Failed to load templates","error")}finally{h(!1)}},[s]);a.useEffect(()=>{e&&(O(),E(),J(),Q())},[e,O,E,J,Q]);const D=a.useCallback(()=>{b(!0),x(null),S(Ga)},[]),T=a.useCallback(U=>{x(U.id),b(!1),S({name:U.name,description:U.description,mode:U.mode||"prompt",phase:U.phase||"pre-merge",prompt:U.prompt,scriptName:U.scriptName||"",enabled:U.enabled,defaultOn:U.defaultOn||!1,modelProvider:U.modelProvider||"",modelId:U.modelId||""})},[]),w=a.useCallback(()=>{x(null),b(!1),S(Ga)},[]),q=a.useCallback(async()=>{if(!y.name.trim()||!y.description.trim()){s("Name and description are required","error");return}R(!0);try{const U=y.mode==="prompt"&&y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:y.mode==="prompt"?{modelProvider:void 0,modelId:void 0}:{};if(v){const Ne={name:y.name.trim(),description:y.description.trim(),mode:y.mode,phase:y.phase,prompt:y.mode==="prompt"&&y.prompt.trim()||void 0,scriptName:y.mode==="script"?y.scriptName.trim():void 0,enabled:y.enabled,defaultOn:y.defaultOn||void 0,...U};await qd(Ne,i),s("Workflow step created","success")}else f&&(await dk(f,{name:y.name.trim(),description:y.description.trim(),mode:y.mode,phase:y.phase,prompt:y.mode==="prompt"?y.prompt:"",scriptName:y.mode==="script"?y.scriptName.trim():void 0,enabled:y.enabled,defaultOn:y.defaultOn,...U},i),s("Workflow step updated","success"));b(!1),x(null),S(Ga),await O()}catch(U){s(ke(U)||"Failed to save workflow step","error")}finally{R(!1)}},[y,v,f,s,O]),G=a.useCallback(async U=>{try{await uk(U,i),s("Workflow step deleted","success"),z(null),f===U&&(x(null),S(Ga)),await O()}catch(Ne){s(ke(Ne)||"Failed to delete workflow step","error")}},[f,s,O]),me=a.useCallback(async()=>{if(!(!f&&!v)&&y.mode==="prompt"){if(v){if(!y.name.trim()||!y.description.trim()){s("Name and description are required before refining","error");return}R(!0);try{const U=y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:{},Ne={name:y.name.trim(),description:y.description.trim(),mode:"prompt",prompt:y.prompt.trim()||void 0,enabled:y.enabled,defaultOn:y.defaultOn||void 0,...U},ne=await qd(Ne,i);b(!1),x(ne.id),M(!0);const xe=await Vd(ne.id,i);S(le=>({...le,prompt:xe.prompt})),s("Prompt refined with AI","success"),await O()}catch(U){s(ke(U)||"Failed to refine prompt","error")}finally{R(!1),M(!1)}return}if(f){M(!0);try{const U=await Vd(f,i);S(Ne=>({...Ne,prompt:U.prompt})),s("Prompt refined with AI","success"),await O()}catch(U){s(ke(U)||"Failed to refine prompt","error")}finally{M(!1)}}}},[f,v,y,s,O]),ce=a.useCallback(async U=>{P(U.id);try{await pk(U.id,i),s(`Added ${U.name} workflow step`,"success"),await O(),p("my-steps")}catch(Ne){const ne=ke(Ne);ne?.includes("already exists")?s(`A workflow step named '${U.name}' already exists`,"error"):s(ne||"Failed to add workflow step from template","error")}finally{P(null)}},[s,O]),ae=wi(n);if(!e)return null;const pe=v||f!==null;return t.jsx("div",{className:"modal-overlay open",...ae,"data-testid":"workflow-step-manager",children:t.jsxs("div",{ref:I,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:u?t.jsx("div",{className:"wfm-loading",children:"Loading..."}):t.jsxs(t.Fragment,{children:[!pe&&t.jsxs("div",{className:"wfm-tab-row",children:[t.jsxs("button",{className:`btn ${g==="my-steps"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>p("my-steps"),"data-testid":"tab-my-steps",children:[t.jsx(_g,{size:14}),"My Workflow Steps (",r.length,")"]}),t.jsxs("button",{className:`btn ${g==="templates"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>p("templates"),"data-testid":"tab-templates",children:[t.jsx(Bi,{size:14}),"Templates (",l.length,")"]})]}),g==="my-steps"&&!pe&&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(U=>t.jsx("div",{className:"wfm-step-card","data-testid":`workflow-step-${U.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:U.name}),t.jsx("span",{className:`wfm-badge ${U.enabled?"wfm-badge-enabled":"wfm-badge-disabled"}`,children:U.enabled?"Enabled":"Disabled"}),t.jsx("span",{className:`wfm-badge ${(U.mode||"prompt")==="script"?"wfm-badge-script":"wfm-badge-prompt"}`,children:(U.mode||"prompt")==="script"?"Script":"AI Prompt"}),t.jsx("span",{className:`wfm-badge ${(U.phase||"pre-merge")==="post-merge"?"wfm-badge-post-merge":"wfm-badge-pre-merge"}`,children:(U.phase||"pre-merge")==="post-merge"?"Post-merge":"Pre-merge"}),U.defaultOn&&t.jsx("span",{className:"wfm-badge wfm-badge-default-on",children:"Default on"})]}),t.jsx("div",{className:"wfm-step-card-desc",children:U.description})]}),t.jsxs("div",{className:"wfm-step-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>T(U),title:"Edit","aria-label":`Edit ${U.name}`,children:t.jsx(Yn,{size:14})}),C===U.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>G(U.id),title:"Confirm delete","aria-label":`Confirm delete ${U.name}`,children:t.jsx(Mn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>z(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(Ot,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>z(U.id),title:"Delete","aria-label":`Delete ${U.name}`,children:t.jsx(Xt,{size:14})})]})]})},U.id))})]}),g==="templates"&&!pe&&t.jsx(t.Fragment,{children:m?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(ot,{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(U=>{const Ne=a4(U.icon),ne=r4(U.category),xe=A===U.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`template-${U.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(Ne,{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:U.name}),t.jsx("span",{className:ne,children:U.category})]}),t.jsx("div",{className:"wfm-template-desc",children:U.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>ce(U),disabled:xe,"data-testid":`add-template-${U.id}`,children:xe?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Zt,{size:12}),"Add"]})})]})]})},U.id)})})}),pe&&t.jsxs("div",{className:"wfm-form","data-testid":"workflow-step-form",children:[t.jsx("h3",{className:"wfm-form-title",children:v?"New Workflow Step":"Edit Workflow Step"}),t.jsxs("div",{className:"wfm-form-fields",children:[t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Name"}),t.jsx("input",{type:"text",value:y.name,onChange:U=>S(Ne=>({...Ne,name:U.target.value})),placeholder:"e.g. Documentation Review","data-testid":"workflow-step-name"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{value:y.description,onChange:U=>S(Ne=>({...Ne,description:U.target.value})),placeholder:"Brief description of what this step does",rows:2,"data-testid":"workflow-step-description"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Mode"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-mode-selector",children:[t.jsxs("button",{className:`btn ${y.mode==="prompt"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>S(U=>({...U,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(bi,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${y.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>S(U=>({...U,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(ri,{size:14}),"Run Script"]})]})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Phase"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-phase-selector",children:[t.jsx("button",{className:`btn ${y.phase==="pre-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>S(U=>({...U,phase:"pre-merge"})),"data-testid":"phase-pre-merge",children:"Pre-merge"}),t.jsx("button",{className:`btn ${y.phase==="post-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>S(U=>({...U,phase:"post-merge"})),"data-testid":"phase-post-merge",children:"Post-merge"})]}),t.jsx("div",{className:"wfm-field-hint",children:y.phase==="pre-merge"?"Runs before merge — can block merge on failure":"Runs after merge success — failures are logged but do not block"})]}),y.mode==="prompt"&&t.jsxs("div",{className:"wfm-field",children:[t.jsxs("div",{className:"wfm-prompt-header",children:[t.jsx("label",{children:"Agent Prompt"}),t.jsxs("button",{className:"btn-icon wfm-refine-btn",onClick:me,disabled:!y.description.trim()||N,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[N?t.jsx(ot,{size:12,className:"spin"}):t.jsx(qn,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:y.prompt,onChange:U=>S(Ne=>({...Ne,prompt:U.target.value})),placeholder:"Leave empty to use AI refinement",rows:6,className:"wfm-prompt-textarea","data-testid":"workflow-step-prompt"})]}),y.mode==="prompt"&&t.jsxs("div",{className:"wfm-field","data-testid":"workflow-step-model-field",children:[t.jsxs("div",{className:"wfm-model-header",children:[t.jsx("label",{children:"Model Override"}),y.modelProvider&&y.modelId&&t.jsxs("button",{type:"button",className:"btn-icon wfm-model-clear-btn",onClick:()=>S(U=>({...U,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(Ot,{size:12}),t.jsx("span",{children:"Use default"})]})]}),t.jsx("span",{className:"wfm-model-hint",children:y.modelProvider&&y.modelId?`Using ${y.modelProvider}/${y.modelId}`:"Using global default model"}),t.jsx("div",{"data-testid":"workflow-step-model-select",children:t.jsx($n,{models:$,value:s4(y.modelProvider,y.modelId),onChange:U=>{const Ne=i4(U);S(ne=>({...ne,modelProvider:Ne.provider,modelId:Ne.modelId}))},placeholder:"Select a model override…",label:"Model override for this workflow step"})})]}),y.mode==="script"&&t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Script"}),Object.keys(F).length===0?t.jsx("div",{className:"wfm-no-scripts","data-testid":"no-scripts-message",children:"No scripts configured. Add scripts in Settings → Scripts first."}):t.jsxs("select",{value:y.scriptName,onChange:U=>S(Ne=>({...Ne,scriptName:U.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(F).map(([U,Ne])=>t.jsxs("option",{value:U,children:[U," (",Ne,")"]},U))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:y.enabled,onChange:U=>S(Ne=>({...Ne,enabled:U.target.checked})),"data-testid":"workflow-step-enabled"}),"Enabled (available for selection on new tasks)"]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:y.defaultOn,onChange:U=>S(Ne=>({...Ne,defaultOn:U.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:w,disabled:k,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:q,disabled:k||!y.name.trim()||!y.description.trim()||y.mode==="script"&&!y.scriptName.trim(),"data-testid":"save-workflow-step",children:k?"Saving...":v?"Create":"Save"})]})]})]})]})}),!pe&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:D,"data-testid":"add-workflow-step",children:[t.jsx(Zt,{size:14}),"Add Workflow Step"]})})]})})}const l4=36e5,c4=3e5,sc=[{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 d4(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 u4(e){return typeof e!="number"||!Number.isFinite(e)?l4:Math.max(c4,Math.round(e))}function jD(e){if(sc.some(s=>s.value===e))return[...sc];const n={value:e,label:`${d4(e)} (custom)`};return[...sc,n].sort((s,i)=>s.value-i.value)}const m4=4,h4=5*6e4;function p4(e){const n=u4(e?.heartbeatIntervalMs);return Math.max(n*m4,h4)}function f4(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 g4(e){const{state:n,lastHeartbeatAt:s,lastError:i,pauseReason:r,runtimeConfig:o}=e,l=f4(e);if(n==="terminated")return{label:"Terminated",icon:t.jsx(ms,{size:14}),color:"var(--state-error-text)",stateDerived:!0};if(n==="error")return{label:i??"Error",icon:t.jsx(Cs,{size:14}),color:"var(--state-error-text)",stateDerived:!i};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(Gs,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(Cs,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(gn,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const c=new Date(s).getTime(),u=Date.now()-c,d=p4(o);return u>d?{label:"Unresponsive",icon:t.jsx(Cs,{size:14}),color:"var(--state-error-text)",stateDerived:!1}:{label:"Healthy",icon:t.jsx(zx,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}const Ja=[{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 x4({isOpen:e,onClose:n,addToast:s,projectId:i}){const[r,o]=a.useState([]),[l,c]=a.useState(!1),[u,d]=a.useState(!1),[m,h]=a.useState(""),[g,p]=a.useState("custom"),[f,x]=a.useState("all"),[v,b]=a.useState(()=>{if(typeof window>"u")return"list";const T=Dn("fn-agent-view",i);return T==="board"||T==="list"?T:"list"});a.useEffect(()=>{const T=Dn("fn-agent-view",i);if(T==="board"||T==="list"){b(T);return}b("list")},[i]),a.useEffect(()=>{os("fn-agent-view",v,i)},[i,v]);const[y,S]=a.useState(null),k=a.useRef(null),[R,N]=a.useState(new Set),[M,C]=a.useState(new Map),{confirm:z}=Ds(),A=a.useMemo(()=>M.size===0?r:r.map(T=>{const w=M.get(T.id);return w?{...T,state:w}:T}),[r,M]),P=a.useMemo(()=>f==="all"?A.filter(T=>T.state!=="terminated"):A,[A,f]),F=a.useCallback(async()=>{c(!0);try{const w=await Na(f!=="all"?{state:f}:void 0,i);o(w)}catch(T){s(`Failed to load agents: ${ke(T)}`,"error")}finally{c(!1)}},[f,s,i]);a.useEffect(()=>{e&&F()},[e,F]),a.useEffect(()=>{if(!e)return;const T=setInterval(()=>{F()},3e4);return()=>{clearInterval(T)}},[e,F]);const W=async()=>{if(m.trim())try{await wk({name:m.trim(),role:g},i),s(`Agent "${m}" created`,"success"),h(""),d(!1),F()}catch(T){s(`Failed to create agent: ${ke(T)}`,"error")}},$=async(T,w)=>{if(!R.has(T)){N(q=>new Set(q).add(T)),C(q=>{const G=new Map(q);return G.set(T,w),G});try{await Sk(T,w,i),s(`Agent state updated to ${w}`,"success"),await F(),C(q=>{const G=new Map(q);return G.delete(T),G})}catch(q){C(G=>{const me=new Map(G);return me.delete(T),me}),s(`Failed to update state: ${ke(q)}`,"error")}finally{N(q=>{const G=new Set(q);return G.delete(T),G})}}},_=async(T,w)=>{if(await z({title:"Delete Agent",message:`Delete agent "${w}"? This cannot be undone.`,danger:!0}))try{await Ck(T,i),s(`Agent "${w}" deleted`,"success"),F()}catch(G){s(`Failed to delete agent: ${ke(G)}`,"error")}},I=async(T,w)=>{const q=r.find(G=>G.id===T);if(q){if(q.role===w){S(null);return}try{await Nk(T,{role:w},i),s(`Agent role updated to ${Ja.find(G=>G.value===w)?.label??w}`,"success"),S(null),F()}catch(G){s(`Failed to update role: ${ke(G)}`,"error")}}},O=(T,w)=>{T.key==="Escape"&&S(null)},J=T=>Ja.find(w=>w.value===T)?.label??T,Q=T=>Ja.find(w=>w.value===T)?.icon??"◆",E=T=>g4(T),D=T=>T.color==="var(--state-active-text)"?"active":T.color==="var(--state-paused-text)"?"paused":T.color==="var(--state-error-text)"?"error":"muted";return e?t.jsx("div",{className:"modal-overlay open",onClick:T=>T.target===T.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(gn,{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(Bi,{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(gc,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void F(),title:"Refresh",disabled:l,children:t.jsx(Nn,{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(uo,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:f,onChange:T=>x(T.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.jsx("option",{value:"terminated",children:"Terminated"})]})]}),t.jsxs("button",{className:"btn btn-task-create btn-sm",onClick:()=>d(!u),children:[t.jsx(Zt,{size:16}),u?"Cancel":"New Agent"]})]}),u&&t.jsxs("div",{className:"agent-create-form",children:[t.jsx("input",{type:"text",placeholder:"Agent name...",value:m,onChange:T=>h(T.target.value),onKeyDown:T=>T.key==="Enter"&&W(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:g,onChange:T=>p(T.target.value),children:Ja.map(T=>t.jsxs("option",{value:T.value,children:[T.icon," ",T.label]},T.value))}),t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:()=>void W(),children:"Create"})]}),t.jsx("div",{className:v==="board"?"agent-board":"agent-list",children:P.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(gn,{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"?P.map(T=>{const w=E(T),q=D(w);return t.jsxs("div",{className:"agent-board-card","data-state":T.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:Q(T.role)}),t.jsx("span",{className:"agent-board-badge","data-state":T.state,children:T.state}),t.jsx("span",{className:"agent-board-health","data-health":q,title:w.label,children:w.icon})]}),t.jsx("div",{className:"agent-board-name",title:T.name,children:T.name}),t.jsx("div",{className:"agent-board-id",children:T.id}),t.jsxs("div",{className:"agent-board-actions",children:[T.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"active"),disabled:R.has(T.id),title:"Activate",children:t.jsx(xn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void _(T.id,T.name),title:"Delete",children:t.jsx(Xt,{size:14})})]}),T.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"paused"),disabled:R.has(T.id),title:"Pause",children:t.jsx(Gs,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:t.jsx(ms,{size:14})})]}),T.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"active"),disabled:R.has(T.id),title:"Resume",children:t.jsx(xn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:t.jsx(ms,{size:14})})]}),T.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"paused"),disabled:R.has(T.id),title:"Pause",children:t.jsx(Gs,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:t.jsx(ms,{size:14})})]}),T.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"active"),disabled:R.has(T.id),title:"Retry",children:t.jsx(xn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:t.jsx(ms,{size:14})})]}),T.state==="terminated"&&t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void _(T.id,T.name),title:"Delete",children:t.jsx(Xt,{size:14})})]})]},T.id)}):P.map(T=>{const w=E(T),q=D(w);return t.jsxs("div",{className:"agent-card","data-state":T.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[y===T.id?t.jsx("select",{ref:k,className:"select agent-role-select",value:T.role,onChange:G=>void I(T.id,G.target.value),onKeyDown:G=>O(G,T.id),onBlur:()=>S(null),autoFocus:!0,children:Ja.map(G=>t.jsxs("option",{value:G.value,children:[G.icon," ",G.label]},G.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>S(T.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:G=>{(G.key==="Enter"||G.key===" ")&&S(T.id)},children:Q(T.role)}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:T.name}),t.jsx("span",{className:"agent-id text-secondary",children:T.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":T.state,children:T.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":q,title:w.label,children:[w.icon,!w.stateDerived&&` ${w.label}`]}),t.jsx("span",{className:"badge text-secondary",children:J(T.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[T.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:T.taskId})]}),T.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date(T.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[T.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"active"),disabled:R.has(T.id),title:"Activate",children:[t.jsx(xn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void _(T.id,T.name),title:"Delete",children:[t.jsx(Xt,{size:14})," Delete"]})]}),T.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"paused"),disabled:R.has(T.id),title:"Pause",children:[t.jsx(Gs,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:[t.jsx(ms,{size:14})," Stop"]})]}),T.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"active"),disabled:R.has(T.id),title:"Resume",children:[t.jsx(xn,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:[t.jsx(ms,{size:14})," Stop"]})]}),T.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"paused"),disabled:R.has(T.id),title:"Pause",children:[t.jsx(Gs,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:[t.jsx(ms,{size:14})," Stop"]})]}),T.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"active"),disabled:R.has(T.id),title:"Retry",children:[t.jsx(xn,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:[t.jsx(ms,{size:14})," Stop"]})]}),T.state==="terminated"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm btn-task-create",onClick:()=>void $(T.id,"active"),disabled:R.has(T.id),title:"Start",children:[t.jsx(xn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void _(T.id,T.name),title:"Delete",children:[t.jsx(Xt,{size:14})," Delete"]})]})]})]},T.id)})})]})]})}):null}function b4({authenticated:e,onToggled:n,compact:s=!1}){const[i,r]=a.useState(null),[o,l]=a.useState(null),[c,u]=a.useState(null),d=a.useRef(!0);a.useEffect(()=>(d.current=!0,()=>{d.current=!1}),[]);const m=a.useCallback(async()=>{try{const b=await Jv();return d.current&&r(b),b}catch(b){return d.current&&u({kind:"error",message:b instanceof Error?b.message:String(b)}),null}},[]);a.useEffect(()=>{m()},[m]);const h=a.useCallback(async()=>{l("testing"),u(null),await m(),d.current&&l(null)},[m]),g=a.useCallback(async b=>{l(b?"enabling":"disabling"),u(null);try{const y=await Yv(b);d.current&&u({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await m()}catch(y){d.current&&u({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{d.current&&l(null)}},[n,m]),p=i?.binary.available??!1,f=i?.enabled??e,x=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"claude"})," CLI. Uses your existing Claude subscription / quota instead of an API key."]}),v=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),f?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void g(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void g(!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(An,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(v4,{status:i,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:v})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:"Details"}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[x,t.jsx(ph,{status:i,authenticated:e}),c&&t.jsx(fh,{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(An,{provider:"claude-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:"Anthropic — via Claude CLI"}),x,t.jsx(ph,{status:i,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(fh,{action:c})]})}function v4({status:e,authenticated:n}){const s=e?.enabled??n,i=e?.binary.available??!1;return s?t.jsx("span",{className:"auth-status-badge authenticated",children:"✓ Active"}):!i&&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 ph({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(ot,{size:10,className:"animate-spin"})," Probing local CLI…"]});const{binary:s,enabled:i,extension:r,ready:o}=e;return s.available?i?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 fh({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 y4(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"),i=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(i);if(l?.[1])return l[1];const c=e.match(r);return c?.[1]?c[1]:null}function ic({instructions:e,"data-testid":n}){const[s,i]=a.useState(!1),r=y4(e),o=a.useRef(null),l=a.useCallback(()=>{i(!0),setTimeout(()=>i(!1),2e3)},[]),c=a.useCallback(async()=>{const u=r??e;try{await navigator.clipboard.writeText(u),l()}catch{}},[r,e,l]);return a.useEffect(()=>{const u=o.current===null&&r!==null;if(o.current=r,!u)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((u,d,m)=>t.jsxs("span",{children:[u,d<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(Mn,{size:12}):t.jsx(Fi,{size:12})})]})]},d))}):e})}const qi="fusion_model_onboarding_state",va=[],ya=[],Eo=!1,_o=!1,ka={},k4=void 0,xi=["ai-setup","github","project-setup","first-task"],j4={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function gs(){if(typeof window>"u")return null;try{const e=localStorage.getItem(qi);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?w4(n):null}catch{return null}}function w4(e){const n=e.postOnboardingDismissedAt??k4;return{...e,completedSteps:e.completedSteps??va,skippedSteps:e.skippedSteps??ya,dismissed:e.dismissed??Eo,completed:e.completed??_o,stepData:e.stepData??ka,...n?{postOnboardingDismissedAt:n}:{}}}function so(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:va,skippedSteps:ya,dismissed:Eo,completed:_o,stepData:ka};try{localStorage.setItem(qi,JSON.stringify(s))}catch{}return}try{const s=gs(),i=new Date().toISOString(),r=n.completed??_o;let o=n.dismissed??Eo;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??va,c=n.skippedSteps??s?.skippedSteps??ya,u={...s?.stepData??ka};if(n.stepData)for(const[m,h]of Object.entries(n.stepData))h!==void 0&&(u[m]={...u[m]??{},...h});const d={currentStep:e,updatedAt:i,completedSteps:l,skippedSteps:c,dismissed:o,completed:r,stepData:u};localStorage.setItem(qi,JSON.stringify(d))}catch{}}}function N4(e){if(!(typeof window>"u"))try{const n=gs(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:va,skippedSteps:[e],dismissed:Eo,completed:_o,stepData:ka};localStorage.setItem(qi,JSON.stringify(o));return}const i=n.skippedSteps.includes(e)?n.skippedSteps:[...n.skippedSteps,e],r={...n,skippedSteps:i,completedSteps:n.completedSteps.filter(o=>o!==e),updatedAt:s};localStorage.setItem(qi,JSON.stringify(r))}catch{}}function gh(){if(!(typeof window>"u"))try{const e=gs(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:va,skippedSteps:ya,dismissed:!1,completed:!0,stepData:ka};localStorage.setItem(qi,JSON.stringify(s))}catch{}}function ja(){const e=gs();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function S4(){if(!(typeof window>"u"))try{const e=gs(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:va,skippedSteps:ya,dismissed:!1,completed:!1,stepData:ka,postOnboardingDismissedAt:n};localStorage.setItem(qi,JSON.stringify(s))}catch{}}function tg(){const e=gs();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function C4(){const e=gs();return!e||ja()?!1:e.currentStep!=="complete"}function E4(){const e=gs();if(!e||ja()||e.currentStep==="complete")return null;const n=e.currentStep,s=j4[n]??A4(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function _4(){const e=gs();return e?e.skippedSteps:ya}function M4(e){const n=gs();return!n||!n.stepData?null:n.stepData[e]??null}function A4(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const ng="fusion_onboarding_events",xh="fusion_onboarding_session_id",R4=200,T4=50;function ws(e,n={}){if(!(typeof window>"u"))try{const s=I4(),i=L4(n.step),r={type:e,timestamp:new Date().toISOString(),...i?{step:i}:{},metadata:n,sessionId:P4()},o=D4([...s,r]);$4(o)}catch{}}function P4(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(xh);if(e)return e;const n=bh();return sessionStorage.setItem(xh,n),n}catch{return bh()}}function bh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function I4(){try{const e=localStorage.getItem(ng);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(z4):[]}catch{return[]}}function $4(e){try{localStorage.setItem(ng,JSON.stringify(e))}catch{}}function D4(e){const n=[...e];for(;n.length>R4;)n.splice(0,T4);return n}function L4(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function z4(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 F4={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"}}},sg={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:"..."}},O4={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},vh={anthropic:"Anthropic",openai:"OpenAI","openai-codex":"OpenAI Codex",openrouter:"OpenRouter",google:"Google",gemini:"Gemini",minimax:"MiniMax",ollama:"Ollama",zai:"Zhipu AI",kimi:"Kimi","kimi-coding":"Kimi Coding",moonshot:"Moonshot"};function Hc(e){if(vh[e])return vh[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 ac=["anthropic","openai","google","gemini","ollama"],U4=["anthropic","claude-cli","openai-codex","gemini","minimax","kimi","zai"],B4={anthropic:"anthropic","claude-cli":"claude-cli","openai-codex":"openai-codex",google:"gemini",gemini:"gemini",minimax:"minimax",kimi:"kimi",moonshot:"kimi","kimi-coding":"kimi",zai:"zai"},H4={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function qc(e){return B4[e]??e}function yh(e){const n=qc(e),s=U4.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function kh(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=yh(e.id),i=yh(n.id);if(s!==i)return s-i;const r=qc(e.id),o=qc(n.id);if(r!==o)return r.localeCompare(o);const l=H4[r];if(l){const u=l.indexOf(e.id),d=l.indexOf(n.id);if(u!==d)return(u===-1?Number.POSITIVE_INFINITY:u)-(d===-1?Number.POSITIVE_INFINITY:d)}const c=e.name.localeCompare(n.name);return c!==0?c:e.id.localeCompare(n.id)}function q4(e,n){const s=n.trim();if(!s)return"API key is required";const i=sg[e]??O4;return i.pattern.test(s)?null:`${Hc(e)} keys should follow this format: ${i.hint} (e.g. ${i.example})`}const ig={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"},V4={description:"AI provider — connect to start using AI models",apiKeyInfo:ig};function Vc(e){return F4[e]??V4}function W4(e){return Vc(e.id).apiKeyInfo??ig}function Ws({summary:e,children:n,className:s=""}){const[i,r]=a.useState(!1);return t.jsxs("div",{className:`onboarding-disclosure ${s}`,children:[t.jsxs("button",{className:"onboarding-disclosure-trigger",onClick:()=>r(!i),"aria-expanded":i,type:"button",children:[t.jsx(hn,{size:14,className:"onboarding-disclosure-chevron","aria-hidden":"true"}),t.jsx("span",{children:e})]}),i&&t.jsx("div",{className:"onboarding-disclosure-content",children:n})]})}function K4({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 i=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:i}),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 G4({provider:e,apiKeyInfo:n,inputValue:s,isSaving:i,error:r,success:o,isConnected:l,onInputChange:c,onSave:u,onClear:d}){const m=`onboarding-apikey-input-${e.id}`,h=i||!s.trim(),g=sg[e.id],p=`input onboarding-apikey-input${r?" onboarding-apikey-input--error":""}${o?" onboarding-apikey-input--success":""}`,f=t.jsxs(t.Fragment,{children:[g&&t.jsxs("small",{className:"onboarding-apikey-hint",children:["Format: ",g.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:()=>d(e.id),disabled:i,children:i?"Removing…":"Remove Key"}),t.jsx(Ws,{summary:"Advanced setup details",children:f}),r&&t.jsx("small",{className:"field-error",children:r})]}):t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsx("label",{htmlFor:m,className:"onboarding-apikey-field-label",children:n.fieldLabel}),t.jsxs("div",{className:"onboarding-apikey-input-row",children:[t.jsx("input",{id:m,type:"password",className:p,placeholder:n.inputPlaceholder??"Enter API key",value:s,onChange:x=>c(e.id,x.target.value),onKeyDown:x=>{x.key==="Enter"&&u(e.id,s)},"data-testid":m}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>u(e.id,s),disabled:h,"data-testid":`onboarding-apikey-save-${e.id}`,children:i?"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(Ws,{summary:"Advanced setup details",children:f})]})}const J4=150;function Y4({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:i,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const u=gs(),d=u?.currentStep,m=d==="complete"?"ai-setup":xi.includes(d)?d:"ai-setup",h=u?.completedSteps??[],g=u?.skippedSteps??_4(),[p,f]=a.useState(!0),[x,v]=a.useState(m),[b,y]=a.useState(h),[S,k]=a.useState(g),[R,N]=a.useState(!1),[M,C]=a.useState(""),[z,A]=a.useState(!1),[P,F]=a.useState(null),[W,$]=a.useState(null),[_,I]=a.useState([]),[O,J]=a.useState(void 0),[Q,E]=a.useState(!0),[D,T]=a.useState(null),[w,q]=a.useState({}),[G,me]=a.useState([]),[ce,ae]=a.useState(""),[pe,U]=a.useState(!1),[Ne,ne]=a.useState({}),[xe,le]=a.useState({}),[ve,ee]=a.useState({}),Ee=a.useRef({}),Fe=a.useRef(null),Ke=a.useRef(null),Ze=a.useRef(null),[Xe,Qe]=a.useState({}),[it,Ie]=a.useState(()=>gs()?.stepData?.github?.skipped===!0),Ge=a.useRef(0),se=a.useRef(l),ye=a.useRef(!1),Z=u?.currentStep,Te=!!u&&u.currentStep!=="complete";Xs(Ke,p,"fusion:model-onboarding-modal-size"),a.useEffect(()=>{const Y=Fe.current;Y&&(Y.scrollTop=0)},[x]);const[ze,be]=a.useState(()=>gs()?.stepData?.["ai-setup"]?.skippedProviders??{}),Me=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],Be=Me.findIndex(Y=>Y.key===x),lt=x==="complete"?Me.length:Be;a.useEffect(()=>{x!=="complete"&&so(x,{completedSteps:b,skippedSteps:S})},[x,b,S]),a.useEffect(()=>{ye.current||(ye.current=!0,ws("onboarding:wizard-opened",{source:Te?"resume":"initial",resumedFromStep:Z}))},[Te,Z]),a.useEffect(()=>{const Y=se.current!=null,Oe=l!=null;!Y&&Oe&&N(!0),Oe||N(!1),se.current=l},[l]);const je=a.useRef(m);a.useEffect(()=>{if(je.current==="ai-setup"&&x!=="ai-setup"&&!_.some(Oe=>Oe.id!=="github"&&Oe.authenticated)){const Oe={};for(const Ye of _)Ye.id!=="github"&&!Ye.authenticated&&!ze[Ye.id]&&(Oe[Ye.id]=!0);if(Object.keys(Oe).length>0){const Ye={...ze,...Oe};be(Ye),so(x,{stepData:{"ai-setup":{skippedProviders:Ye}}})}}je.current=x},[x,_,ze]);const ie=a.useCallback(async()=>{try{const{providers:Y,ghCli:Oe}=await mr();I(Y),J(Oe),q(Ye=>{const st={};for(const[pt,jt]of Object.entries(Ye)){const _t=Y.find(yn=>yn.id===pt);_t&&!_t.authenticated&&(st[pt]=jt)}return Object.keys(st).length===Object.keys(Ye).length?Ye:st}),be(Ye=>{const st={...Ye};for(const pt of Y)pt.authenticated&&st[pt.id]&&delete st[pt.id];return Object.keys(st).length===Object.keys(Ye).length?Ye:st})}catch{}},[]),Ae=a.useRef(!1);a.useEffect(()=>{Ae.current&&ie(),Ae.current=x!=="ai-setup"},[x,ie]);const he=_.find(Y=>Y.id==="github"),Re=!!he,Je=he?.authenticated??!1,$e=O?.authenticated??!1,de=Je||$e,re=!Je&&$e,ue=a.useCallback(Y=>{if(Y.authenticated)return"connected";const Oe=Xe?.[Y.id];return Oe==="timeout"||Oe==="failed"?"retry":ze[Y.id]?"skipped":"not-connected"},[Xe,ze]);function Pe({status:Y}){const Oe={connected:{text:"✓ Connected",className:"auth-status-badge connected"},"not-connected":{text:"Not connected",className:"auth-status-badge not-connected"},skipped:{text:"Skipped",className:"auth-status-badge skipped"},retry:{text:"Retry",className:"auth-status-badge retry"}},{text:Ye,className:st}=Oe[Y];return t.jsx("span",{"data-testid":"provider-status-badge",className:st,"data-status":Y,children:Ye})}const Se=a.useCallback(()=>{if(de)return"connected";const Y=Xe.github;return Y==="pending"?"pending":Y==="failed"||Y==="timeout"?"failed":it?"skipped":"not-connected"},[de,Xe,it]);function fe({status:Y}){const Oe={connected:{text:"✓ Connected",className:"auth-status-badge connected"},pending:{text:"⏳ Connecting…",className:"auth-status-badge pending"},failed:{text:"✗ Connection failed",className:"auth-status-badge retry"},skipped:{text:"Skipped",className:"auth-status-badge skipped"},"not-connected":{text:"Not connected",className:"auth-status-badge not-connected"}},{text:Ye,className:st}=Oe[Y];return t.jsx("span",{"data-testid":"github-status-badge",className:st,"data-status":Y,children:Ye})}const tt=a.useCallback(async()=>{try{const Y=await cs();me(Y.models)}catch{}},[]),ut=a.useCallback(async()=>{try{const Y=await Vi();if(Y.defaultProvider&&Y.defaultModelId){const Oe=`${Y.defaultProvider}/${Y.defaultModelId}`;ae(Oe)}}catch{}},[]);a.useEffect(()=>{Promise.all([ie(),tt(),ut()]).finally(()=>E(!1))},[ie,tt,ut]),a.useEffect(()=>{const Y=M4("ai-setup");if(Y?.loginOutcomes){const Oe=Y.loginOutcomes,Ye={};for(const[st,pt]of Object.entries(Oe))pt!=="pending"&&(Ye[st]=pt);Object.keys(Ye).length>0&&Qe(Ye)}},[]);const vt=a.useCallback((Y,Oe)=>{so(x,{completedSteps:b,stepData:{"ai-setup":{loginOutcomes:{[Y]:Oe}}}})},[x,b]);a.useEffect(()=>{const Y=Object.entries(Xe).filter(([Oe,Ye])=>Ye!=="pending");for(const[Oe,Ye]of Y)vt(Oe,Ye)},[Xe,vt]),a.useEffect(()=>()=>{Ze.current&&clearInterval(Ze.current),Object.values(Ee.current).forEach(clearTimeout),Ee.current={}},[]);const gt=a.useCallback(Y=>{Ie(Y),so(x,{completedSteps:b,stepData:{github:{skipped:Y}}})},[x,b]),dt=a.useCallback(Y=>Y==="complete"?-1:xi.indexOf(Y),[]),wt=a.useCallback(()=>{y(Oe=>[...new Set([...Oe,x])]),k(Oe=>Oe.filter(Ye=>Ye!==x)),ws("onboarding:step-completed",{step:x}),x==="github"&&!Je&>(!1);const Y=dt(x);Y>=0&&Y<xi.length-1&&v(xi[Y+1])},[x,Je,gt,dt]),Mt=a.useCallback(()=>{k(Oe=>[...new Set([...Oe,x])]),N4(x),ws("onboarding:step-skipped",{step:x}),x==="github"&&!Je&>(!0);const Y=dt(x);Y>=0&&Y<xi.length-1&&v(xi[Y+1])},[x,Je,gt,dt]),yt=a.useCallback(()=>{const Y=x;y(Ye=>Ye.filter(st=>st!==Y)),k(Ye=>Ye.filter(st=>st!==Y)),Y==="github"&&!Je&>(!1);const Oe=dt(x);Oe>0&&v(xi[Oe-1])},[x,Je,gt,dt]),Et=a.useCallback(()=>{Mt()},[Mt]),Nt=a.useCallback(async Y=>{Qe(Oe=>{const Ye=Oe[Y];if(Ye&&Ye!=="pending"){const{[Y]:st,...pt}=Oe;return pt}return Oe}),q(Oe=>{if(!(Y in Oe))return Oe;const Ye={...Oe};return delete Ye[Y],Ye}),Qe(Oe=>({...Oe,[Y]:"pending"})),T(Y),Ge.current=0;try{const{url:Oe,instructions:Ye}=await Qv(Y);Ye?.trim()&&q(st=>({...st,[Y]:Ye})),window.open(Qs(Oe),"_blank"),Ze.current=setInterval(async()=>{if(Ge.current++,Ge.current>=J4){Ze.current&&(clearInterval(Ze.current),Ze.current=null),T(null),Qe(st=>({...st,[Y]:"timeout"})),q(st=>{if(!(Y in st))return st;const pt={...st};return delete pt[Y],pt}),n("Login timed out. Please try again.","warning");return}try{const{providers:st,ghCli:pt}=await mr();I(st),J(pt),st.find(_t=>_t.id===Y)?.authenticated&&(Ze.current&&(clearInterval(Ze.current),Ze.current=null),T(null),Qe(_t=>({..._t,[Y]:"success"})),q(_t=>{if(!(Y in _t))return _t;const yn={..._t};return delete yn[Y],yn}),Y==="github"&>(!1),n("Login successful","success"))}catch{}},2e3)}catch(Oe){Oe instanceof Error&&Oe.message.includes("already in progress")||Oe&&typeof Oe=="object"&&"status"in Oe&&Oe.status===409?(n("Login already in progress. Please wait or cancel the current attempt.","warning"),Qe(st=>({...st,[Y]:"failed"}))):(n(Oe instanceof Error?Oe.message:"Login failed","error"),Qe(st=>({...st,[Y]:"failed"}))),T(null),q(st=>{if(!(Y in st))return st;const pt={...st};return delete pt[Y],pt})}},[n,gt]),Tt=a.useCallback(Y=>{Ze.current&&(clearInterval(Ze.current),Ze.current=null),T(null),Ge.current=0,Qe(Oe=>({...Oe,[Y]:"cancelled"})),q(Oe=>{if(!(Y in Oe))return Oe;const Ye={...Oe};return delete Ye[Y],Ye})},[]),Ht=a.useCallback((Y,Oe)=>{ne(st=>({...st,[Y]:Oe}));const Ye=Ee.current[Y];Ye&&(clearTimeout(Ye),delete Ee.current[Y]),le(st=>{if(!st[Y])return st;const pt={...st};return delete pt[Y],pt}),ee(st=>{if(!st[Y])return st;const pt={...st};return delete pt[Y],pt})},[]),Ut=a.useCallback(()=>{const Y=Fe.current;if(!Y)return;const Oe=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof Y.scrollTo=="function"){Y.scrollTo({top:0,behavior:Oe?"auto":"smooth"});return}}catch{}Y.scrollTop=0},[]),Vt=a.useCallback(async(Y,Oe)=>{const Ye=(Oe??Ne[Y]??"").trim(),st=q4(Y,Ye);if(st){le(jt=>({...jt,[Y]:st}));return}const pt=Ee.current[Y];pt&&(clearTimeout(pt),delete Ee.current[Y]),T(Y),le(jt=>{const _t={...jt};return delete _t[Y],_t}),ee(jt=>{if(!jt[Y])return jt;const _t={...jt};return delete _t[Y],_t});try{await Zv(Y,Ye),await ie(),Ut(),ne(jt=>{const _t={...jt};return delete _t[Y],_t}),le(jt=>{if(!jt[Y])return jt;const _t={...jt};return delete _t[Y],_t}),ee(jt=>({...jt,[Y]:"✓ Key saved"})),Ee.current[Y]=setTimeout(()=>{ee(jt=>{if(!jt[Y])return jt;const _t={...jt};return delete _t[Y],_t}),delete Ee.current[Y]},3e3),n("API key saved","success")}catch(jt){const _t=jt instanceof TypeError&&jt.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":jt instanceof Error?jt.message:"Failed to save API key";le(yn=>({...yn,[Y]:_t})),ee(yn=>{if(!yn[Y])return yn;const en={...yn};return delete en[Y],en}),n(_t,"error")}finally{T(null)}},[Ne,n,ie,Ut]),zt=a.useCallback(async Y=>{T(Y);try{await ey(Y),await ie(),n("API key removed","success")}catch(Oe){n(Oe instanceof Error?Oe.message:"Failed to clear API key","error")}finally{T(null)}},[n,ie]),Ct=a.useCallback(async Y=>{T(Y);try{await Xv(Y),await ie(),n("Logged out","success")}catch(Oe){n(Oe instanceof Error?Oe.message:"Logout failed","error")}finally{T(null)}},[n,ie]),At=a.useCallback(Y=>{ae(Y)},[]),kt=a.useCallback(async()=>{try{const Y={modelOnboardingComplete:!0};if(ce){const Oe=ce.indexOf("/"),Ye=Oe!==-1?ce.slice(0,Oe):void 0,st=Oe!==-1?ce.slice(Oe+1):ce,pt=G.find(jt=>jt.id===st);pt?(Y.defaultProvider=pt.provider,Y.defaultModelId=pt.id):Ye&&st&&(Y.defaultProvider=Ye,Y.defaultModelId=st)}await sn(Y),gh()}catch{}},[ce,G,sn,gh]),Kt=a.useCallback(async()=>{const Y=[...new Set([...b,"first-task"])];U(!0);try{await kt(),ws("onboarding:completed",{completedSteps:Y,skippedSteps:S}),y(Y),k(Oe=>Oe.filter(Ye=>Ye!=="first-task")),v("complete")}finally{U(!1)}},[kt,b,S]),$t=a.useCallback(async()=>{if(!s)return;const Y=M.trim();if(!Y){F("Please enter a task description.");return}F(null),A(!0);let Oe=!1;try{const Ye=await Xh({description:Y},s);$(Ye),N(!0),ws("onboarding:first-task-created",{taskId:Ye?.id}),n("Task created","success"),Oe=!0}catch(Ye){const st=Ye instanceof Error?Ye.message:"Something went wrong creating your task. Please try again.";F(st),n(st,"error")}finally{A(!1)}Oe&&kt()},[s,M,n,kt]),B=a.useCallback(async()=>{U(!0);try{await kt()}finally{U(!1)}ws("onboarding:open-new-task",{}),r?.()},[kt,r]),ge=a.useCallback(async()=>{if(de){U(!0);try{await kt()}finally{U(!1)}f(!1),e(),ws("onboarding:open-github-import",{}),o?.()}},[kt,de,e,o]),te=a.useCallback(async()=>{ws("onboarding:dismissed",{currentStep:x,completedSteps:b,skippedSteps:S}),U(!0);try{await sn({modelOnboardingComplete:!0})}catch{}f(!1),e()},[x,b,S,e]),j=a.useCallback(()=>{ws("onboarding:finished",{}),f(!1),e()},[e]),V=a.useCallback(()=>{const Y=l??W;Y&&(kt(),c?.(Y),e())},[l,W,kt,c,e]),De=a.useCallback(()=>{kt(),e()},[kt,e]);if(!p)return null;const nt=Se(),St=_.filter(Y=>Y.id!=="github"),Pt=[...St].sort(kh),Rt=Pt.some(Y=>!Y.type||Y.type==="oauth"),un=Pt.some(Y=>Y.type==="api_key"),mn=St.filter(Y=>Y.authenticated),wn=mn.length>0,Gt=!!s,es=x==="github"&&!wn,we=(()=>{if(!ce)return"";const Y=ce.indexOf("/"),Oe=Y===-1?void 0:ce.slice(0,Y),Ye=Y===-1?ce:ce.slice(Y+1),st=G.find(pt=>pt.id===Ye&&(!Oe||pt.provider===Oe));return st?.name?st.name:Oe?`${Hc(Oe)} ${Ye}`:ce})(),rt=[];if(Gt?rt.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):rt.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),wn){const Y=Hc(mn[0]?.id??"");rt.push({label:"AI Provider",status:"connected",detail:`${Y} connected — AI agents can work on tasks`})}else St.length>0&&St.some(Y=>ze[Y.id])?rt.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):rt.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});de?rt.push({label:"GitHub",status:"connected",detail:re?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!Re||it?rt.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):rt.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),we&&rt.push({label:"Default Model",status:"connected",detail:we});const Jt=l??W,Sn=Jt?.description?.split(`
|
|
656
|
+
`)[0]?.trim()||Jt?.title||"",Cn=new Set(ac),pn=Pt.filter(Y=>Cn.has(Y.id)).sort((Y,Oe)=>{const Ye=ac.indexOf(Y.id),st=ac.indexOf(Oe.id);return Ye!==st?Ye-st:kh(Y,Oe)}),bn=Pt.filter(Y=>Y.authenticated&&!Cn.has(Y.id)),Rn=Pt.filter(Y=>!Y.authenticated&&!Cn.has(Y.id)),vn=Y=>{if(Y.id==="claude-cli"&&Y.type==="cli")return t.jsx(b4,{authenticated:Y.authenticated,onToggled:()=>{ie()}},Y.id);if(Y.type==="api_key"){const Oe=Vc(Y.id),Ye=W4(Y);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${Y.id}`,className:`onboarding-provider-card${Y.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${Y.id}`,"aria-hidden":"true",children:t.jsx(An,{provider:Y.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(Vh,{size:14,className:"onboarding-provider-key-icon"}),Y.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:Oe.description}),t.jsx(Pe,{status:ue(Y)}),Y.authenticated&&Y.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",Y.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(G4,{provider:Y,apiKeyInfo:Ye,inputValue:Ne[Y.id]??"",isSaving:D===Y.id,error:xe[Y.id],success:ve[Y.id],isConnected:Y.authenticated,onInputChange:Ht,onSave:Vt,onClear:zt})})]},Y.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${Y.id}`,className:`onboarding-provider-card${Y.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${Y.id}`,"aria-hidden":"true",children:t.jsx(An,{provider:Y.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:Y.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:Vc(Y.id).description}),t.jsx(Pe,{status:ue(Y)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:D===Y.id?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:Y.authenticated?"Logging out…":"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Tt(Y.id),children:"Cancel"})]}):Y.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>Ct(Y.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>Nt(Y.id),children:"Login"})}),D===Y.id&&w[Y.id]&&t.jsx(ic,{instructions:w[Y.id],"data-testid":`onboarding-login-instructions-${Y.id}`}),Xe[Y.id]==="timeout"&&D!==Y.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),Xe[Y.id]==="failed"&&D!==Y.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},Y.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:Ke,children:[t.jsxs("div",{className:"model-onboarding-header",children:[t.jsxs("h2",{id:"onboarding-title",className:"model-onboarding-title",children:[x==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Pn,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(hs,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(_d,{size:24})," Set Up Your Project"]}),x==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(_d,{size:24})," Create Your First Task"]}),x==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(dn,{size:24})," All Set!"]})]}),x!=="complete"&&t.jsx("button",{className:"modal-close",onClick:te,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(Ot,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:Me.map((Y,Oe)=>{const Ye=lt>Oe,st=b.includes(Y.key)&&Ye,pt=S.includes(Y.key)&&!b.includes(Y.key)&&Ye,jt=st||pt;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[Oe>0&&t.jsx("div",{className:`model-onboarding-step-connector ${Oe<=lt?"done":""}`}),jt?t.jsxs("button",{className:`model-onboarding-step-indicator ${x===Y.key?"active":""} ${st?"done":""} ${pt?"skipped":""}`,onClick:()=>v(Y.key),"aria-label":`Go back to ${Y.label}`,title:`Review ${Y.label}`,children:[t.jsx("span",{className:"step-number",children:st?t.jsx(dn,{size:14}):pt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Oe+1}),t.jsx("span",{className:"step-label",children:Y.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${x===Y.key?"active":""} ${st?"done":""} ${pt?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:st?t.jsx(dn,{size:14}):pt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Oe+1}),t.jsx("span",{className:"step-label",children:Y.label})]})]},Y.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:Fe,children:[x==="ai-setup"&&t.jsxs("div",{className:"model-onboarding-ai-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Fusion uses AI models to plan, write, and review code for you. Connect an AI provider below to get started — you can use a hosted service or enter an API key."}),t.jsx("p",{className:"onboarding-helper-text model-onboarding-primary-helper",children:"You only need one provider to get started."}),!Q&&_.length>0&&(()=>{const Y=_.filter(jt=>jt.id!=="github"&&jt.authenticated).length,Oe=_.filter(jt=>jt.id!=="github").length,Ye=Object.keys(ze).filter(jt=>!_.find(_t=>_t.id===jt)?.authenticated).length;if(Oe===0)return null;let st="onboarding-provider-summary",pt="";return Y>0?(st+=" onboarding-provider-summary--connected",pt=`✓ ${Y} of ${Oe} provider${Oe!==1?"s":""} connected`):Ye>0?(st+=" onboarding-provider-summary--skipped",pt=`${Ye} provider${Ye!==1?"s":""} skipped`):(st+=" onboarding-provider-summary--none",pt="No providers connected yet"),t.jsx("div",{className:st,"data-testid":"provider-summary",children:pt})})(),t.jsx(Ws,{summary:"What are AI providers?",children:t.jsx("p",{className:"onboarding-helper-text",children:"AI providers like OpenAI and Anthropic power the AI capabilities in Fusion. Connecting a provider lets Fusion's agents use AI models to help with your tasks."})}),_.length>0&&!_.some(Y=>Y.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),Q?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(ot,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):_.length===0?t.jsx("div",{className:"model-onboarding-empty",children:"No AI providers are configured. Please check your Fusion configuration."}):t.jsxs(t.Fragment,{children:[t.jsxs("section",{className:"onboarding-provider-section","data-testid":"onboarding-quick-start-providers",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Quick start providers"}),pn.length>0?t.jsx("div",{className:"model-onboarding-providers",children:pn.map(Y=>vn(Y))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),bn.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:bn.map(Y=>vn(Y))})]}),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(Ws,{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."})}),G.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($n,{models:G,value:ce,onChange:At,placeholder:"Select a default model…",label:"Default model"})}),ce&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",G.find(Y=>Y.id===ce)?.name??ce]})})]}),t.jsx(Ws,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsx("div",{"data-testid":"onboarding-advanced-provider-settings",children:Rn.length>0?t.jsx("div",{className:"model-onboarding-providers",children:Rn.map(Y=>vn(Y))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."})})}),Rt&&t.jsx(Ws,{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."})}),un&&t.jsx(Ws,{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."})})]})]}),x==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[de?t.jsx("p",{className:"model-onboarding-description",children:re?"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."}),!de&&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"})]})}),es&&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(Ws,{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."})}),Re?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(hs,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(fe,{status:nt})})]}),Je&&(D==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>Ct("github"),children:"Disconnect"}))]}),(nt==="not-connected"||nt==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[D==="github"?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:()=>Tt("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>Nt("github"),children:[t.jsx(hs,{size:16}),"Connect"]}),D==="github"&&w.github&&t.jsx(ic,{instructions:w.github,"data-testid":"onboarding-login-instructions-github"})]}),nt==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:re?"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."}),nt==="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:()=>Nt("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Et,children:"Skip for now"})]})]}),nt==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),nt==="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:()=>Nt("github"),children:"Connect anyway"})})]}),nt==="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(An,{provider:"github",size:"lg"})}),re?t.jsx("p",{children:"GitHub CLI is already authenticated, so imports and PR tracking work now. OAuth from the dashboard is optional and only controls dashboard-managed connect/disconnect."}):t.jsx("p",{children:"GitHub OAuth isn't connected yet. You can set it up in Settings → Authentication, or continue now and connect later."}),t.jsxs("div",{className:"model-onboarding-github-optional__actions",children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>v("project-setup"),children:re?"Continue with gh CLI auth →":"Continue without GitHub →"}),re&&(D==="github"?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(ot,{size:14,className:"onboarding-spinner"}),"Waiting for OAuth login…"]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>Nt("github"),children:[t.jsx(An,{provider:"github",size:"sm"}),"Connect OAuth (optional)"]}))]}),re&&D==="github"&&w.github&&t.jsx(ic,{instructions:w.github,"data-testid":"onboarding-login-instructions-github"})]})]}),x==="project-setup"&&t.jsxs("div",{className:"model-onboarding-project-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Choose your first project before creating or importing tasks. You can register an existing local directory or clone a GitHub repository URL through the setup wizard."}),Gt?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:i,"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(Ws,{summary:"What does project setup do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Project setup registers a workspace so Fusion knows where to read files, run commands, and track task changes."})})]}),x==="first-task"&&t.jsxs("div",{className:"model-onboarding-first-task",children:[t.jsx("p",{className:"model-onboarding-description",children:"Create your first task to start the board and launch AI execution."}),R&&Jt?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(dn,{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:Jt.id}),Sn&&t.jsx("p",{className:"onboarding-task-created__description",children:Sn}),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:V,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:De,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[Gt?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:M,onChange:Y=>{C(Y.target.value),F(null)},placeholder:"Example: Build a login page with email and password",rows:4}),t.jsx("div",{className:"onboarding-first-task-form__actions",children:t.jsx("button",{type:"button",className:"btn btn-primary",onClick:$t,disabled:z,"data-testid":"onboarding-first-task-submit",children:z?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),P&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:P}),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:i,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"})]}),t.jsx(K4,{items:rt}),Gt&&t.jsxs(t.Fragment,{children:[t.jsx(Ws,{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:B,disabled:pe,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Zt,{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${de?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:ge,disabled:pe||!de,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(hs,{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"}),!de&&t.jsx("small",{className:"onboarding-cta-note",children:"Requires GitHub connection"})]})]})]}),t.jsxs("p",{className:"onboarding-skip-note",children:["You can create tasks anytime from the board, or use"," ",t.jsx("code",{children:"fn task create"})," in the terminal."]})]})]})]}),x==="complete"&&t.jsxs("div",{className:"model-onboarding-complete",children:[t.jsx(dn,{size:48,className:"success-icon"}),t.jsx("p",{children:"Setup complete! Head to the board to create your first task, or explore the dashboard to see what's available."})]})]}),t.jsxs("div",{className:"model-onboarding-footer",children:[x==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:te,disabled:pe,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Mt,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:wt,children:"Next →"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:yt,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Mt,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:wt,children:"Next →"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:yt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:wt,disabled:!Gt,children:"Next →"})]}),x==="first-task"&&!R&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:yt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:Kt,disabled:pe,children:pe?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),x==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:j,children:[t.jsx(dn,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function ag({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 Q4=a.lazy(()=>nn(()=>import("./SetupWizardModal-Bk_8HfLm.js"),__vite__mapDeps([6,1,7,8,9,0,2,10])).then(e=>({default:e.SetupWizardModal}))),X4=a.lazy(()=>nn(()=>import("./SettingsModal-BiLA-BeG.js"),__vite__mapDeps([11,1,12,13,14,15,0,2,16])).then(e=>({default:e.SettingsModal})));function Z4(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{nn(()=>import("./SettingsModal-BiLA-BeG.js"),__vite__mapDeps([11,1,12,13,14,15,0,2,16]))},{timeout:1500})}function eT({projectId:e,tasks:n,projects:s,currentProject:i,addToast:r,toasts:o,removeToast:l,modalManager:c,projectActions:u,taskHandlers:d,taskOperations:m,deepLink:h,settings:g,onSettingsClose:p,onReopenOnboarding:f}){const[x,v]=a.useState(null),b=c.detailTask?(()=>{const M=n.find(C=>C.id===c.detailTask?.id);return M?"prompt"in c.detailTask?{...c.detailTask,...M,prompt:c.detailTask.prompt,log:c.detailTask.log}:M:c.detailTask})():null,y=p??c.closeSettings,S=a.useCallback(()=>{c.openNewTask()},[c]),k=a.useCallback(()=>{c.openGitHubImport()},[c]),R=a.useCallback(M=>{v(null),c.closeModelOnboarding(),c.openDetailTask(M)},[c]),N=a.useCallback(async M=>{const C=await d.handleModalCreate(M);return c.modelOnboardingOpen&&v(C),C},[d.handleModalCreate,c.modelOnboardingOpen]);return a.useEffect(()=>{!c.modelOnboardingOpen&&x&&v(null)},[c.modelOnboardingOpen,x]),a.useEffect(()=>{Z4()},[]),t.jsxs(t.Fragment,{children:[b&&t.jsx(Ti,{children:t.jsx(XM,{task:b,projectId:e,tasks:n,onClose:h.handleDetailClose,onOpenDetail:c.openDetailTask,onMoveTask:m.moveTask,onDeleteTask:m.deleteTask,onMergeTask:m.mergeTask,onRetryTask:m.retryTask,onDuplicateTask:m.duplicateTask,onTaskUpdated:c.updateDetailTask,addToast:r,prAuthAvailable:g.prAuthAvailable,initialTab:c.detailTaskInitialTab})}),c.settingsOpen&&t.jsx(Ti,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(X4,{onClose:y,addToast:r,initialSection:c.settingsInitialSection,projectId:e,themeMode:g.themeMode,colorTheme:g.colorTheme,onThemeModeChange:g.setThemeMode,onColorThemeChange:g.setColorTheme,onReopenOnboarding:f})})}),t.jsx(eA,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:d.handleGitHubImport,tasks:n,projectId:e}),t.jsx(Ti,{children:t.jsx(iA,{isOpen:c.isPlanningOpen,onClose:c.closePlanning,onTaskCreated:d.handlePlanningTaskCreated,onTasksCreated:d.handlePlanningTasksCreated,tasks:n,initialPlan:c.planningInitialPlan??void 0,projectId:e,resumeSessionId:c.planningResumeSessionId})}),t.jsx(Ti,{children:t.jsx(pA,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:d.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx($A,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(LA,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(iR,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),t.jsx(hR,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e,anchorRect:c.usageAnchorRect}),t.jsx(BR,{isOpen:c.systemStatsOpen,onClose:c.closeSystemStats,projectId:e}),c.schedulesOpen&&t.jsx(PR,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(Ti,{children:t.jsx(LR,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:N,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(KR,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:i,onOpenTaskDetail:M=>{const C=n.find(z=>z.id===M);C&&c.openDetailTask(C)}}),t.jsx(Ti,{children:t.jsx(JR,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(Ti,{children:t.jsx(o4,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(x4,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(a.Suspense,{fallback:null,children:t.jsx(Q4,{onProjectRegistered:u.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(Y4,{onComplete:u.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:u.handleAddProject,onOpenNewTask:S,onOpenGitHubImport:k,firstCreatedTask:x,onViewTask:R}),t.jsx(ag,{toasts:o,onRemove:l})]})}function tT({errorMessage:e,isRetrying:n,onRetry:s}){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.jsx("button",{type:"button",className:"btn btn-primary",onClick:s,disabled:n,children:n?"Retrying…":"Retry Connection"})]})}const Wc=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function nT(e,n){if(n==="ready")return"done";const s=Wc.findIndex(r=>r.id===n),i=Wc.findIndex(r=>r.id===e);return i<s?"done":i===s?"active":"pending"}function sT({stage:e}){const[n]=a.useState(()=>tv());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:Wc.map(s=>{const i=nT(s.id,e);return t.jsxs("li",{className:`dashboard-loader__step dashboard-loader__step--${i}`,"data-testid":`dashboard-loader-step-${s.id}`,children:[t.jsx("span",{className:"dashboard-loader__step-icon","aria-hidden":"true",children:i==="done"?"✓":i==="active"?t.jsx(ot,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:s.label})]},s.id)})})]})})}const iT=5e3;function aT(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function rT(e,n,s){let i=0,r=0,o=0,l=0,c=0;for(const u of e){switch(u.column){case"in-progress":i++,vo(u,n,s)&&o++;break;case"todo":l++;break;case"in-review":c++;break}u.blockedBy&&u.blockedBy.length>0&&r++}return{runningTaskCount:i,blockedTaskCount:r,stuckTaskCount:o,queuedTaskCount:l,inReviewCount:c}}function oT(e,n,s,i){const[r,o]=a.useState({globalPause:!1,enginePaused:!1,maxConcurrent:2}),[l,c]=a.useState(!0),[u,d]=a.useState(null),m=a.useRef(null),h=a.useRef(null),g=a.useCallback(async()=>{h.current&&h.current.abort(),h.current=new AbortController;try{c(!0),d(null);const v=await Pk(n);o(v)}catch(v){if(v instanceof Error&&v.name==="AbortError")return;d(v instanceof Error?v.message:"Failed to fetch executor stats")}finally{c(!1)}},[n]);a.useEffect(()=>(g(),()=>{h.current&&h.current.abort()}),[g]),a.useEffect(()=>(m.current&&clearInterval(m.current),m.current=setInterval(()=>{g()},iT),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[g]);const p=rT(e,s,i),f=aT(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:f,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:u,refresh:g}}const lT={planning:Ys,subtask:Ui,mission_interview:ls,milestone_interview:ls,slice_interview:ls},cT={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function dT({sessions:e,generating:n,needsInput:s,onOpenSession:i,onDismissSession:r}){const{confirm:o}=Ds(),[l,c]=a.useState(!1),[u,d]=a.useState(new Set),m=a.useRef(null),h=a.useRef(new Map),g=a.useRef(null),{activeTabMap:p}=Sa(),f=a.useMemo(()=>Wi(),[]);if(a.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]),a.useEffect(()=>{const b=new Set,y=new Map;for(const S of e){const k=p.get(S.id),R=[S.status,S.updatedAt,k?.tabId??S.lockedByTab??"",k?.stale?"stale":"fresh"].join("|"),N=h.current.get(S.id);N&&N!==R&&b.add(S.id),y.set(S.id,R)}if(h.current=y,b.size!==0)return d(b),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{d(new Set),g.current=null},500),()=>{g.current&&(clearTimeout(g.current),g.current=null)}},[p,e]),e.length===0)return null;const x=e.length,v=s>0;return t.jsxs("div",{ref:m,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${v?" background-tasks-indicator__pill--attention":""}`,onClick:()=>c(b=>!b),title:`${x} background AI task${x!==1?"s":""}${s>0?` (${s} need${s!==1?"":"s"} input)`:""}`,children:[n>0&&t.jsx(ot,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(mc,{size:12}),t.jsxs("span",{children:["AI ",x]})]}),l&&t.jsxs("div",{className:"background-tasks-indicator__popover",children:[t.jsx("div",{className:"background-tasks-indicator__popover-header",children:"Background Tasks"}),t.jsx("div",{className:"background-tasks-indicator__popover-list",children:e.map(b=>{const y=lT[b.type],S=b.status==="generating",k=b.status==="awaiting_input",R=b.status==="error",N=p.get(b.id),M=N?.tabId??b.lockedByTab??null,C=!!(M&&M!==f&&!N?.stale),z=u.has(b.id);return t.jsxs("div",{className:`background-tasks-indicator__item${z?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:z?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:z?"translateY(-1px)":void 0},onClick:async()=>{C&&!await o({title:"Open Active Session",message:"This session is active in another tab. Open anyway?"})||(i(b),c(!1))},children:[R?t.jsx(Xn,{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:[R?"Failed":cT[b.type],S&&" — generating...",k&&!C&&" — needs input",k&&C&&" — active in another tab"]})]}),S&&t.jsx(ot,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),k&&!C&&t.jsx(mc,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),k&&C&&t.jsx(Io,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:A=>{A.stopPropagation(),r(b.id)},title:"Dismiss",children:t.jsx(Ot,{size:12})})]},b.id)})})]})]})}function uT(e){if(!e)return"no activity";const n=Date.now(),s=new Date(e).getTime(),i=n-s,r=Math.floor(i/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 mT(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:xn};case"paused":return{label:"Paused",color:"var(--triage)",icon:Gs};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:Pn}}}function hT({tasks:e,projectId:n,taskStuckTimeoutMs:s,backgroundSessions:i,backgroundGenerating:r,backgroundNeedsInput:o,onOpenBackgroundSession:l,onDismissBackgroundSession:c,lastFetchTimeMs:u,currentProjectPath:d,onOpenProjectDirectory:m}){const{stats:h,loading:g,error:p}=oT(e,n,s,u),[f,x]=a.useState(!1),v=a.useMemo(()=>mT(h.executorState),[h.executorState]),b=a.useMemo(()=>uT(h.lastActivityAt),[h.lastActivityAt]),y=v.icon;return p?t.jsx("div",{className:"executor-status-bar executor-status-bar--error",role:"status","aria-label":"Executor status",children:t.jsxs("span",{className:"executor-status-bar__error",children:[t.jsx(Yc,{size:14}),p]})}):g&&h.runningTaskCount===0?t.jsx("div",{className:"executor-status-bar executor-status-bar--loading",role:"status","aria-label":"Executor status",children:t.jsx("span",{className:"executor-status-bar__loading-text",children:"Loading..."})}):t.jsxs("div",{className:`executor-status-bar ${h.executorState==="running"?"executor-status-bar--running":""}`,role:"status","aria-label":"Executor status",children:[i&&i.length>0&&l&&c&&t.jsxs(t.Fragment,{children:[t.jsx(dT,{sessions:i,generating:r??0,needsInput:o??0,onOpenSession:l,onDismissSession:c}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--queued","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Queued"}),t.jsx("span",{className:"executor-status-bar__count",children:h.queuedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--running ${h.runningTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Running"}),t.jsx("span",{className:"executor-status-bar__count",children:h.runningTaskCount}),t.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),t.jsx("span",{className:"executor-status-bar__max",children:h.maxConcurrent})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),h.stuckTaskCount>0&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--stuck",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--stuck executor-status-bar__indicator--active","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Stuck"}),t.jsx("span",{className:"executor-status-bar__count executor-status-bar__count--error",children:h.stuckTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--blocked ${h.blockedTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Blocked"}),t.jsx("span",{className:`executor-status-bar__count ${h.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:h.blockedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--review","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"In Review"}),t.jsx("span",{className:"executor-status-bar__count",children:h.inReviewCount})]}),d&&m&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--project-directory",children:[t.jsx("button",{className:`executor-status-bar__folder-toggle${f?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>x(S=>!S),"aria-label":f?"Hide project directory":"Show project directory","aria-expanded":f,"data-testid":"executor-project-path-toggle",title:f?"Hide project directory":"Show project directory",children:t.jsx(In,{size:12,"aria-hidden":"true"})}),f&&t.jsx("button",{className:"executor-status-bar__project-path",onClick:m,title:d,"data-testid":"executor-project-path-link",children:d})]})]}),t.jsx("div",{className:"executor-status-bar__spacer"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[t.jsx(yi,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:b})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx(y,{size:12,style:{color:v.color},"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__state",style:{color:v.color},children:v.label})]})]})}const pT={planning:Ys,subtask:Ui,mission_interview:ls,milestone_interview:ls,slice_interview:ls},fT={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},$i=new Set;function gT({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:i}){const[r,o]=a.useState(0),l=()=>o(f=>f+1);a.useEffect(()=>{if($i.size===0)return;const f=new Map(e.map(v=>[v.id,v]));let x=!1;for(const v of $i){const b=f.get(v);b&&b.status!=="awaiting_input"&&b.status!=="error"&&($i.delete(v),x=!0)}x&&l()},[e]);const c=a.useMemo(()=>e.filter(f=>(f.status==="awaiting_input"||f.status==="error")&&!$i.has(f.id)),[e,r]);if(c.length===0)return null;const u=c.filter(f=>f.status==="awaiting_input").length,d=c.filter(f=>f.status==="error").length;let m="";u>0&&d>0?m=`${u} AI session${u===1?"":"s"} need${u===1?"s":""} your input, ${d} failed`:u>0?m=`${u} AI session${u===1?"":"s"} need${u===1?"s":""} your input`:d>0&&(m=`${d} AI session${d===1?"":"s"} failed`);const h=f=>{$i.add(f),l()},g=f=>{$i.delete(f.id),l(),n(f)},p=()=>{for(const f of c)$i.add(f.id);l(),i()};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(Xn,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(Ot,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Dismiss all"})]})]}),t.jsx("div",{className:"session-notification-banner__list",children:c.map(f=>{const x=pT[f.type],v=f.status==="error";return t.jsxs("article",{className:`session-notification-banner__item${v?" session-notification-banner__item--error":""}`,"data-session-type":f.type,"data-session-status":f.status,children:[t.jsxs("div",{className:"session-notification-banner__item-main",children:[v?t.jsx(Xn,{size:16,className:"session-notification-banner__type-icon session-notification-banner__type-icon--error","aria-hidden":"true"}):t.jsx(x,{size:16,className:"session-notification-banner__type-icon","aria-hidden":"true"}),t.jsxs("div",{className:"session-notification-banner__text",children:[t.jsx("p",{className:"session-notification-banner__title",title:f.title,children:f.title}),t.jsx("p",{className:"session-notification-banner__meta",children:v?"Failed":fT[f.type]})]})]}),t.jsxs("div",{className:"session-notification-banner__actions",children:[t.jsx("button",{className:"session-notification-banner__resume",onClick:()=>g(f),children:v?"Retry":"Resume"}),t.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{h(f.id),s(f.id)},"aria-label":`Dismiss ${f.title}`,children:t.jsx(Ot,{size:14,"aria-hidden":"true"})})]})]},f.id)})})]})}function xT({latestVersion:e,currentVersion:n,onDismiss:s}){return t.jsxs("div",{className:"update-available-banner",role:"status","aria-live":"polite",children:[t.jsxs("p",{className:"update-available-banner__text",children:["Update available: v",e," (current: v",n,"). Run ",t.jsx("code",{children:"npm i -g @runfusion/fusion"})," to update. "," ",t.jsx("a",{className:"update-available-banner__link",href:"https://github.com/Runfusion/Fusion/releases",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(Ot,{size:16,"aria-hidden":"true"})})]})}function bT({onResume:e}){const n=E4();if(!n)return null;const s=n.completedSteps.length,i=xi.length,r=s>0?`${s} of ${i} 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(qn,{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:()=>{ws("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(xn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function vT({onOpenSettings:e,onOpenModelOnboarding:n}){const s=ja(),i=tg(),[r,o]=a.useState(!0),[l,c]=a.useState(!1),[u,d]=a.useState(!1),[m,h]=a.useState({needsAiProvider:!1,needsDefaultModel:!1,needsGitHub:!1});a.useEffect(()=>{if(!s||i){o(!1);return}let b=!1;return(async()=>{try{o(!0),c(!1);const[S,k]=await Promise.all([mr(),Vi()]);if(b)return;const R=S.providers??[],N=R.find(P=>P.id==="github"),C=!R.some(P=>P.id!=="github"&&P.authenticated),z=!k.defaultProvider&&!k.defaultModelId,A=N?!N.authenticated:!1;h({needsAiProvider:C,needsDefaultModel:z,needsGitHub:A})}catch{b||c(!0)}finally{b||o(!1)}})(),()=>{b=!0}},[s,i]);const g=a.useCallback(()=>{S4(),d(!0)},[]),p=a.useCallback(()=>{n()},[n]),f=a.useCallback(()=>{e("global-models")},[e]),x=a.useCallback(()=>{e("authentication")},[e]),v=a.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:Pn}),m.needsDefaultModel&&b.push({id:"default-model",title:"Select Default Model",description:"Choose a default AI model for task execution",actionLabel:"Choose Model",onAction:f,icon:Vh}),m.needsGitHub&&b.push({id:"github",title:"Connect GitHub",description:"Connect GitHub to import issues and track pull requests",actionLabel:"Connect GitHub",onAction:x,icon:hs}),b},[m.needsAiProvider,m.needsDefaultModel,m.needsGitHub,x,f,p]);return!s||i||u||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(Ys,{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.jsxs("span",{className:"post-onboarding-recommendations__item-icon","aria-hidden":"true",children:[t.jsx(Xn,{size:14,"aria-hidden":!0}),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("button",{type:"button",className:"post-onboarding-recommendations__dismiss",onClick:g,"aria-label":"Dismiss recommendations",children:t.jsx(Ot,{size:16,"aria-hidden":!0})})]})}function yT({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 rc(e){return e>99?"99+":String(e)}function kT({view:e,onChangeView:n,footerVisible:s,modalOpen:i=!1,onOpenSettings:r,onOpenActivityLog:o,onOpenSystemStats:l,onOpenMailbox:c,mailboxUnreadCount:u=0,onOpenGitManager:d,onOpenWorkflowSteps:m,onOpenSchedules:h,onOpenScripts:g,onToggleTerminal:p,onOpenFiles:f,onOpenGitHubImport:x,onOpenPlanning:v,onResumePlanning:b,activePlanningSessionCount:y=0,onOpenUsage:S,onRunScript:k,projectId:R,onViewAllProjects:N,showSkillsTab:M,experimentalFeatures:C}){const z=Cr(),[A,P]=a.useState(!1),[F,W]=a.useState(!1),[$,_]=a.useState({}),[I,O]=a.useState(!1),J=a.useMemo(()=>Object.entries($).sort(([pe],[U])=>pe.localeCompare(U)),[$]);a.useEffect(()=>{if(!F)return;let pe=!1;return O(!0),hr(R).then(U=>{pe||_(U)}).catch(()=>{pe||_({})}).finally(()=>{pe||O(!1)}),()=>{pe=!0}},[F,R]);const Q=a.useCallback(()=>P(!1),[]),E=a.useCallback(pe=>{Q(),pe?.()},[Q]);if(a.useEffect(()=>{if(!A)return;const pe=U=>{U.key==="Escape"&&P(!1)};return document.addEventListener("keydown",pe),()=>document.removeEventListener("keydown",pe)},[A]),z!=="mobile"||i)return null;const D=y>0&&b?b:v,T=!!C?.roadmap,w=!!M,q=!!C?.todoView,G=T&&(!w||e==="roadmaps"),me=w&&(!T||e!=="roadmaps"),ce=w&&!me,ae=e==="documents"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||e==="todos"&&q||e==="roadmaps"&&!G||e==="skills"&&!me;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(Bi,{}),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(gn,{}),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(ls,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Missions"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="chat"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-chat",role:"tab","aria-selected":e==="chat",onClick:()=>n("chat"),children:[t.jsx(bi,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Chat"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="mailbox"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-mailbox",role:"tab","aria-selected":e==="mailbox",onClick:()=>n("mailbox"),children:[t.jsx(ma,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:rc(u)})]}),me&&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(Pn,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),G&&t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="roadmaps"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-roadmaps",role:"tab","aria-selected":e==="roadmaps",onClick:()=>n("roadmaps"),children:[t.jsx(xc,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Roadmaps"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${ae?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>P(pe=>!pe),children:[t.jsx(hc,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),A&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:Q}),t.jsxs("div",{className:"mobile-more-sheet",children:[t.jsx("div",{className:"mobile-more-sheet-handle"}),t.jsx("div",{className:"mobile-more-sheet-title",children:"Navigate"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-mailbox",onClick:()=>E(c),children:[t.jsx(ma,{}),t.jsx("span",{children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:rc(u)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>E(o),children:[t.jsx(Cs,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>E(l),children:[t.jsx(dr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>E(d),children:[t.jsx(Js,{}),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:()=>E(p),children:[t.jsx(ri,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>W(pe=>!pe),"aria-expanded":F,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(hn,{size:14,className:`mobile-more-chevron${F?" mobile-more-chevron--open":""}`})})]}),F&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:I?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(ot,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):J.length>0?t.jsxs(t.Fragment,{children:[J.map(([pe,U])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${pe}`,onClick:()=>{k&&k(pe,U),Q(),W(!1)},children:[t.jsx(xn,{size:14}),t.jsx("span",{children:pe})]},pe)),g&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{Q(),W(!1),g()},children:[t.jsx(Is,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):g&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":"mobile-more-scripts-manage",onClick:()=>{Q(),W(!1),g()},children:[t.jsx(Is,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>E(f),children:[t.jsx(In,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>E(D),children:[t.jsx(Ys,{}),t.jsx("span",{children:"Planning"}),y>0&&t.jsx("span",{className:"mobile-more-item-badge",children:rc(y)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>E(m),children:[t.jsx(vc,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>E(h),children:[t.jsx(yi,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>E(x),children:[t.jsx(yT,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>E(S),children:[t.jsx(Cs,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>E(N),children:[t.jsx(qh,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>E(()=>n("documents")),children:[t.jsx(Oi,{}),t.jsx("span",{children:"Documents"})]}),ce&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>E(()=>n("skills")),children:[t.jsx(Pn,{}),t.jsx("span",{children:"Skills"})]}),T&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-roadmaps",onClick:()=>E(()=>n("roadmaps")),children:[t.jsx(xc,{}),t.jsx("span",{children:"Roadmaps"})]}),C?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>E(()=>n("insights")),children:[t.jsx(qn,{}),t.jsx("span",{children:"Insights"})]}),C?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>E(()=>n("memory")),children:[t.jsx(co,{}),t.jsx("span",{children:"Memory"})]}),C?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{E(()=>n("dev-server"))},children:[t.jsx(dr,{size:14}),t.jsx("span",{children:"Dev Server"})]}),q&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>E(()=>n("todos")),children:[t.jsx(Gh,{size:14}),t.jsx("span",{children:"Todos"})]}),t.jsx("div",{className:"mobile-more-separator"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-settings",onClick:()=>E(r),children:[t.jsx(sr,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function jT({agents:e,filter:n,highlightedIndex:s,visible:i,onSelect:r,position:o="below"}){const l=a.useMemo(()=>{const c=n.trim().toLowerCase();return c?e.filter(u=>u.name.toLowerCase().includes(c)):e},[e,n]);return i?t.jsx("div",{className:`agent-mention-popup agent-mention-popup--${o}`,"data-testid":"agent-mention-popup",role:"listbox","aria-label":"Agent mention suggestions",children:l.length===0?t.jsx("div",{className:"agent-mention-empty",children:"No agents found"}):l.map((c,u)=>t.jsxs("button",{type:"button",className:`agent-mention-item${u===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${c.id}`,onMouseDown:d=>d.preventDefault(),onClick:()=>r(c),role:"option","aria-selected":u===s,children:[t.jsx(gn,{size:14,"aria-hidden":"true"}),t.jsx("span",{className:"agent-mention-name",children:c.name}),t.jsx("span",{className:"agent-mention-role",children:c.role})]},c.id))}):null}const Sd="__fn_agent__";function rg(e,n){const s=typeof e=="string"?e.trim():"",i=typeof n=="string"?n.trim():"";return!s||!i?{}:{modelProvider:s,modelId:i}}function jh(e,n,s){const i=typeof e=="string"?e.trim():"",r=rg(n,s),o=i||(r.modelProvider&&r.modelId?Sd:"");return o?{agentId:o,...r}:null}function oc(e,n,s){const i=rg(n,s),r=i.modelProvider??"",o=i.modelId??"";return`${e}::${r}/${o}`}function wT(e){const n=e?.toolCalls;if(!Array.isArray(n))return;const s=n.map(i=>{if(!i||typeof i!="object")return null;const r=i,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(i=>i!==null);return s.length>0?s:void 0}function wh(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:wT(e.metadata),createdAt:e.createdAt}}function NT(e,n){const[s,i]=a.useState(null),[r,o]=a.useState(!1),[l,c]=a.useState([]),[u,d]=a.useState(!1),[m,h]=a.useState(!1),[g,p]=a.useState(""),[f,x]=a.useState(""),[v,b]=a.useState([]),[y,S]=a.useState(""),k=a.useRef(null),R=a.useRef(!1),N=a.useRef(""),M=a.useRef(""),C=a.useRef(null);a.useEffect(()=>{N.current=y},[y]);const z=a.useCallback(async Q=>{const E={agentId:Q.agentId};return Q.modelProvider&&Q.modelId&&(E.modelProvider=Q.modelProvider,E.modelId=Q.modelId),(await Kj(E,e)).session},[e]),A=a.useCallback(async(Q,E,D)=>{const T=jh(Q,E,D);if(!T)return;const w=oc(T.agentId,T.modelProvider,T.modelId);o(!0);try{const{session:q}=await Wj({agentId:T.agentId,modelProvider:T.modelProvider,modelId:T.modelId},e);if(q)i(q),M.current=w;else{const G=await z(T);i(G),M.current=w}}catch(q){console.error("[useQuickChat] Failed to initialize session:",q),n?.("Failed to initialize chat","error")}finally{o(!1)}},[e,n,z]),P=a.useCallback(async()=>{if(s){d(!0);try{const Q=await Xd(s.id,{limit:50},e);c(Q.messages.map(wh))}catch(Q){console.error("[useQuickChat] Failed to load messages:",Q)}finally{d(!1)}}},[s,e]);a.useEffect(()=>{s?P():c([])},[s,P]);const F=a.useCallback(async()=>{if(s){d(!0);try{const Q=await Xd(s.id,{limit:50},e);c(Q.messages.map(wh))}catch(Q){console.error("[useQuickChat] Failed to reload messages:",Q)}finally{d(!1)}}},[s,e]),W=a.useCallback(async(Q,E,D)=>{const T=jh(Q,E,D);if(!T)return;const w=oc(T.agentId,T.modelProvider,T.modelId);C.current=T;const q=w===M.current&&s;if(q||(k.current&&(k.current.close(),k.current=null),p(""),x(""),b([]),h(!1)),q){await F();return}i(null),c([]),M.current=w,await A(T.agentId,T.modelProvider,T.modelId)},[A,F,s]),$=a.useCallback(async(Q,E)=>{await W(Sd,Q,E)},[W]),_=a.useCallback(async()=>{const Q=C.current;if(!Q)return;const E=oc(Q.agentId,Q.modelProvider,Q.modelId);k.current&&(k.current.close(),k.current=null),p(""),x(""),b([]),h(!1),c([]),i(null),o(!0);try{const D=await z(Q);i(D),M.current=E}catch(D){console.error("[useQuickChat] Failed to start a fresh session:",D),n?.("Failed to start a new chat","error")}finally{o(!1)}},[n,z]),I=a.useCallback(()=>{s&&(R.current=!0,k.current?.close(),k.current=null,Gj(s.id,e).catch(()=>{}),h(!1),p(""),x(""),b([]))},[s,e]),O=a.useCallback(()=>{N.current="",S("")},[]),J=a.useCallback(Q=>{if(!s||!Q.trim())return;if(m){N.current=Q,S(Q);return}R.current=!1,k.current&&(k.current.close(),k.current=null);const D={id:`temp-${Date.now()}`,sessionId:s.id,role:"user",content:Q,createdAt:new Date().toISOString()};c(me=>[...me,D]),p(""),x(""),b([]),h(!0);let T="",w="",q=[];const G={onThinking:me=>{w+=me,x(w)},onText:me=>{T+=me,p(T)},onToolStart:me=>{q=[...q,{toolName:me.toolName,args:me.args,isError:!1,status:"running"}],b(q)},onToolEnd:me=>{const ce=[...q];for(let ae=ce.length-1;ae>=0;ae--){const pe=ce[ae];if(pe?.toolName===me.toolName&&pe.status==="running"){ce[ae]={...pe,status:"completed",isError:me.isError,result:me.result},q=ce,b(ce);return}}q=[...ce,{toolName:me.toolName,isError:me.isError,result:me.result,status:"completed"}],b(q)},onDone:me=>{const ce={id:me.messageId||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:T,thinkingOutput:w||void 0,toolCalls:q.length>0?q:void 0,createdAt:new Date().toISOString()};c(pe=>[...pe,ce]),p(""),x(""),b([]),h(!1),k.current=null;const ae=N.current.trim();ae&&(N.current="",S(""),J(ae))},onError:me=>{if(p(""),x(""),b([]),h(!1),k.current=null,console.error("[useQuickChat] Stream error:",me),n?.("Failed to get response","error"),!R.current){const ce=N.current.trim();ce&&(N.current="",S(""),J(ce))}F()}};k.current=Jj(s.id,Q,G,e)},[s,m,e,n,F]);return a.useEffect(()=>()=>{k.current&&(k.current.close(),k.current=null)},[]),a.useMemo(()=>({activeSession:s,sessionsLoading:r,messages:l,messagesLoading:u,isStreaming:m,streamingText:g,streamingThinking:f,streamingToolCalls:v,pendingMessage:y,sendMessage:J,stopStreaming:I,clearPendingMessage:O,switchSession:W,startModelChat:$,startFreshSession:_,loadMessages:P,reloadMessages:F}),[s,r,l,u,m,g,f,v,y,J,I,O,W,$,_,P,F])}function ST(e,n){const[s,i]=a.useState([]),[r,o]=a.useState(null),[l,c]=a.useState(!1),u=a.useCallback(async g=>{c(!0);try{const p=n?.filterState,f=p&&p!=="all"?{state:p}:void 0,x=n?.showSystemAgents??!1,v=await Na({...f,...g,includeEphemeral:g?.includeEphemeral??x},e),b=Array.from(new Map(v.map(y=>[y.id,y])).values());i(b)}catch(p){console.error("Failed to load agents:",p)}finally{c(!1)}},[e,n?.filterState,n?.showSystemAgents]),d=a.useCallback(async()=>{try{const g=await Ek(e);o(g)}catch(g){console.error("Failed to load agent stats:",g)}},[e]);a.useEffect(()=>{u(),d()},[u,d]),a.useEffect(()=>{const g=e?`?projectId=${encodeURIComponent(e)}`:"",p=()=>{u(),d()};return Ls(`/api/events${g}`,{events:{"agent:created":p,"agent:updated":p,"agent:deleted":p,"agent:stateChanged":p}})},[e,u,d]);const m=n?.showSystemAgents??!1,h=s.filter(g=>g.state!=="active"&&g.state!=="running"?!1:m||!mw(g));return{agents:s,activeAgents:h,stats:r,isLoading:l,loadAgents:u,loadStats:d}}function CT({visible:e,position:n,files:s,selectedIndex:i,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 u=l.path.includes("/")?l.path.slice(0,l.path.lastIndexOf("/")+1):"",d=l.name;return t.jsxs("li",{className:`file-mention-popup-item${c===i?" file-mention-popup-item--selected":""}`,onClick:()=>r(l),onMouseEnter:()=>{},role:"option","aria-selected":c===i,"data-testid":`file-mention-item-${c}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(Bh,{size:14})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsx("span",{className:"file-mention-popup-item-name",children:d}),u&&t.jsx("span",{className:"file-mention-popup-item-path",children:u})]})]},l.path)})})]}):null}const ET=200;function _T(e={}){const{projectId:n,workspace:s="project"}=e,[i,r]=a.useState(!1),[o,l]=a.useState(""),[c,u]=a.useState(-1),[d,m]=a.useState([]),[h,g]=a.useState(!1),[p,f]=a.useState(0),x=a.useRef(null),v=a.useRef(null);a.useEffect(()=>()=>{x.current&&clearTimeout(x.current),v.current?.abort()},[]);const b=a.useCallback((N,M)=>{if(M<0||M>N.length){r(!1);return}const C=z=>/[a-zA-Z0-9/_.-]/.test(z);for(let z=M-1;z>=0;z--){if(N[z]==="#")if(z===0){const A=N.slice(z+1,M);u(z),l(A),f(0),r(!0);return}else{const A=N[z-1];if(/[\s,.;:!?'"()[\]{}]/.test(A)){const P=N.slice(z+1,M);u(z),l(P),f(0),r(!0);return}r(!1);return}if(!C(N[z])){r(!1);return}}r(!1)},[]),y=a.useCallback(()=>{r(!1),l(""),u(-1),m([]),f(0),g(!1)},[]),S=a.useCallback(async N=>{if(!N.trim()){m([]),g(!1);return}v.current?.abort(),v.current=new AbortController;try{g(!0);const M=await $y(N,s,n);m(M.files),f(0)}catch(M){M.name!=="AbortError"&&m([])}finally{g(!1)}},[s,n]);a.useEffect(()=>{if(i)return x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{S(o)},ET),()=>{x.current&&clearTimeout(x.current)}},[o,i,S]);const k=a.useCallback((N,M)=>{if(!i||c<0)return M;const C=M.slice(0,c),z=M.slice(c+1),A=z.match(/[\s]|$/),P=A?A.index:z.length,F=z.slice(P);return`${C}#${N.path}${F}`},[i,c]),R=a.useCallback((N,M)=>{if(!i||d.length===0)return!1;switch(N.key){case"ArrowDown":return N.preventDefault(),f(C=>Math.min(C+1,d.length-1)),!0;case"ArrowUp":return N.preventDefault(),f(C=>Math.max(C-1,0)),!0;case"Enter":case"Tab":return d[p]?(N.preventDefault(),!0):!1;case"Escape":return N.preventDefault(),y(),!0;default:return!1}},[i,d,p,y]);return{mentionActive:i,files:d,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:f,detectMention:b,selectFile:k,dismissMention:y,handleKeyDown:R}}function MT(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let lc=null;function AT(){return lc===null&&(lc=window.innerHeight),lc}function RT(){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 i=AT()-e.offsetTop-e.height;return i>=30&&i>80?i:0}function TT({enabled:e=!0}={}){const[n,s]=a.useState(0),[i,r]=a.useState(null);return a.useEffect(()=>{if(!e||!MT()){s(0),r(null);return}const o=window.visualViewport;if(!o){s(0),r(null);return}const l=()=>{const c=RT();s(c),r(c>0?o.height:null)};return l(),o.addEventListener("resize",l),o.addEventListener("scroll",l),()=>{o.removeEventListener("resize",l),o.removeEventListener("scroll",l),s(0),r(null)}},[e]),{keyboardOverlap:n,viewportHeight:i}}function PT(e){return`${e.name?.trim()||e.id} (${e.role})`}function IT(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 $T(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 oo(e,n){return e.length>n?`${e.slice(0,n)}…`:e}function DT(e){if(!e)return null;const n=Object.entries(e);return n.length===0?null:n.map(([s,i])=>{let r="";if(typeof i=="string")r=i;else try{r=JSON.stringify(i)}catch{r=String(i)}return`${s}=${oo(r,50)}`}).join(", ")}function LT(e){if(e===void 0)return null;if(typeof e=="string")return oo(e,200);try{return oo(JSON.stringify(e),200)}catch{return oo(String(e),200)}}function Nh(e,n=!1){return!e||e.length===0?null:t.jsxs("div",{className:`chat-tool-calls${n?" chat-tool-calls--compact":""}`,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(Xb,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:"Tool calls"})]}),e.map((s,i)=>{const r=s.status==="running",o=s.status==="completed"&&s.isError,l=DT(s.args),c=LT(s.result),u=r?l:c?`result: ${c}`:l?`args: ${l}`:null,d=r?"running":o?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${r?" chat-tool-call--running":""}${o?" chat-tool-call--error":""}`,open:r,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",children:s.toolName}),u&&t.jsx("span",{className:"chat-tool-call-preview",title:u,children:u}),t.jsx("span",{className:"chat-tool-call-status-text",children:d})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[l&&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:l})]}),c&&t.jsxs("div",{className:`chat-tool-call-row${o?" 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:c})]})]})]},`${s.toolName}-${i}`)})]})}const zT={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 FT(e,n){const s=e.slice(0,n),i=/(^|[\s])@([\w-]*)$/.exec(s);if(!i)return null;const r=i[2]??"",o=s.length-r.length-1;return{filter:r,start:o,end:n}}const io={width:320,height:400},ia={width:280,height:260},Kc=768,aa=8;function OT(e,n){const s=a.useCallback(()=>{if(typeof window>"u")return 0;const x=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return x&&parseFloat(x)||0},[]),i=a.useCallback(()=>typeof window<"u"&&window.innerWidth<=768?{x:4,y:4+s()}:{x:24,y:24+s()},[s]),[r,o]=a.useState(()=>{if(typeof window>"u")return i();const x=`fusion-quick-chat-position-${e||"default"}`;try{const v=localStorage.getItem(x);if(v){const b=JSON.parse(v);if(typeof b.x=="number"&&typeof b.y=="number"&&!isNaN(b.x)&&!isNaN(b.y))return b}}catch{}return i()}),[l,c]=a.useState(!1),u=a.useRef(null),d=n??a.useRef(!1),m=a.useCallback(x=>{if(typeof window>"u")return x;const v=48,b=window.innerWidth<=768?4:8,y=window.innerWidth<=768?44:0,S=window.innerWidth>768?s():0,k=window.innerWidth-v-b,R=window.innerHeight-v-b-y-S;return{x:Math.max(b,Math.min(k,x.x)),y:Math.max(b,Math.min(R,x.y))}},[s]),h=a.useCallback(x=>{if(typeof window>"u")return;const v=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(v,JSON.stringify(x))}catch{}},[e]),g=a.useCallback(x=>{if(x.button!==0&&x.pointerType==="mouse")return;const b=x.target.closest(".quick-chat-fab");b&&(x.preventDefault(),typeof b.setPointerCapture=="function"&&b.setPointerCapture(x.pointerId),u.current={x:r.x,y:r.y,pointerX:x.clientX,pointerY:x.clientY},d.current=!1,c(!0),document.body.style.userSelect="none")},[r]),p=a.useCallback(x=>{if(!u.current||!l)return;const v=x.clientX-u.current.pointerX,b=x.clientY-u.current.pointerY;if((Math.abs(v)>=5||Math.abs(b)>=5)&&(d.current=!0),d.current){const y=u.current.x-v,S=u.current.y-b,k=m({x:y,y:S});o(k)}},[l,m]),f=a.useCallback(x=>{if(!u.current)return;const v=x.target.closest(".quick-chat-fab");if(v&&typeof v.releasePointerCapture=="function"&&v.releasePointerCapture(x.pointerId),c(!1),document.body.style.userSelect="",!d.current){u.current=null;return}h(r),u.current=null,d.current=!1},[r,h]);return{position:r,isDragging:l,handlePointerDown:g,handlePointerMove:p,handlePointerUp:f}}function UT(e,n,s){const i=`fusion:quick-chat-size-${e||"default"}`,r=a.useCallback(()=>typeof window<"u"&&window.innerWidth>Kc,[]),o=a.useCallback((g,p,f)=>{if(typeof window>"u")return g;const x=Math.max(ia.width,window.innerWidth-p-aa),v=Math.max(ia.height,window.innerHeight-f-aa);return{width:Math.max(ia.width,Math.min(x,g.width)),height:Math.max(ia.height,Math.min(v,g.height))}},[]),l=a.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=Kc)return io;try{const g=localStorage.getItem(i);if(!g)return io;const p=JSON.parse(g);return typeof p.width!="number"||typeof p.height!="number"?io:{width:p.width,height:p.height}}catch{return io}},[i]),[c,u]=a.useState(l),[d,m]=a.useState({right:0,bottom:0});a.useEffect(()=>{if(!r())return;const g={right:n+d.right,bottom:s+d.bottom};u(p=>o(p,g.right,g.bottom))},[o,r,n,s,d]),a.useEffect(()=>{if(r())try{localStorage.setItem(i,JSON.stringify(c))}catch{}},[r,c,i]);const h=a.useCallback(g=>{if(!r())return;const p=g.currentTarget.dataset.resizeDirection;if(!p)return;g.preventDefault(),g.stopPropagation();const f=g.currentTarget;typeof f.setPointerCapture=="function"&&f.setPointerCapture(g.pointerId);const x={pointerX:g.clientX,pointerY:g.clientY,width:c.width,height:c.height,anchorRight:d.right,anchorBottom:d.bottom};document.body.style.userSelect="none";const v=y=>{const S=y.clientX-x.pointerX,k=y.clientY-x.pointerY;let R=x.width,N=x.height,M=x.anchorRight,C=x.anchorBottom;if(p.includes("w")&&(R=x.width-S),p.includes("e")){const $=S;R=x.width+$,M=x.anchorRight-$}if(p.includes("n")&&(N=x.height-k),p.includes("s")){const $=k;N=x.height+$,C=x.anchorBottom-$}const z=n+M,A=s+C,P=o({width:R,height:N},z,A),F=Math.max(aa-n,Math.min(window.innerWidth-n-ia.width-aa,M)),W=Math.max(aa-s,Math.min(window.innerHeight-s-ia.height-aa,C));u(P),m({right:F,bottom:W})},b=y=>{typeof f.releasePointerCapture=="function"&&f.releasePointerCapture(y.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b);try{localStorage.setItem(i,JSON.stringify({width:c.width,height:c.height}))}catch{}};document.addEventListener("pointermove",v),document.addEventListener("pointerup",b)},[d.bottom,d.right,o,s,n,r,c.height,c.width,i]);return{panelSize:c,anchorOffset:d,handleResizeStart:h}}function BT({projectId:e,addToast:n,showFAB:s=!0,open:i,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:u}){const{agents:d}=ST(e),[m,h]=a.useState(!1),g=i!==void 0,p=g?i:m,f=g?te=>{r?.(typeof te=="function"?te(p):te)}:h,{keyboardOverlap:x,viewportHeight:v}=TT({enabled:p}),b=x>0?{"--keyboard-overlap":`${x}px`,...v!==null?{"--vv-height":`${v}px`}:{}}:{},[y,S]=a.useState("agent"),[k,R]=a.useState(""),[N,M]=a.useState([]),[C,z]=a.useState(!1),[A,P]=a.useState(""),[F,W]=a.useState(""),[$,_]=a.useState(""),[I,O]=a.useState(!1),[J,Q]=a.useState(0),[E,D]=a.useState(-1),[T,w]=a.useState(()=>new Set),[,q]=a.useState(!1),[G,me]=a.useState({top:0,left:0}),ce=_T({projectId:e}),ae=a.useCallback(te=>{if(!te||!ce.mentionActive)return;const j=te.getBoundingClientRect();me({top:j.top-260,left:j.left+8})},[ce.mentionActive]),pe=a.useRef(!1),U=a.useRef(!1),Ne=a.useRef(""),ne=a.useRef(0),xe=a.useRef(null),{position:le,isDragging:ve,handlePointerDown:ee,handlePointerMove:Ee,handlePointerUp:Fe}=OT(e,pe),Ke=le.y+60,{panelSize:Ze,anchorOffset:Xe,handleResizeStart:Qe}=UT(e,le.x,Ke),it=typeof window<"u"&&window.innerWidth>Kc,{activeSession:Ie,messages:Ge,isStreaming:se,streamingText:ye,streamingThinking:Z,streamingToolCalls:Te,sessionsLoading:ze,messagesLoading:be,sendMessage:Me,stopStreaming:Be,pendingMessage:lt,clearPendingMessage:je,switchSession:ie,startModelChat:Ae,startFreshSession:he}=NT(e,n),Re=a.useRef(null),Je=a.useRef(null),$e=a.useRef(null),de=a.useRef(null),re=a.useMemo(()=>IT(A),[A]),ue=a.useMemo(()=>N.find(te=>`${te.provider}/${te.id}`===A)??null,[N,A]),Pe=a.useMemo(()=>$T(ue,re),[ue,re]),Se=a.useMemo(()=>y==="model"?re?`${Sd}::${re.modelProvider}/${re.modelId}`:"":k?`${k}::`:"",[y,re,k]),fe=y==="agent"?!!k:!!re;a.useEffect(()=>{if(d.length===0){R(""),S("model");return}d.some(j=>j.id===k)||R(d[0]?.id??"")},[d,k]),a.useEffect(()=>{!p||U.current||(U.current=!0,z(!0),cs().then(te=>{const j=te.models??[];if(M(j),A||j.length===0)return;const V=te.defaultProvider,De=te.defaultModelId;if(V&&De){const nt=`${V}/${De}`;if(j.some(Pt=>`${Pt.provider}/${Pt.id}`===nt)){P(nt),S("model");return}}if(d.length===0){const nt=j[0];nt&&P(`${nt.provider}/${nt.id}`)}}).catch(te=>{console.error("[QuickChatFAB] Failed to load models:",te),M([])}).finally(()=>{z(!1)}))},[p,d.length,A]),a.useEffect(()=>{if(!p){Ne.current="";return}if(!Se){Ne.current="";return}const te=Se===Ne.current&&!Ie&&!ze;if(!(Se===Ne.current&&!te)){if(Ne.current=Se,y==="model"&&re){Ae(re.modelProvider,re.modelId);return}y==="agent"&&k&&ie(k)}},[p,y,re,k,Se,Ie,ze,Ae,ie]),a.useEffect(()=>{p||(O(!1),_(""),D(-1))},[p]);const tt=a.useCallback(te=>{R(te)},[]),ut=a.useCallback(te=>{P(te)},[]),vt=a.useCallback(()=>{!fe||ze||he()},[fe,ze,he]),gt=a.useMemo(()=>d.find(te=>te.id===k)??null,[d,k]),dt=a.useMemo(()=>{const te=$.trim().toLowerCase();return te?d.filter(j=>j.name.toLowerCase().includes(te)):d},[d,$]),wt=a.useMemo(()=>{const te=new Map;for(const j of d)te.set(j.name.toLowerCase(),j);return te},[d]);a.useEffect(()=>{Q(0)},[$,I]),a.useEffect(()=>()=>{xe.current!==null&&(window.clearTimeout(xe.current),xe.current=null)},[]),a.useEffect(()=>{if(!p)return;const te=V=>{const De=V.target;Re.current?.contains(De)||Je.current?.contains(De)||De.closest(".model-combobox-dropdown--portal")||f(!1)},j=V=>{V.key==="Escape"&&f(!1)};return document.addEventListener("mousedown",te),document.addEventListener("keydown",j),()=>{document.removeEventListener("mousedown",te),document.removeEventListener("keydown",j)}},[p,f]),a.useEffect(()=>{if(!p)return;const te=$e.current;te&&(te.scrollTop=te.scrollHeight)},[Ge,ye,Z,p]);const Mt=a.useMemo(()=>y==="agent"?gt?`Message ${gt.name||gt.id}`:"Select an agent to start chatting":Pe?`Message ${Pe}`:"Select a model to start chatting",[y,gt,Pe]),yt=!fe||!Ie,Et=lt.length>50?`${lt.slice(0,50)}…`:lt,Nt=a.useCallback(()=>{const te=F.trim();!te||yt||(W(""),O(!1),_(""),D(-1),Me(te))},[Me,yt,F]),Tt=a.useCallback((te,j)=>{const V=FT(te,j);if(V){O(!0),_(V.filter),D(V.start);return}O(!1),_(""),D(-1)},[]),Ht=a.useCallback(te=>{const j=de.current;if(!j||E<0)return;const V=j.selectionStart??ne.current,De=j.selectionEnd??V,nt=Math.max(V,De),St=Math.min(E,nt),Rt=`${`@${te.name.replace(/\s+/g,"_")}`} `,un=F.slice(0,St)+Rt+F.slice(nt),mn=St+Rt.length;W(un),O(!1),_(""),Q(0),D(-1),window.requestAnimationFrame(()=>{de.current&&(de.current.focus(),de.current.setSelectionRange(mn,mn))})},[E,F]),Ut=a.useCallback(te=>{const j=te.target.value,V=te.target.selectionStart??j.length;ne.current=V,W(j),Tt(j,V),ce.detectMention(j,V),q(ce.mentionActive),ce.mentionActive&&ae(te.target)},[Tt,ce,ae]),Vt=a.useCallback(()=>{xe.current!==null&&window.clearTimeout(xe.current),xe.current=window.setTimeout(()=>{O(!1),_(""),D(-1),q(!1),ce.dismissMention(),xe.current=null},120)},[ce]),zt=a.useCallback(()=>{xe.current!==null&&(window.clearTimeout(xe.current),xe.current=null)},[]),Ct=a.useCallback(te=>{const j=te.currentTarget,V=j.selectionStart??j.value.length;ne.current=V,Tt(j.value,V),ce.detectMention(j.value,V),q(ce.mentionActive),ce.mentionActive&&ae(j)},[Tt,ce,ae]),At=a.useCallback(te=>{te.key!=="Escape"&&Ct(te)},[Ct]),kt=a.useCallback(te=>{const j=/@([\w-]+)/g,V=[];let De=0,nt=j.exec(te);for(;nt;){const[St,Pt=""]=nt,Rt=nt.index;Rt>De&&V.push(te.slice(De,Rt));const un=Pt.replace(/_/g," ").toLowerCase(),mn=wt.get(un);mn?V.push(t.jsxs("span",{className:"chat-mention-chip",children:["@",mn.name.replace(/\s+/g,"_")]},`${mn.id}-${Rt}`)):V.push(St),De=Rt+St.length,nt=j.exec(te)}return De<te.length&&V.push(te.slice(De)),V.length===0?te:V},[wt]),Kt=a.useCallback(te=>{w(j=>{const V=new Set(j);return V.has(te)?V.delete(te):V.add(te),V})},[]),$t=a.useCallback((te,j=!1)=>j?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:te}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(ci,{remarkPlugins:[di],components:zT,children:te})}),[]),B=a.useCallback(te=>{if(ne.current=te.currentTarget.selectionStart??ne.current,ce.mentionActive&&ce.files.length>0){if(ce.handleKeyDown(te,F),te.key==="Enter"||te.key==="Tab"){const j=ce.files[ce.selectedIndex];if(j){const V=ce.selectFile(j,F);W(V),ce.dismissMention(),q(!1)}}return}if(I&&te.key==="ArrowDown"){te.preventDefault(),dt.length>0&&Q(j=>(j+1)%dt.length);return}if(I&&te.key==="ArrowUp"){te.preventDefault(),dt.length>0&&Q(j=>j===0?dt.length-1:j-1);return}if(I&&te.key==="Enter"){te.preventDefault();const j=dt[J]??dt[0];j&&Ht(j);return}if(I&&te.key==="Escape"){te.preventDefault(),te.stopPropagation(),O(!1),_(""),D(-1);return}te.key!=="Enter"||te.shiftKey||(te.preventDefault(),Nt())},[I,dt,J,Ht,Nt,ce,F]),ge=a.useCallback(()=>{if(pe.current){pe.current=!1;return}f(te=>!te)},[f]);return t.jsxs(t.Fragment,{children:[s&&t.jsx("button",{ref:Je,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":ve?"true":"false",style:{right:le.x,bottom:le.y},onPointerDown:ee,onPointerMove:Ee,onPointerUp:Fe,onClick:ge,children:t.jsx(bi,{size:24})}),p&&t.jsxs("div",{className:"quick-chat-panel",ref:Re,"data-testid":"quick-chat-panel",style:{right:le.x+Xe.right,bottom:Ke+Xe.bottom,...it?{width:Ze.width,height:Ze.height}:{},...b},children:[it&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:Qe,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:Qe,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:Qe,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:Qe,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:Qe,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:Qe,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:Qe,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:Qe,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"}),Pe&&t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:Pe,children:Pe})]}),t.jsxs("div",{className:"quick-chat-panel-header-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm","data-testid":"quick-chat-new-thread",onClick:vt,disabled:!fe||ze,children:"New chat"}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":"Close quick chat","data-testid":"quick-chat-close",onClick:()=>f(!1),children:t.jsx(Ot,{size:16})})]})]}),d.length>0&&t.jsxs("div",{className:"quick-chat-mode-toggle","data-testid":"quick-chat-mode-toggle",children:[t.jsx("button",{type:"button",className:`quick-chat-mode-btn${y==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-agent",onClick:()=>{S("agent"),P("")},children:"Agent"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${y==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-model",onClick:()=>{S("model"),R("")},children:"Model"})]}),y==="agent"&&d.length>0&&t.jsxs("div",{className:"quick-chat-panel-agent-select",children:[t.jsx("label",{htmlFor:"quick-chat-agent-select",className:"visually-hidden",children:"Select agent"}),t.jsx("select",{id:"quick-chat-agent-select",value:k,onChange:te=>tt(te.target.value),"data-testid":"quick-chat-agent-select",children:d.map(te=>t.jsx("option",{value:te.id,children:PT(te)},te.id))})]}),y==="model"&&t.jsxs("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-model-select",children:[t.jsx("label",{htmlFor:"quick-chat-model-override",className:"visually-hidden",children:"Select model override"}),t.jsx($n,{id:"quick-chat-model-override",models:N,value:A,onChange:ut,label:"Select model override",placeholder:C?"Loading models…":"Select a model",disabled:C||N.length===0,favoriteProviders:o,favoriteModels:l,onToggleFavorite:c,onToggleModelFavorite:u})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:$e,"data-testid":"quick-chat-messages",children:ze||be?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):Ge.length===0&&!ye&&!Z&&!se?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[Ge.map(te=>{const j=te.role==="user",V=!j&&T.has(te.id);return t.jsxs("div",{className:`quick-chat-panel-message ${j?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${te.id}`,children:[j?t.jsx("p",{children:kt(te.content)}):t.jsxs(t.Fragment,{children:[$t(te.content,V),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${V?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":V?"Show rendered markdown":"Show plain text",onClick:()=>Kt(te.id),children:V?t.jsx(pc,{size:14}):t.jsx(da,{size:14})})]}),Nh(te.toolCalls,!0)]},te.id)}),se&&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:[ye?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:$t(ye,T.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${T.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":T.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>Kt("__streaming__"),children:T.has("__streaming__")?t.jsx(pc,{size:14}):t.jsx(da,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:"Thinking…"}),Nh(Te,!0),Z&&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:Z})]})]})]})}),t.jsxs("div",{className:"quick-chat-panel-input",children:[t.jsxs("div",{className:"quick-chat-input-wrapper",children:[t.jsx("input",{ref:de,type:"text",value:F,onChange:Ut,onKeyDown:B,onKeyUp:At,onClick:Ct,onBlur:Vt,onFocus:zt,placeholder:Mt,disabled:yt,"data-testid":"quick-chat-input"}),t.jsx(jT,{agents:d,filter:$,highlightedIndex:J,visible:I,onSelect:Ht,position:"above"}),t.jsx(CT,{visible:ce.mentionActive&&!I,position:G,files:ce.files,selectedIndex:ce.selectedIndex,onSelect:te=>{const j=ce.selectFile(te,F);W(j),ce.dismissMention(),q(!1),de.current?.focus()},loading:ce.loading}),lt&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${Et}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:je,children:"×"})]})]}),se?t.jsx("button",{type:"button",className:"chat-input-stop",onClick:Be,"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(ms,{size:14})}):t.jsx("button",{type:"button",onClick:()=>void Nt(),disabled:yt||F.trim().length===0,"data-testid":"quick-chat-send",children:t.jsx(Di,{size:16})})]})]})]})}function Ya(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Sh(e){return e.status==="generating"||e.status==="awaiting_input"}function Qa(e){return e==="complete"||e==="error"}function HT(e){const[n,s]=a.useState([]),i=a.useRef(new Map),r=a.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:u}=Sa(),d=a.useCallback(()=>{Zc(e).then(p=>{const f=p.filter(v=>{const b=Ya(v.updatedAt),y=r.current.get(v.id);return y===void 0?!0:b<=y?!1:(r.current.delete(v.id),!0)}),x=new Map;for(const v of f)x.set(v.id,Ya(v.updatedAt));i.current=x,s(f)}).catch(p=>{console.warn("[useBackgroundSessions] Failed to fetch AI sessions:",p)})},[e]);a.useEffect(()=>{u(),d()},[d,u]),a.useEffect(()=>{s(p=>{if(o.size===0)return p;let f=!1;const x=new Map(p.map(v=>[v.id,v]));for(const v of o.values()){if(e&&v.projectId&&v.projectId!==e)continue;const b=v.lastEventTimestamp,y=i.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&&!Qa(v.status)&&r.current.delete(v.sessionId),Qa(v.status)){x.delete(v.sessionId)&&(f=!0),i.current.set(v.sessionId,b);continue}const k=x.get(v.sessionId),R=v.type??k?.type,N=v.title??k?.title;if(!k&&(!R||!N))continue;const M={id:v.sessionId,type:R??"planning",status:v.status,title:N??"AI Session",projectId:v.projectId??k?.projectId??e??null,lockedByTab:v.owningTabId??k?.lockedByTab??null,updatedAt:v.updatedAt??k?.updatedAt??new Date(b).toISOString()},C=x.get(v.sessionId);(!C||C.status!==M.status||C.title!==M.title||C.type!==M.type||C.projectId!==M.projectId||C.lockedByTab!==M.lockedByTab||C.updatedAt!==M.updatedAt)&&(x.set(v.sessionId,M),i.current.set(v.sessionId,b),f=!0)}return f?[...x.values()].sort((v,b)=>Ya(b.updatedAt)-Ya(v.updatedAt)):p})},[e,o]),a.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",f=v=>{try{const b=JSON.parse(v.data),y=Ya(b.updatedAt)||Date.now();s(S=>{const k=i.current.get(b.id)??0;if(y<k)return S;const R=r.current.get(b.id);if(R!==void 0&&y<=R)return S;if(R!==void 0&&y>R&&!Qa(b.status)&&r.current.delete(b.id),i.current.set(b.id,y),Qa(b.status))return S.filter(M=>M.id!==b.id);const N=S.findIndex(M=>M.id===b.id);if(N>=0){const M=[...S];return M[N]=b,M}return Sh(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}),Qa(b.status)&&c({sessionId:b.id,status:b.status,timestamp:y})}catch{}},x=v=>{try{const b=JSON.parse(v.data),y=Date.now();r.current.set(b,y),i.current.set(b,Math.max(i.current.get(b)??0,y)),c({sessionId:b,status:"complete",timestamp:y}),s(S=>S.filter(k=>k.id!==b))}catch{}};return Ls(`/api/events${p}`,{events:{"ai_session:updated":f,"ai_session:deleted":x},onReconnect:()=>{d()}})},[c,l,e,d]);const m=a.useCallback(async p=>{const x=n.find(S=>S.id===p)?.type,v=Wi();let b=!1;if(x==="planning")try{await np(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of planning session ${p} despite lock by another tab`)}else if(x==="subtask")try{await ap(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of subtask session ${p} despite lock by another tab`)}else if(x==="mission_interview")try{await dp(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),i.current.set(p,Math.max(i.current.get(p)??0,y)),c({sessionId:p,status:"complete",timestamp:y});try{await up(p)}catch{}s(S=>S.filter(k=>k.id!==p))},[c,e,n]),h=a.useMemo(()=>n.filter(p=>Sh(p)),[n]),g=a.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:g,dismissSession:m,refresh:d}}function Bn(e){return{...e,dependencies:Array.isArray(e.dependencies)?e.dependencies:[],steps:Array.isArray(e.steps)?e.steps:[],log:Array.isArray(e.log)?e.log:[]}}function Ch(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function qT(e){const n=e?.projectId,s=e?.searchQuery,i=e?.sseEnabled??!0,[r,o]=a.useState([]),[l,c]=a.useState(!1),u=a.useRef(l);u.current=l;const d=a.useRef(r),m=a.useRef(0),h=a.useRef(0),g=a.useRef(s),p=a.useRef(null),f=a.useRef(void 0),x=a.useRef(0),v=a.useRef(n);d.current=r,g.current=s,v.current!==n&&(v.current=n,x.current++);const b=1e3,y=a.useCallback(async _=>{const I=++m.current,O=n,J=_?.searchQueryOverride??s,Q=_?.includeArchivedOverride??u.current;try{const E=await wv(void 0,void 0,O,J,Q);if(m.current!==I||n!==O)return;o(E.map(Bn)),f.current=Date.now()}catch{if(m.current!==I||n!==O)return;if(_?.clearOnError){o([]);return}o(E=>E)}},[n,s]);p.current=y;const S=a.useCallback(async()=>{u.current||(c(!0),u.current=!0,await p.current({includeArchivedOverride:!0}))},[]);a.useEffect(()=>{if(s===void 0)return;const _=setTimeout(()=>{y({searchQueryOverride:s})},300);return()=>clearTimeout(_)},[s]),a.useEffect(()=>{y({clearOnError:!0});const _=()=>{if(document.visibilityState!=="visible")return;const I=Date.now();I-h.current<b||(h.current=I,y())};return document.addEventListener("visibilitychange",_),()=>{document.removeEventListener("visibilitychange",_)}},[y]),a.useEffect(()=>{if(i===!1)return;const _=x.current,I=n?`?projectId=${encodeURIComponent(n)}`:"",O=()=>x.current!==_;let J=!0;const Q=G=>{if(O())return;const me=Bn(JSON.parse(G.data));if(g.current){p.current({searchQueryOverride:g.current});return}o(ce=>ce.some(ae=>ae.id===me.id)?ce:[...ce,me])},E=G=>{if(O())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:me,to:ce}=JSON.parse(G.data),ae=Bn(me);o(pe=>pe.map(U=>U.id===ae.id?{...ae,column:ce}:U)),f.current=Date.now()},D=G=>{if(O())return;if(g.current){p.current({searchQueryOverride:g.current});return}const me=Bn(JSON.parse(G.data));o(ce=>ce.map(ae=>{if(ae.id!==me.id||Ch(me.updatedAt,ae.updatedAt)<0)return ae;if(ae.column===me.column)return me;const U=Ch(ae.columnMovedAt,me.columnMovedAt);return ae.columnMovedAt&&!me.columnMovedAt?{...me,column:ae.column,columnMovedAt:ae.columnMovedAt}:U>0?{...me,column:ae.column,columnMovedAt:ae.columnMovedAt}:me})),f.current=Date.now()},T=G=>{if(O())return;if(g.current){p.current({searchQueryOverride:g.current});return}const me=Bn(JSON.parse(G.data));o(ce=>ce.filter(ae=>ae.id!==me.id))},w=G=>{if(O())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:me}=JSON.parse(G.data),ce=Bn(me);o(ae=>ae.map(pe=>pe.id===ce.id?{...ce,column:"done"}:pe))},q=Ls(`/api/events${I}`,{events:{"task:created":Q,"task:moved":E,"task:updated":D,"task:deleted":T,"task:merged":w},onReconnect:()=>{J&&(O()||p.current())}});return()=>{J=!1,q()}},[n,i]);const k=a.useCallback(async _=>{const I=Bn(await Xh(_,n));return o(O=>O.some(J=>J.id===I.id)?O:[...O,I]),I},[n]),R=a.useCallback(async(_,I)=>Bn(await Sv(_,I,n)),[n]),N=a.useCallback(async _=>Bn(await Zh(_,n)),[n]),M=a.useCallback(async _=>Bn(await Cv(_,n)),[n]),C=a.useCallback(async _=>Ev(_,n),[n]),z=a.useCallback(async _=>Bn(await _v(_,n)),[n]),A=a.useCallback(async _=>{const I=Bn(await Mv(_,n));return o(O=>O.some(J=>J.id===I.id)?O:[...O,I]),I},[n]),P=a.useCallback(async(_,I)=>{const O=d.current.find(Q=>Q.id===_),J=O?{...O,...I,updatedAt:new Date().toISOString()}:void 0;J&&o(Q=>Q.map(E=>E.id===_?J:E));try{const Q=Bn(await Ks(_,I,n));return o(E=>E.map(D=>D.id===_?Q:D)),Q}catch(Q){throw O&&o(E=>E.map(D=>D.id===_?O:D)),Q}},[n]),F=a.useCallback(async _=>{const I=Bn(await Rv(_,n));return o(O=>O.map(J=>J.id===_?I:J)),I},[n]),W=a.useCallback(async _=>{const I=Bn(await Tv(_,n));return o(O=>O.map(J=>J.id===_?I:J)),I},[n]),$=a.useCallback(async()=>{const I=(await Pv(n)).map(Bn);return o(O=>O.map(J=>I.find(E=>E.id===J.id)||J)),I},[n]);return{tasks:r,createTask:k,moveTask:R,pauseTask:N,deleteTask:M,mergeTask:C,retryTask:z,duplicateTask:A,updateTask:P,archiveTask:F,unarchiveTask:W,archiveAllDone:$,loadArchivedTasks:S,includeArchived:l,lastFetchTimeMs:f.current}}const VT=5e3,WT=1e3;function KT(){const[e,n]=a.useState([]),[s,i]=a.useState(!0),[r,o]=a.useState(null),l=a.useRef(null),c=a.useRef(0),u=a.useCallback(async()=>{try{o(null);const g=await Kd();n(g)}catch(g){o(g instanceof Error?g.message:"Failed to fetch projects")}},[]);a.useEffect(()=>{let g=!1;async function p(){i(!0);const x=performance.now();try{const v=await Kd(),y=`initial fetchProjectsAcrossNodes took ${Math.round(performance.now()-x)}ms (${v.length} projects)`;console.log(`[useProjects] ${y}`),ir("[useProjects]",y),g||(n(v),o(null))}catch(v){const y=`initial fetch failed after ${Math.round(performance.now()-x)}ms: ${v instanceof Error?v.message:String(v)}`;console.warn(`[useProjects] ${y}`),ir("[useProjects]",y),g||o(v instanceof Error?v.message:"Failed to fetch projects")}finally{g||i(!1)}}p();const f=()=>{if(document.visibilityState!=="visible")return;const x=Date.now();x-c.current<WT||(c.current=x,u())};return document.addEventListener("visibilitychange",f),()=>{g=!0,document.removeEventListener("visibilitychange",f)}},[u]),a.useEffect(()=>{if(!s)return l.current=setInterval(()=>{u()},VT),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async g=>{const p=await Tk(g);return n(f=>[...f,p]),p},[]),m=a.useCallback(async(g,p)=>{const f=await zk(g,p);return n(x=>x.map(v=>v.id===g?f:v)),f},[]),h=a.useCallback(async g=>{await op(g),n(p=>p.filter(f=>f.id!==g))},[]);return{projects:e,loading:s,error:r,refresh:u,register:d,update:m,unregister:h}}const GT="kb-dashboard-current-project";function JT(e){return e??"local"}function YT(e,n={}){const{nodeId:s=null}=n,[i,r]=a.useState(null),[o,l]=a.useState(!0),c=a.useRef(!1),u=a.useRef(!1),d=a.useRef(null),m=JT(s);a.useEffect(()=>{let p=!1;async function f(){try{const x=await Vi();if(p)return;d.current=x.dashboardCurrentProjectIdByNode??{};const v=d.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(GT);if(b){const y=JSON.parse(b);y?.id&&e.some(k=>k.id===y.id)&&(r(y),c.current=!0,d.current={...d.current,[m]:y.id},await sn({dashboardCurrentProjectIdByNode:d.current}).catch(()=>{}))}}catch{}}catch{}finally{p||l(!1)}}return f(),()=>{p=!0}},[m,e]),a.useEffect(()=>{if(!o){if(i){if(!e.some(x=>x.id===i.id)&&e.length>0){const x=e.find(v=>v.status==="active");r(x||e[0]||null);return}const f={...d.current,[m]:i.id};d.current=f,sn({dashboardCurrentProjectIdByNode:f}).catch(()=>{})}else if(e.length>0&&!u.current){const p=e.find(f=>f.status==="active");p&&r(p)}}},[i,e,o,m]);const h=a.useCallback(p=>{if(u.current=!1,r(p),p){const f={...d.current,[m]:p.id};d.current=f,sn({dashboardCurrentProjectIdByNode:f}).catch(()=>{})}},[m]),g=a.useCallback(()=>{u.current=!0,r(null);const p={...d.current};delete p[m],d.current=p,sn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:i,setCurrentProject:h,clearCurrentProject:g,loading:o}}const og=a.createContext(null);function QT({children:e}){const[n,s]=a.useState([]),i=a.useRef(0),r=a.useRef(new Map),o=a.useCallback(c=>{const u=r.current.get(c);u!==void 0&&(clearTimeout(u),r.current.delete(c)),s(d=>d.filter(m=>m.id!==c))},[]),l=a.useCallback((c,u="info")=>{const d=i.current++;s(h=>[...h,{id:d,message:c,type:u}]);const m=setTimeout(()=>o(d),4e3);r.current.set(d,m)},[o]);return a.useEffect(()=>()=>{r.current.forEach(c=>clearTimeout(c)),r.current.clear()},[]),lo.createElement(og.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function XT(){const e=a.useContext(og);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const lg="kb-dashboard-theme-mode",cg="kb-dashboard-color-theme",dg=[...dw],Gc="theme-data",cc="theme-data.css";function ZT(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.endsWith("/")?e.slice(0,-1)+`/${cc}`:e.replace(/\/[^/]+$/,`/${cc}`):`/${cc}`}const Ss=typeof window<"u",eP=Ss?a.useLayoutEffect:a.useEffect;function ug(e){return e==="dark"||e==="light"||e==="system"}function Eh(){if(!Ss)return"dark";try{const e=localStorage.getItem(lg);if(ug(e))return e}catch{}return"dark"}function _h(){if(!Ss)return"default";try{const e=localStorage.getItem(cg);if(e&&dg.includes(e))return e}catch{}return"default"}function Mh(e){if(Ss)try{localStorage.setItem(lg,e)}catch{}}function Ah(e){if(Ss)try{localStorage.setItem(cg,e)}catch{}}function tP(e,n){return e==="system"?n?"dark":"light":e}function nP(e,n,s){if(!Ss)return;const i=tP(e,s);document.documentElement.setAttribute("data-theme",i),document.documentElement.setAttribute("data-color-theme",n)}function Rh(){if(!Ss)return;const e=ZT(),n=document.getElementById(Gc);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=Gc,document.head.appendChild(s)}function Th(){if(!Ss)return;const e=document.getElementById(Gc);e&&e.remove()}function sP(){const[e,n]=a.useState(()=>Eh()),[s,i]=a.useState(()=>_h()),[r,o]=a.useState(!0),[l,c]=a.useState(()=>Ss?window.matchMedia("(prefers-color-scheme: dark)").matches:!0),u=a.useRef(e),d=a.useRef(s),m=a.useRef(!1),h=a.useRef(!1);a.useEffect(()=>{u.current=e},[e]),a.useEffect(()=>{d.current=s},[s]),a.useEffect(()=>{if(!Ss||!r)return;let f=!1;return Vi().then(x=>{f||(ug(x.themeMode)&&!m.current&&(u.current!==x.themeMode&&(u.current=x.themeMode,n(x.themeMode)),Eh()!==x.themeMode&&Mh(x.themeMode)),x.colorTheme&&dg.includes(x.colorTheme)&&!h.current&&(d.current!==x.colorTheme&&(d.current=x.colorTheme,i(x.colorTheme)),_h()!==x.colorTheme&&Ah(x.colorTheme)))}).catch(x=>{console.warn("[useTheme] Failed to hydrate theme from global settings",x)}).finally(()=>{f||o(!1)}),()=>{f=!0}},[r]),a.useEffect(()=>{if(!Ss)return;const f=window.matchMedia("(prefers-color-scheme: dark)"),x=v=>{c(v.matches)};return f.addEventListener("change",x),()=>f.removeEventListener("change",x)},[]),eP(()=>{nP(e,s,l)},[e,s,l]),a.useEffect(()=>{!Ss||r||(s!=="default"?Rh():Th())},[s,r]);const g=a.useCallback(f=>{m.current=!0,u.current=f,n(f),Mh(f),sn({themeMode:f}).catch(x=>{console.warn("[useTheme] Failed to persist themeMode to global settings",x)})},[]),p=a.useCallback(f=>{h.current=!0,d.current=f,i(f),Ah(f),f!=="default"?Rh():Th(),sn({colorTheme:f}).catch(x=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",x)})},[]);return{themeMode:e,colorTheme:s,setThemeMode:g,setColorTheme:p,isSystemDark:l}}function iP(e){const{planningSessions:n}=e,[s,i]=a.useState(!1),[r,o]=a.useState(!1),[l,c]=a.useState(null),[u,d]=a.useState(void 0),[m,h]=a.useState(!1),[g,p]=a.useState(null),[f,x]=a.useState(void 0),[v,b]=a.useState(null),[y,S]=a.useState("definition"),[k,R]=a.useState(!1),[N,M]=a.useState(void 0),[C,z]=a.useState(!1),[A,P]=a.useState(!1),[F,W]=a.useState(!1),[$,_]=a.useState(null),[I,O]=a.useState(!1),[J,Q]=a.useState(!1),[E,D]=a.useState(void 0),[T,w]=a.useState(!1),[q,G]=a.useState("project"),[me,ce]=a.useState(!1),[ae,pe]=a.useState(!1),[U,Ne]=a.useState(!1),[ne,xe]=a.useState(!1),[le,ve]=a.useState(!1),[ee,Ee]=a.useState(!1),[Fe,Ke]=a.useState(!1),Ze=!!(v||k||s||r||m||J||T||me||ae||U||le||ne||F||I||C||A||ee||Fe),Xe=a.useCallback(()=>i(!0),[]),Qe=a.useCallback(()=>i(!1),[]),it=a.useCallback(()=>o(!0),[]),Ie=a.useCallback(B=>{c(B),o(!0)},[]),Ge=a.useCallback(()=>{const B=n[0];B&&(d(B.id),o(!0))},[n]),se=a.useCallback(B=>{d(B),o(!0)},[]),ye=a.useCallback(()=>{o(!1),c(null),d(void 0)},[]),Z=a.useCallback(B=>{p(B),h(!0)},[]),Te=a.useCallback(B=>{x(B),h(!0)},[]),ze=a.useCallback(()=>{h(!1),p(null),x(void 0)},[]),be=a.useCallback((B,ge="definition")=>{b(B),S(ge)},[]),Me=a.useCallback(B=>{b(B),S("changes")},[]),Be=a.useCallback(B=>{b(ge=>ge&&{...ge,...B})},[]),lt=a.useCallback(()=>{b(null)},[]),je=a.useCallback(B=>{M(B),R(!0)},[]),ie=a.useCallback(()=>{R(!1),M(void 0)},[]),Ae=a.useCallback(()=>z(!0),[]),he=a.useCallback(()=>z(!1),[]),Re=a.useCallback(()=>P(!0),[]),Je=a.useCallback(()=>P(!1),[]),$e=a.useCallback(B=>{_(B??null),W(!0)},[]),de=a.useCallback(()=>{W(!1),_(null)},[]),re=a.useCallback(()=>O(!0),[]),ue=a.useCallback(()=>O(!1),[]),Pe=a.useCallback(()=>{Q(B=>!B)},[]),Se=a.useCallback(()=>{Q(!1),D(void 0)},[]),fe=a.useCallback(()=>w(!0),[]),tt=a.useCallback(()=>w(!1),[]),ut=a.useCallback(B=>{G(B)},[]),vt=a.useCallback(()=>ce(!0),[]),gt=a.useCallback(()=>ce(!1),[]),dt=a.useCallback(()=>pe(!0),[]),wt=a.useCallback(()=>pe(!1),[]),Mt=a.useCallback(()=>Ne(!0),[]),yt=a.useCallback(()=>Ne(!1),[]),Et=a.useCallback(()=>xe(!0),[]),Nt=a.useCallback(()=>xe(!1),[]),Tt=a.useCallback(()=>ve(!0),[]),Ht=a.useCallback(()=>ve(!1),[]),Ut=a.useCallback(async(B,ge)=>{ve(!1),D(ge),Q(!0)},[]),Vt=a.useCallback(()=>Ee(!0),[]),zt=a.useCallback(()=>Ee(!1),[]),Ct=a.useCallback(()=>Ke(!0),[]),At=a.useCallback(()=>Ke(!1),[]),kt=a.useCallback((B,ge)=>{ge(`Created ${B.id} from planning mode`,"success"),o(!1),c(null)},[]),Kt=a.useCallback((B,ge)=>{const te=B.map(j=>j.id).join(", ");ge(`Created ${te} from planning mode`,"success"),o(!1),c(null)},[]),$t=a.useCallback((B,ge)=>{const te=B.map(j=>j.id).join(", ");ge(`Created ${te} from subtask breakdown`,"success"),h(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:l,planningResumeSessionId:u,isSubtaskOpen:m,subtaskInitialDescription:g,subtaskResumeSessionId:f,detailTask:v,detailTaskInitialTab:y,settingsOpen:k,settingsInitialSection:N,schedulesOpen:C,githubImportOpen:A,usageOpen:F,usageAnchorRect:$,systemStatsOpen:I,terminalOpen:J,terminalInitialCommand:E,filesOpen:T,fileBrowserWorkspace:q,activityLogOpen:me,gitManagerOpen:ae,workflowStepsOpen:U,agentsOpen:ne,scriptsOpen:le,setupWizardOpen:ee,modelOnboardingOpen:Fe,anyModalOpen:Ze,openNewTask:Xe,closeNewTask:Qe,openPlanning:it,openPlanningWithInitialPlan:Ie,resumePlanning:Ge,openPlanningWithSession:se,closePlanning:ye,openSubtaskBreakdown:Z,openSubtaskWithSession:Te,closeSubtask:ze,openDetailTask:be,openDetailWithChangesTab:Me,updateDetailTask:Be,closeDetailTask:lt,openSettings:je,closeSettings:ie,openSchedules:Ae,closeSchedules:he,openGitHubImport:Re,closeGitHubImport:Je,openUsage:$e,closeUsage:de,openSystemStats:re,closeSystemStats:ue,toggleTerminal:Pe,closeTerminal:Se,openFiles:fe,closeFiles:tt,setFileWorkspace:ut,openActivityLog:vt,closeActivityLog:gt,openGitManager:dt,closeGitManager:wt,openWorkflowSteps:Mt,closeWorkflowSteps:yt,openAgents:Et,closeAgents:Nt,openScripts:Tt,closeScripts:Ht,runScript:Ut,openSetupWizard:Vt,closeSetupWizard:zt,openModelOnboarding:Ct,closeModelOnboarding:At,onPlanningTaskCreated:kt,onPlanningTasksCreated:Kt,onSubtaskTasksCreated:$t}}function aP(e){const[n,s]=a.useState(2),[i,r]=a.useState("."),[o,l]=a.useState(!0),[c,u]=a.useState(!1),[d,m]=a.useState(!1),[h,g]=a.useState(void 0),[p,f]=a.useState(!1),[x,v]=a.useState(!1),[b,y]=a.useState({}),[S,k]=a.useState(!1),[R,N]=a.useState(!1),[M,C]=a.useState(!1),[z,A]=a.useState(!1),[P,F]=a.useState(!1),W=a.useCallback(async()=>{const[J,Q]=await Promise.allSettled([Dv(e),Lo(e)]);if(J.status==="fulfilled"&&(s(J.value.maxConcurrent),r(J.value.rootDir)),Q.status==="fulfilled"){const E=Q.value;l(!!E.autoMerge),u(!!E.globalPause),m(!!E.enginePaused),v(!!E.prAuthAvailable),g(E.taskStuckTimeoutMs),f(E.showQuickChatFAB===!0),y(E.experimentalFeatures??{});const D=E.experimentalFeatures??{};k(D.insights===!0),N(D.roadmap===!0),C(D.memoryView===!0),A(D.devServerView===!0||D.devServer===!0),F(D.todoView===!0)}},[e]);a.useEffect(()=>{W()},[W]);const $=a.useCallback(async()=>{const J=!o;l(J);try{await zr({autoMerge:J},e)}catch{l(!J)}},[o,e]),_=a.useCallback(async()=>{const J=!c;u(J);try{await zr({globalPause:J,globalPauseReason:J?"manual":void 0},e)}catch{u(!J)}},[c,e]),I=a.useCallback(async()=>{const J=!d;m(J);try{await zr({enginePaused:J},e)}catch{m(!J)}},[d,e]),O=a.useCallback(async()=>{const J=!p;f(J);try{await zr({showQuickChatFAB:J},e)}catch{f(!J)}},[p,e]);return{maxConcurrent:n,rootDir:i,autoMerge:o,globalPaused:c,enginePaused:d,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:x,experimentalFeatures:b,insightsEnabled:S,roadmapEnabled:R,memoryEnabled:M,devServerEnabled:z,todosEnabled:P,toggleAutoMerge:$,toggleGlobalPause:_,toggleEnginePause:I,toggleShowQuickChatFAB:O,refresh:W}}function rP(e){const{projectId:n,projects:s,projectsLoading:i,currentProject:r,setCurrentProject:o,addToast:l,openTaskDetail:c,closeTaskDetail:u}=e,d=a.useRef(!1),m=a.useRef(null);return a.useEffect(()=>{const g=new URLSearchParams(window.location.search),p=g.get("project"),f=g.get("task");if(!f||i)return;if(p){const v=s.find(b=>b.id===p);if(!v){l(`Project '${p}' not found`,"error");return}r?.id!==v.id&&o(v)}if(d.current)return;d.current=!0,fo(f,p??n).then(v=>{c(v),m.current=f}).catch(()=>{l(`Task ${f} not found`,"error")})},[n,s,i,r,o,l,c]),{handleDetailClose:a.useCallback(()=>{if(m.current){const g=new URLSearchParams(window.location.search);g.delete("task");const p=g.toString();window.history.replaceState(null,"",p?`${window.location.pathname}?${p}`:window.location.pathname),m.current=null}u()},[u])}}function oP(){const[e,n]=a.useState([]),[s,i]=a.useState([]),[r,o]=a.useState([]),l=a.useRef(s),c=a.useRef(r);a.useEffect(()=>{cs().then(m=>{n(m.models),l.current=m.favoriteProviders,c.current=m.favoriteModels,i(m.favoriteProviders),o(m.favoriteModels)}).catch(()=>{})},[]),a.useEffect(()=>{l.current=s},[s]),a.useEffect(()=>{c.current=r},[r]);const u=a.useCallback(async m=>{const h=l.current,p=h.includes(m)?h.filter(f=>f!==m):[m,...h];l.current=p,i(()=>p);try{await sn({favoriteProviders:p,favoriteModels:c.current})}catch(f){throw l.current=h,i(()=>h),f}},[]),d=a.useCallback(async m=>{const h=c.current,p=h.includes(m)?h.filter(f=>f!==m):[m,...h];c.current=p,o(()=>p);try{await sn({favoriteProviders:l.current,favoriteModels:p})}catch(f){throw c.current=h,o(()=>h),f}},[]);return{availableModels:e,favoriteProviders:s,favoriteModels:r,toggleFavoriteProvider:u,toggleFavoriteModel:d}}function lP({projectId:e,setupWizardOpen:n,openModelOnboarding:s,openSettings:i}){const r=a.useRef(!1),o=a.useRef(n);o.current=n,a.useEffect(()=>{if(n||!e||r.current)return;r.current=!0;let l=!1,c=!1;mr().then(({providers:u})=>{const d=u.some(h=>h.authenticated);if(u.length>0&&!d||u.length>0&&d)return Vi().then(h=>{const g=!!(h.defaultProvider&&h.defaultModelId);(h.modelOnboardingComplete===!1||h.modelOnboardingComplete===void 0)&&(!d||!g)&&!ja()?l=!0:!d&&!ja()&&(c=!0)})}).then(()=>{if(o.current){r.current=!1;return}l?(ws("onboarding:auto-triggered",{trigger:"first-run"}),s()):c&&(ws("onboarding:auto-triggered",{trigger:"missing-provider"}),i("authentication"))}).catch(()=>{})},[e,n,s,i])}const Ph="kb-update-banner-dismissed";function cP(){const[e,n]=a.useState(!0),[s,i]=a.useState(!1),[r,o]=a.useState(null),[l,c]=a.useState(null),[u,d]=a.useState(!1);a.useEffect(()=>{const h=sessionStorage.getItem(Ph)==="true";d(h);let g=!1;return Lv().then(p=>{g||p.disabled||(i(p.updateAvailable===!0),o(typeof p.latestVersion=="string"?p.latestVersion:null),c(typeof p.currentVersion=="string"?p.currentVersion:null))}).catch(()=>{}).finally(()=>{g||n(!1)}),()=>{g=!0}},[]);const m=a.useCallback(()=>{d(!0),sessionStorage.setItem(Ph,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:u,dismiss:m}}const dP=["board","list","agents","missions","chat","documents","roadmaps","skills","mailbox","insights","memory","devserver","dev-server","todos"];function Ih(e){return e!==null&&dP.includes(e)}function uP(e){return e==="devserver"?"dev-server":e}function mP(e){const{projectsLoading:n,projectsError:s,currentProjectLoading:i,currentProject:r,projectsLength:o,setupWizardOpen:l,openSetupWizard:c,themeMode:u,setThemeMode:d}=e,[m,h]=a.useState(()=>{if(typeof window<"u"){const b=window.localStorage.getItem("kb-dashboard-view-mode");if(b==="overview"||b==="project")return b}return"overview"}),[g,p]=a.useState(()=>{const b=Dn("kb-dashboard-task-view");return Ih(b)?b:"board"}),f=a.useRef(!1);a.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),a.useEffect(()=>{const b=Dn("kb-dashboard-task-view",r?.id);if(Ih(b)){const y=!f.current&&b==="devserver";p(y?"devserver":uP(b))}else p("board");r?.id&&(f.current=!0)},[r?.id]),a.useEffect(()=>{os("kb-dashboard-task-view",g,r?.id)},[r?.id,g]),a.useEffect(()=>{n||i||r&&m==="overview"&&h("project")},[n,i,r,m]),a.useEffect(()=>{if(n||i||l||s||o>0||r)return;const b=window.setTimeout(()=>{c()},500);return()=>window.clearTimeout(b)},[n,s,o,i,r,l,c]);const x=a.useCallback(b=>{p(b)},[]),v=a.useCallback(()=>{const b=["dark","light","system"],y=b.indexOf(u),S=b[(y+1)%b.length];d(S)},[u,d]);return{viewMode:m,setViewMode:h,taskView:g,setTaskView:p,handleChangeTaskView:x,handleToggleTheme:v}}function hP(e){const{setCurrentProject:n,clearCurrentProject:s,setViewMode:i,currentProject:r,refreshProjects:o,toggleFavoriteProvider:l,toggleFavoriteModel:c,addToast:u,openSettings:d,openSetupWizard:m,closeSetupWizard:h,closeModelOnboarding:g}=e,p=a.useCallback(C=>{n(C),i("project")},[n,i]),f=a.useCallback(()=>{s(),i("overview")},[s,i]),x=a.useCallback(()=>{d()},[d]),v=a.useCallback(()=>{m()},[m]),b=a.useCallback(C=>{h(),n(C),i("project"),u(`Project ${C.name} registered successfully`,"success"),o()},[h,n,i,u,o]),y=a.useCallback(()=>{g()},[g]),S=a.useCallback(async C=>{try{await Dk(C.id),u(`Project ${C.name} paused`,"success"),await o()}catch{u(`Failed to pause project ${C.name}`,"error")}},[u,o]),k=a.useCallback(async C=>{try{await Lk(C.id),u(`Project ${C.name} resumed`,"success"),await o()}catch{u(`Failed to resume project ${C.name}`,"error")}},[u,o]),R=a.useCallback(async C=>{try{await op(C.id),u(`Project ${C.name} removed`,"success"),r?.id===C.id&&(s(),i("overview")),await o()}catch{u(`Failed to remove project ${C.name}`,"error")}},[r,s,i,u,o]),N=a.useCallback(async C=>{try{await l(C)}catch{u("Failed to update favorites","error")}},[l,u]),M=a.useCallback(async C=>{try{await c(C)}catch{u("Failed to update model favorites","error")}},[c,u]);return{handleSelectProject:p,handleViewAllProjects:f,handleOpenSettings:x,handleAddProject:v,handleSetupComplete:b,handleModelOnboardingComplete:y,handlePauseProject:S,handleResumeProject:k,handleRemoveProject:R,handleToggleFavorite:N,handleToggleModelFavorite:M}}function pP(e){const{createTask:n,onPlanningTaskCreated:s,onPlanningTasksCreated:i,onSubtaskTasksCreated:r,addToast:o}=e,l=a.useCallback(async g=>n({...g,column:"triage"}),[n]),c=a.useCallback(async g=>await n({...g,column:"triage"}),[n]),u=a.useCallback(g=>{s(g,o)},[s,o]),d=a.useCallback(g=>{i(g,o)},[i,o]),m=a.useCallback(g=>{r(g,o)},[r,o]),h=a.useCallback(g=>{o(`Imported ${g.id} from GitHub`,"success")},[o]);return{handleBoardQuickCreate:l,handleModalCreate:c,handlePlanningTaskCreated:u,handlePlanningTasksCreated:d,handleSubtaskTasksCreated:m,handleGitHubImport:h}}async function fP(e){return Fo("/health",{nodeId:e})}async function gP(e){return Fo("/projects",{nodeId:e})}async function xP(e,n,s){const i=new URLSearchParams({projectId:n});return s&&s.trim()&&i.set("q",s.trim()),Fo(`/tasks?${i.toString()}`,{nodeId:e})}async function bP(e,n){return Fo(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function wD(e){return L(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function ND(e){return L(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function SD(e){return L(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function CD(e){return L(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}function vP(e,n){const{projectId:s,searchQuery:i}=n??{},[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState(null),[m,h]=a.useState(!1),[g,p]=a.useState(null),f=a.useRef(null),x=a.useCallback(async()=>{if(!e){o([]),c([]),d(null),h(!1),p(null);return}f.current?.abort();const b=new AbortController;f.current=b,h(!0),p(null);try{const y=[fP(e),gP(e)];s&&(y.push(xP(e,s,i)),y.push(bP(e,s)));const S=await Promise.allSettled(y);if(b.signal.aborted)return;const k=S[0],R=S[1];if(k.status==="rejected"){p(`Failed to fetch node health: ${k.reason}`),h(!1);return}if(d(k.value),R.status==="rejected"){p(`Failed to fetch projects: ${R.reason}`),h(!1);return}if(o(R.value),s&&S[2]){const N=S[2];if(N.status==="rejected"){p(`Failed to fetch tasks: ${N.reason}`),h(!1);return}N.status==="fulfilled"&&c(N.value)}h(!1)}catch(y){b.signal.aborted||(p(y instanceof Error?y.message:"Unknown error"),h(!1))}},[e,s,i]);a.useEffect(()=>(x(),()=>{f.current?.abort()}),[x]);const v=a.useCallback(()=>{x()},[x]);return{projects:r,tasks:l,health:u,loading:m,error:g,refresh:v}}function yP(e){const[n,s]=a.useState(!1),[i,r]=a.useState(null);return a.useEffect(()=>{if(!e){s(!1),r(null);return}const o=`/api/proxy/${encodeURIComponent(e)}/events`;return Ls(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:i}}const kP="fusion-dashboard-current-node",mg=a.createContext(null);function jP({children:e}){const[n,s]=a.useState(null),[i,r]=a.useState(!0),o=a.useRef(!1),l=a.useRef(void 0);a.useEffect(()=>{let m=!1;async function h(){try{const g=await Vi();if(m)return;l.current=g.dashboardCurrentNodeId;const p=g.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const f=localStorage.getItem(kP);if(f){const x=JSON.parse(f);x?.id&&x?.type==="remote"&&(l.current=x.id,await sn({dashboardCurrentNodeId:x.id}).catch(()=>{}))}}catch{}}catch{}finally{m||r(!1)}}return h(),()=>{m=!0}},[]),a.useEffect(()=>{if(!i)if(n&&n.type==="remote"&&n.id){const m=n.id;l.current!==m&&(l.current=m,sn({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,sn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,i]);const c=a.useCallback(m=>{s(m)},[]),u=a.useCallback(()=>{s(null),l.current=void 0,sn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),d={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:u};return t.jsx(mg.Provider,{value:d,children:e})}function wP(){const e=a.useContext(mg);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}function NP({open:e}){const[n,s]=a.useState(""),i=a.useRef(null);a.useEffect(()=>{e&&i.current?.focus()},[e]);const r=a.useCallback(()=>{const l=n.trim();l&&(mv(l),window.location.reload())},[n]),o=a.useCallback(()=>{hv(),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:i,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 SP=200,CP=a.lazy(()=>nn(()=>import("./AgentsView-CXaYJX_G.js").then(e=>e.A),__vite__mapDeps([17,1,18,8,19])).then(e=>({default:e.AgentsView}))),EP=a.lazy(()=>nn(()=>import("./DocumentsView-CjrtI3TX.js"),__vite__mapDeps([20,1,0,2,21])).then(e=>({default:e.DocumentsView}))),_P=a.lazy(()=>nn(()=>import("./InsightsView-BkfQ-TV1.js"),__vite__mapDeps([22,1,14,0,2,23])).then(e=>({default:e.InsightsView}))),MP=a.lazy(()=>nn(()=>import("./NodesView-Bn_1R73N.js"),__vite__mapDeps([24,1,18,0,2,25])).then(e=>({default:e.NodesView}))),AP=a.lazy(()=>nn(()=>import("./ChatView-iXxGAaN1.js"),__vite__mapDeps([26,1,0,2])).then(e=>({default:e.ChatView}))),RP=a.lazy(()=>nn(()=>import("./RoadmapsView-B4VnQP83.js"),__vite__mapDeps([27,1,0,2,28])).then(e=>({default:e.RoadmapsView}))),TP=a.lazy(()=>nn(()=>import("./SkillsView-CRvqF8P1.js"),__vite__mapDeps([29,1,0,2,30])).then(e=>({default:e.SkillsView}))),PP=a.lazy(()=>nn(()=>import("./MemoryView-1G0zWu1i.js"),__vite__mapDeps([31,1,12,13,0,2,32])).then(e=>({default:e.MemoryView}))),IP=a.lazy(()=>nn(()=>import("./DevServerView-BeXfFkF4.js"),__vite__mapDeps([33,1,0,2,34])).then(e=>({default:e.DevServerView}))),$P=a.lazy(()=>nn(()=>import("./TodoView-Vzui5Eha.js"),__vite__mapDeps([35,1,36,0,2,37])).then(e=>({default:e.TodoView})));function DP(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{nn(()=>import("./AgentsView-CXaYJX_G.js").then(n=>n.A),__vite__mapDeps([17,1,18,8,19])),nn(()=>import("./DocumentsView-CjrtI3TX.js"),__vite__mapDeps([20,1,0,2,21])),nn(()=>import("./InsightsView-BkfQ-TV1.js"),__vite__mapDeps([22,1,14,0,2,23])),nn(()=>import("./NodesView-Bn_1R73N.js"),__vite__mapDeps([24,1,18,0,2,25])),nn(()=>import("./ChatView-iXxGAaN1.js"),__vite__mapDeps([26,1,0,2])),nn(()=>import("./RoadmapsView-B4VnQP83.js"),__vite__mapDeps([27,1,0,2,28])),nn(()=>import("./SkillsView-CRvqF8P1.js"),__vite__mapDeps([29,1,0,2,30])),nn(()=>import("./MemoryView-1G0zWu1i.js"),__vite__mapDeps([31,1,12,13,0,2,32])),nn(()=>import("./DevServerView-BeXfFkF4.js"),__vite__mapDeps([33,1,0,2,34])),nn(()=>import("./TodoView-Vzui5Eha.js"),__vite__mapDeps([35,1,36,0,2,37]))})}const dc="kb-setup-warning-dismissed";function LP(){const{toasts:e,addToast:n,removeToast:s}=XT(),i=typeof window<"u"&&!!window.electronAPI;a.useEffect(()=>{DP()},[]);const{projects:r,loading:o,error:l,refresh:c}=KT(),{nodes:u}=Bo(),{currentNode:d,currentNodeId:m,isRemote:h,setCurrentNode:g,clearCurrentNode:p}=wP(),{currentProject:f,setCurrentProject:x,clearCurrentProject:v,loading:b}=YT(r,{nodeId:m}),{hasAiProvider:y,hasGithub:S,loading:k,hasWarnings:R}=Zf(f?.id),{updateAvailable:N,latestVersion:M,currentVersion:C,dismissed:z,dismiss:A}=cP();a.useEffect(()=>{if(m&&!d&&u.length>0){const We=u.find(mt=>mt.id===m);if(We){g(We);return}}m&&u.length>0&&(u.some(mt=>mt.id===m)||p())},[m,d,u,g,p]);const[P,F]=a.useState(""),W=vP(m,{projectId:f?.id,searchQuery:P||void 0});yP(m);const $=h&&W.projects.length>0?W.projects:r,{themeMode:_,colorTheme:I,setThemeMode:O,setColorTheme:J}=sP(),{sessions:Q,generating:E,needsInput:D,planningSessions:T,dismissSession:w}=HT(f?.id),q=Q.filter(We=>We.status==="awaiting_input"||We.status==="error"),G=iP({projectId:f?.id,planningSessions:T}),{viewMode:me,setViewMode:ce,taskView:ae,handleChangeTaskView:pe}=mP({projectsLoading:o,projectsError:l,currentProjectLoading:b,currentProject:f,projectsLength:r.length,setupWizardOpen:G.setupWizardOpen,openSetupWizard:G.openSetupWizard,themeMode:_,setThemeMode:O}),U=a.useCallback(We=>{We==="missions"&&(de(void 0),ue(void 0),Se(void 0)),pe(We)},[pe]),Ne=ae==="board"||ae==="list",{tasks:ne,createTask:xe,moveTask:le,pauseTask:ve,deleteTask:ee,mergeTask:Ee,retryTask:Fe,updateTask:Ke,duplicateTask:Ze,archiveTask:Xe,unarchiveTask:Qe,archiveAllDone:it,loadArchivedTasks:Ie,lastFetchTimeMs:Ge}=qT({...f?{projectId:f.id}:{},searchQuery:P||void 0,sseEnabled:Ne}),[se,ye]=a.useState(!1),Z=a.useRef(performance.now()),Te=a.useRef(!1),ze=a.useRef(!1),be=a.useMemo(()=>o?"projects":b?"project":"tasks",[o,b]);a.useEffect(()=>{if(!o&&!Te.current){Te.current=!0;const We=`projects loaded at ${Math.round(performance.now()-Z.current)}ms from mount`;console.log(`[App] ${We}`),ir("[App]",We)}if(!b&&!ze.current){ze.current=!0;const We=`current-project resolved at ${Math.round(performance.now()-Z.current)}ms from mount`;console.log(`[App] ${We}`),ir("[App]",We)}},[o,b]),a.useEffect(()=>{if(se||o||b)return;const We=performance.now(),mt=window.setTimeout(()=>{const fn=`dashboard ready at ${Math.round(performance.now()-Z.current)}ms from mount (settle delay=${Math.round(performance.now()-We)}ms)`;console.log(`[App] ${fn}`),ir("[App]",fn),ye(!0)},SP);return()=>{window.clearTimeout(mt)}},[se,o,b]);const Be=Cr()==="mobile",[lt,je]=a.useState(0),ie=a.useCallback(()=>{mp(f?.id).then(We=>{je(We.unreadCount)}).catch(We=>{console.warn("[App] Failed to fetch mailbox unread count:",We)})},[f?.id]);a.useEffect(()=>{ie();const We=new URLSearchParams;f?.id&&We.set("projectId",f.id);const mt=We.size>0?`?${We.toString()}`:"";return Ls(`/api/events${mt}`,{events:{"message:sent":ie,"message:received":ie,"message:read":ie,"message:deleted":ie}})},[f?.id,ie]);const[Ae,he]=a.useState(!1),[Re,Je]=a.useState(!1),[$e,de]=a.useState(void 0),[re,ue]=a.useState(void 0),[Pe,Se]=a.useState(void 0),[fe,tt]=a.useState(!1),[ut,vt]=a.useState(!1),[gt,dt]=a.useState(()=>Dn(dc,f?.id)==="true");a.useEffect(()=>{dt(Dn(dc,f?.id)==="true")},[f?.id]),a.useEffect(()=>{const We=()=>{vt(!0)};return window.addEventListener(jc,We),()=>{window.removeEventListener(jc,We)}},[]);const wt=a.useCallback(()=>{os(dc,"true",f?.id),dt(!0)},[f?.id]),{maxConcurrent:Mt,autoMerge:yt,globalPaused:Et,enginePaused:Nt,taskStuckTimeoutMs:Tt,showQuickChatFAB:Ht,prAuthAvailable:Ut,experimentalFeatures:Vt,insightsEnabled:zt,roadmapEnabled:Ct,memoryEnabled:At,devServerEnabled:kt,todosEnabled:Kt,toggleAutoMerge:$t,toggleGlobalPause:B,toggleEnginePause:ge,refresh:te}=aP(f?.id),j=Vt.skillsView===!0,V=Vt.nodesView===!0,De=!0;a.useEffect(()=>{Object.keys(Vt).length!==0&&(ae==="insights"&&!zt&&pe("board"),ae==="roadmaps"&&!Ct&&pe("board"),ae==="memory"&&!At&&pe("board"),(ae==="devserver"||ae==="dev-server")&&!kt&&pe("board"),ae==="todos"&&!Kt&&pe("board"))},[ae,zt,Ct,Vt,pe,De,At,kt,Kt]),a.useEffect(()=>{Ae&&!V&&he(!1)},[Ae,V]);const{availableModels:nt,favoriteProviders:St,favoriteModels:Pt,toggleFavoriteProvider:Rt,toggleFavoriteModel:un}=oP();lP({projectId:f?.id,setupWizardOpen:G.setupWizardOpen,openModelOnboarding:G.openModelOnboarding,openSettings:G.openSettings});const{handleSelectProject:mn,handleViewAllProjects:wn,handleOpenSettings:Gt,handleAddProject:es,handleSetupComplete:we,handleModelOnboardingComplete:rt,handlePauseProject:Jt,handleResumeProject:Sn,handleRemoveProject:Cn,handleToggleFavorite:pn,handleToggleModelFavorite:bn}=hP({setCurrentProject:x,clearCurrentProject:v,setViewMode:ce,currentProject:f,refreshProjects:c,toggleFavoriteProvider:Rt,toggleFavoriteModel:un,addToast:n,openSettings:G.openSettings,openSetupWizard:G.openSetupWizard,closeSetupWizard:G.closeSetupWizard,closeModelOnboarding:G.closeModelOnboarding}),{handleDetailClose:Rn}=rP({projectId:f?.id,projects:r,projectsLoading:o,currentProject:f,setCurrentProject:x,addToast:n,openTaskDetail:G.openDetailTask,closeTaskDetail:G.closeDetailTask}),{handleBoardQuickCreate:vn,handleModalCreate:Y,handlePlanningTaskCreated:Oe,handlePlanningTasksCreated:Ye,handleSubtaskTasksCreated:st,handleGitHubImport:pt}=pP({createTask:xe,onPlanningTaskCreated:G.onPlanningTaskCreated,onPlanningTasksCreated:G.onPlanningTasksCreated,onSubtaskTasksCreated:G.onSubtaskTasksCreated,addToast:n}),jt=a.useCallback((We,mt)=>{if(mt==="changes"){G.openDetailWithChangesTab(We);return}G.openDetailTask(We,mt)},[G]),_t=a.useCallback(()=>{V&&he(We=>!We)},[V]),yn=a.useCallback(()=>{G.setFileWorkspace("project"),G.openFiles()},[G]),en=a.useCallback(async()=>{Je(!0);try{await c()}finally{Je(!1)}},[c]),xt=a.useCallback(We=>{ue(We),de(void 0),pe("missions")},[pe]),ts=a.useCallback(We=>{We.type==="planning"?G.openPlanningWithSession(We.id):We.type==="subtask"?G.openSubtaskWithSession(We.id):We.type==="mission_interview"?(ue(void 0),de(We.id),Se(void 0),pe("missions")):(We.type==="milestone_interview"||We.type==="slice_interview")&&(de(void 0),ue(void 0),Se(We.id),pe("missions"))},[pe,G]),ns=a.useCallback(()=>{},[]),ss=a.useCallback(()=>{},[]),Si=!o&&!b&&r.length===0&&!f&&!!l,oe=()=>Si?t.jsx(tT,{errorMessage:l??"Failed to fetch projects",isRetrying:Re,onRetry:en}):Ae?t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(MP,{addToast:n,onClose:()=>he(!1)})})})}):me==="overview"?t.jsx(Jn,{children:t.jsx(ON,{projects:r,loading:o,onSelectProject:mn,onAddProject:es,onPauseProject:Jt,onResumeProject:Sn,onRemoveProject:Cn,nodes:u})}):ae==="skills"?j?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(TP,{addToast:n,projectId:f?.id,onClose:()=>pe("board")})})}):(pe("board"),null):ae==="chat"?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(AP,{addToast:n,projectId:f?.id})})}):ae==="mailbox"?t.jsx(Jn,{children:t.jsx(T1,{projectId:f?.id,addToast:n,onUnreadCountChange:je})}):ae==="roadmaps"?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(RP,{addToast:n,projectId:f?.id})})}):ae==="missions"?t.jsx(Jn,{children:t.jsx(_1,{isInline:!0,isOpen:!0,onClose:()=>{ue(void 0),de(void 0),Se(void 0),pe("board")},addToast:n,projectId:f?.id,onSelectTask:We=>{const mt=ne.find(fn=>fn.id===We);mt&&G.openDetailTask(mt)},availableTasks:ne.map(We=>({id:We.id,title:We.title})),resumeSessionId:$e,targetMissionId:re,milestoneSliceResumeSessionId:Pe,onMilestoneSliceResumeFetchError:()=>Se(void 0)})}):ae==="agents"&&De?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(CP,{addToast:n,projectId:f?.id})})}):ae==="documents"?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(EP,{projectId:f?.id,addToast:n,onOpenDetail:G.openDetailTask})})}):ae==="insights"?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(_P,{projectId:f?.id,addToast:n,onClose:()=>pe("board")})})}):ae==="memory"?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(PP,{addToast:n,projectId:f?.id})})}):ae==="todos"?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx($P,{addToast:n,projectId:f?.id})})}):ae==="devserver"||ae==="dev-server"?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(IP,{addToast:n,projectId:f?.id})})}):ae==="board"?t.jsx(Jn,{children:t.jsx(EN,{tasks:h&&W.tasks.length>0?W.tasks:ne,projectId:f?.id,maxConcurrent:Mt,onMoveTask:le,onPauseTask:ve,onOpenDetail:G.openDetailTask,addToast:n,onQuickCreate:vn,onNewTask:G.openNewTask,onPlanningMode:G.openPlanningWithInitialPlan,onSubtaskBreakdown:G.openSubtaskBreakdown,autoMerge:yt,onToggleAutoMerge:$t,globalPaused:Et,onUpdateTask:Ke,onRetryTask:Fe,onArchiveTask:Xe,onUnarchiveTask:Qe,onDeleteTask:ee,onArchiveAllDone:it,onLoadArchivedTasks:Ie,searchQuery:P,availableModels:nt,onOpenDetailWithTab:jt,favoriteProviders:St,favoriteModels:Pt,onToggleFavorite:pn,onToggleModelFavorite:bn,taskStuckTimeoutMs:Tt,onOpenMission:xt,lastFetchTimeMs:Ge})}):t.jsx(Jn,{children:t.jsx(AN,{tasks:h&&W.tasks.length>0?W.tasks:ne,projectId:f?.id,onMoveTask:le,onRetryTask:Fe,onOpenDetail:G.openDetailTask,addToast:n,globalPaused:Et,onNewTask:G.openNewTask,onQuickCreate:vn,onPlanningMode:G.openPlanningWithInitialPlan,onSubtaskBreakdown:G.openSubtaskBreakdown,availableModels:nt,favoriteProviders:St,favoriteModels:Pt,onToggleFavorite:pn,onToggleModelFavorite:bn,taskStuckTimeoutMs:Tt,searchQuery:P,lastFetchTimeMs:Ge})});if(!se)return t.jsxs(t.Fragment,{children:[t.jsx(sT,{stage:be}),t.jsx(ag,{toasts:e,onRemove:s})]});const _e=!G.modelOnboardingOpen&&C4(),at=!G.modelOnboardingOpen&&!_e&&ja()&&!tg();return t.jsxs(t.Fragment,{children:[t.jsx(tw,{isElectron:i,onOpenSettings:Gt,onOpenGitHubImport:G.openGitHubImport,onOpenPlanning:G.openPlanning,onResumePlanning:G.resumePlanning,activePlanningSessionCount:T.length,onOpenUsage:G.openUsage,onOpenActivityLog:G.openActivityLog,onOpenSystemStats:G.openSystemStats,onOpenMailbox:()=>U("mailbox"),mailboxUnreadCount:lt,onOpenSchedules:G.openSchedules,onOpenGitManager:G.openGitManager,onOpenNodes:_t,showNodesButton:V,onOpenWorkflowSteps:G.openWorkflowSteps,onOpenScripts:G.openScripts,onRunScript:G.runScript,onToggleTerminal:G.toggleTerminal,onOpenFiles:G.openFiles,filesOpen:G.filesOpen,globalPaused:Et,enginePaused:Nt,onToggleGlobalPause:B,onToggleEnginePause:ge,view:ae,onChangeView:me==="project"&&f?U:void 0,showSkillsTab:j,showAgentsTab:De,searchQuery:P,onSearchChange:F,projects:$,currentProject:f,onSelectProject:mn,onViewAllProjects:wn,projectId:f?.id,mobileNavEnabled:Be,availableNodes:u,currentNode:d,onSelectNode:We=>{We===null?p():g(We)},isRemote:h,experimentalFeatures:{insights:zt,roadmap:Ct,memoryView:At,devServer:kt,devServerView:kt,todoView:Kt}}),me==="project"&&f&&!Ae&&ae!=="missions"&&!G.isPlanningOpen&&t.jsx(gT,{sessions:q,onResumeSession:ts,onDismissSession:ns,onDismissAll:ss}),me==="project"&&f&&_e&&t.jsx(bT,{onResume:G.openModelOnboarding}),me==="project"&&f&&at&&t.jsx(vT,{onOpenModelOnboarding:G.openModelOnboarding,onOpenSettings:We=>G.openSettings(We)}),me==="project"&&f&&N&&M&&C&&!z&&t.jsx(xT,{latestVersion:M,currentVersion:C,onDismiss:A}),me==="project"&&f&&!k&&R&&!gt&&t.jsx(eg,{hasAiProvider:y,hasGithub:S,onDismiss:wt}),t.jsx("div",{className:`project-content${me==="project"&&f?" project-content--with-footer":""}${Be?" project-content--with-mobile-nav":""}`,children:oe()}),me==="project"&&f&&!Ae&&t.jsx(hT,{tasks:h&&W.tasks.length>0?W.tasks:ne,projectId:f.id,taskStuckTimeoutMs:Tt,backgroundSessions:Q,backgroundGenerating:E,backgroundNeedsInput:D,onOpenBackgroundSession:ts,onDismissBackgroundSession:w,lastFetchTimeMs:Ge,currentProjectPath:f.path,onOpenProjectDirectory:yn}),t.jsx(kT,{view:ae,onChangeView:me==="project"&&f?U:()=>{},footerVisible:me==="project"&&!!f,modalOpen:G.anyModalOpen,onOpenSettings:Gt,onOpenActivityLog:G.openActivityLog,onOpenSystemStats:G.openSystemStats,onOpenMailbox:()=>U("mailbox"),mailboxUnreadCount:lt,onOpenGitManager:G.openGitManager,onOpenWorkflowSteps:G.openWorkflowSteps,onOpenSchedules:G.openSchedules,onOpenScripts:G.openScripts,onToggleTerminal:G.toggleTerminal,onOpenFiles:G.openFiles,onOpenGitHubImport:G.openGitHubImport,onOpenPlanning:G.openPlanning,onResumePlanning:G.resumePlanning,activePlanningSessionCount:T.length,onOpenUsage:()=>G.openUsage(null),onViewAllProjects:wn,onRunScript:G.runScript,projectId:f?.id,showSkillsTab:j,experimentalFeatures:{insights:zt,roadmap:Ct,memoryView:At,devServer:kt,devServerView:kt,todoView:Kt}}),me==="project"&&f&&ae!=="chat"&&ae!=="mailbox"&&ae!=="insights"&&ae!=="devserver"&&ae!=="dev-server"&&t.jsx(BT,{projectId:f.id,addToast:n,showFAB:Ht,open:fe,onOpenChange:tt,favoriteProviders:St,favoriteModels:Pt,onToggleFavorite:pn,onToggleModelFavorite:bn}),t.jsx(eT,{projectId:f?.id,tasks:ne,projects:r,currentProject:f,addToast:n,toasts:e,removeToast:s,modalManager:G,projectActions:{handleAddProject:es,handleSetupComplete:we,handleModelOnboardingComplete:rt},taskHandlers:{handleModalCreate:Y,handlePlanningTaskCreated:Oe,handlePlanningTasksCreated:Ye,handleSubtaskTasksCreated:st,handleGitHubImport:pt},taskOperations:{moveTask:le,deleteTask:ee,mergeTask:Ee,retryTask:Fe,duplicateTask:Ze},deepLink:{handleDetailClose:Rn},settings:{prAuthAvailable:Ut,themeMode:_,colorTheme:I,setThemeMode:O,setColorTheme:J},onSettingsClose:()=>{G.closeSettings(),te()},onReopenOnboarding:()=>{G.closeSettings(),G.openModelOnboarding()}}),t.jsx(NP,{open:ut})]})}function zP(){return t.jsx(QT,{children:t.jsx(jP,{children:t.jsx(fw,{children:t.jsx(LP,{})})})})}yv();av();hg.createRoot(document.getElementById("root")).render(t.jsx(a.StrictMode,{children:t.jsx(rv,{children:t.jsx(zP,{})})}));"serviceWorker"in navigator&&navigator.serviceWorker.register("/sw.js").then(e=>{console.log("SW registered:",e.scope)}).catch(e=>{console.log("SW registration failed:",e)});export{nn as $,Cs as A,gn as B,dn as C,u4 as D,jD as E,Oi as F,To as G,hn as H,sc as I,xn as J,Gs as K,ot as L,Xt as M,qt as N,g4 as O,An as P,Nk as Q,Nn as R,oa as S,Yc as T,c4 as U,d4 as V,Sk as W,Ot as X,ZI as Y,Pn as Z,Ck as _,os as a,E$ as a$,kI as a0,jI as a1,fo as a2,Py as a3,pc as a4,da as a5,wa as a6,ci as a7,di as a8,li as a9,pr as aA,Kj as aB,dD as aC,uD as aD,Gj as aE,Jj as aF,_T as aG,Cr as aH,TT as aI,Ao as aJ,jT as aK,CT as aL,ms as aM,Di as aN,bi as aO,Xb as aP,g$ as aQ,b$ as aR,x$ as aS,v$ as aT,y$ as aU,k$ as aV,j$ as aW,w$ as aX,N$ as aY,S$ as aZ,C$ as a_,mD as aa,fD as ab,pD as ac,hD as ad,gD as ae,qn as af,Xn as ag,Vb as ah,Ys as ai,lx as aj,Mo as ak,yi as al,SD as am,wD as an,ND as ao,CD as ap,mo as aq,Ib as ar,sr as as,sx as at,Yn as au,Kh as av,Bo as aw,KT as ax,cD as ay,Xd as az,l$ as b,nD as b$,_$ as b0,M$ as b1,R$ as b2,T$ as b3,A$ as b4,Mn as b5,Jc as b6,Fi as b7,oD as b8,rD as b9,Xc as bA,Zy as bB,ek as bC,tk as bD,Xy as bE,II as bF,yr as bG,$o as bH,Tb as bI,dr as bJ,Sb as bK,I$ as bL,$$ as bM,D$ as bN,L$ as bO,z$ as bP,F$ as bQ,O$ as bR,P$ as bS,Xh as bT,ha as bU,Tk as bV,mv as bW,hv as bX,tD as bY,NI as bZ,wI as b_,lD as ba,tI as bb,eI as bc,ZP as bd,nI as be,uI as bf,mI as bg,lI as bh,aI as bi,rI as bj,oI as bk,iI as bl,sI as bm,XP as bn,cI as bo,XA as bp,LI as bq,DI as br,HI as bs,$I as bt,zI as bu,FI as bv,OI as bw,UI as bx,nk as by,BI as bz,Ue as c,zx as c$,SI as c0,PI as c1,AI as c2,CI as c3,RI as c4,EI as c5,TI as c6,_I as c7,MI as c8,_g as c9,YA as cA,b4 as cB,ic as cC,Oo as cD,KP as cE,qP as cF,WP as cG,GP as cH,JP as cI,YP as cJ,QP as cK,lw as cL,Uo as cM,vD as cN,Bm as cO,yD as cP,kD as cQ,dI as cR,U$ as cS,H$ as cT,W$ as cU,q$ as cV,B$ as cW,V$ as cX,K$ as cY,rp as cZ,Id as c_,Xs as ca,zA as cb,hI as cc,p$ as cd,UP as ce,BP as cf,mr as cg,c$ as ch,HP as ci,VP as cj,ry as ck,Qv as cl,Qs as cm,Xv as cn,Zv as co,ey as cp,gI as cq,d$ as cr,u$ as cs,m$ as ct,wi as cu,xD as cv,bD as cw,f$ as cx,mc as cy,In as cz,r$ as d,G$ as d0,t$ as d1,YI as d2,XI as d3,QI as d4,i$ as d5,s$ as d6,Uh as d7,GI as d8,KI as d9,l4 as da,e$ as db,vr as dc,oM as dd,VI as de,qI as df,Iy as dg,WI as dh,JI as di,J$ as dj,Y$ as dk,wb as dl,bc as dm,sD as dn,Z$ as dp,X$ as dq,eD as dr,Q$ as ds,h$ as dt,xI as du,pI as dv,fI as dw,vI as dx,yI as dy,bI as dz,o$ as e,aD as f,Dn as g,cs as h,Na as i,iD as j,$n as k,wk as l,a$ as m,ST as n,Ds as o,Lo as p,zr as q,ke as r,Ls as s,mw as t,sn as u,n$ as v,gc as w,Js as x,Zt as y,uo as z};
|