@runfusion/fusion 0.9.1 → 0.9.2
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 +5390 -3696
- package/dist/client/assets/AgentDetailView-CcvwSbwq.js +18 -0
- package/dist/client/assets/{AgentsView-DvN5EsoE.js → AgentsView-m8dBmo63.js} +3 -3
- package/dist/client/assets/{ChatView-DsETFRQp.js → ChatView-BKlUxTL8.js} +1 -1
- package/dist/client/assets/{DevServerView-D1_7SL1h.js → DevServerView-BygenPXh.js} +1 -1
- package/dist/client/assets/{DirectoryPicker-BBcm5G9F.js → DirectoryPicker-BosMLSTv.js} +1 -1
- package/dist/client/assets/{DocumentsView-OuVpmTPp.js → DocumentsView-BfEPLY3E.js} +1 -1
- package/dist/client/assets/{InsightsView-DMC_bLUc.js → InsightsView-B8FDRckf.js} +1 -1
- package/dist/client/assets/{MemoryView-cI4IK-lz.js → MemoryView-RT80_hUg.js} +1 -1
- package/dist/client/assets/{NodesView-C_LWLFNr.js → NodesView-UaaYrNBq.js} +1 -1
- package/dist/client/assets/{PiExtensionsManager-DCTHvy2u.js → PiExtensionsManager-Cjtt84Cv.js} +3 -3
- package/dist/client/assets/{PluginManager-BXMpkZx-.js → PluginManager-BuhG8uF_.js} +1 -1
- package/dist/client/assets/ResearchView-DLDnrYVm.js +1 -0
- package/dist/client/assets/ResearchView-aQkoD9QR.css +1 -0
- package/dist/client/assets/{RoadmapsView-BHTePn2u.js → RoadmapsView-DP7o1HsL.js} +2 -2
- package/dist/client/assets/SettingsModal-BAZQbTpw.js +31 -0
- package/dist/client/assets/{SettingsModal-BSZIno8y.js → SettingsModal-BWkxqiIg.js} +1 -1
- package/dist/client/assets/SettingsModal-FfIAhzcJ.css +1 -0
- package/dist/client/assets/{SetupWizardModal-DVoRhy_V.js → SetupWizardModal-BZFsWHpZ.js} +1 -1
- package/dist/client/assets/{SkillsView-CK52SRz5.js → SkillsView-87geY7V_.js} +1 -1
- package/dist/client/assets/TodoView-DaYieTys.js +6 -0
- package/dist/client/assets/{folder-open-C0SfzRFt.js → folder-open-Di63O7Be.js} +1 -1
- package/dist/client/assets/index-BFOt3vs-.js +656 -0
- package/dist/client/assets/index-BKZuWpfH.css +1 -0
- package/dist/client/assets/{list-checks-D5c428sr.js → list-checks-DQ8ece3U.js} +1 -1
- package/dist/client/assets/{star-GGmbVi2b.js → star-CHOSzU9a.js} +1 -1
- package/dist/client/assets/{upload-CrJJybRJ.js → upload-D7w2Kq_t.js} +1 -1
- package/dist/client/assets/{users-C56SMdh4.js → users-YG5FjHxk.js} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/client/version.json +1 -1
- package/dist/extension.js +5168 -4050
- package/dist/pi-claude-cli/package.json +1 -1
- package/package.json +1 -1
- package/dist/client/assets/AgentDetailView-khrspqE3.js +0 -18
- package/dist/client/assets/SettingsModal-2s-L1oWD.js +0 -31
- package/dist/client/assets/SettingsModal-xVaD-0tP.css +0 -1
- package/dist/client/assets/TodoView-BKqIV8P6.js +0 -6
- package/dist/client/assets/index-DawWARY5.css +0 -1
- package/dist/client/assets/index-DiC9GfBH.js +0 -656
|
@@ -1,656 +0,0 @@
|
|
|
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-DVoRhy_V.js","assets/DirectoryPicker-BBcm5G9F.js","assets/folder-open-C0SfzRFt.js","assets/DirectoryPicker-DzKVmxOf.css","assets/SetupWizardModal-DRF5fOoR.css","assets/SettingsModal-2s-L1oWD.js","assets/SettingsModal-BSZIno8y.js","assets/SettingsModal-xVaD-0tP.css","assets/users-C56SMdh4.js","assets/star-GGmbVi2b.js","assets/SettingsModal-YjpwLH2V.css","assets/AgentsView-DvN5EsoE.js","assets/upload-CrJJybRJ.js","assets/AgentsView-MotzGhZJ.css","assets/DocumentsView-OuVpmTPp.js","assets/DocumentsView-BrhyOdeE.css","assets/InsightsView-DMC_bLUc.js","assets/InsightsView-4KiUKzbz.css","assets/NodesView-C_LWLFNr.js","assets/NodesView-DCoS6iYh.css","assets/ChatView-DsETFRQp.js","assets/RoadmapsView-BHTePn2u.js","assets/RoadmapsView-BOYnyMCh.css","assets/SkillsView-CK52SRz5.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-cI4IK-lz.js","assets/MemoryView-DiajLXby.css","assets/DevServerView-D1_7SL1h.js","assets/DevServerView-DlZpuAnj.css","assets/TodoView-BKqIV8P6.js","assets/list-checks-D5c428sr.js","assets/TodoView-C1g65hJo.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as a,j as t,R as po,a as da,g as Bh,c as wg}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 Hh=(...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 Ng=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 Sg=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 Dd=e=>{const n=Sg(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 ol={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 Cg=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},Eg=a.createContext({}),_g=()=>a.useContext(Eg),Mg=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=""}=_g()??{},f=i??h?Number(s??m)*24/Number(n??d):s??m;return a.createElement("svg",{ref:u,...ol,width:n??d??ol.width,height:n??d??ol.height,stroke:e??g,strokeWidth:f,className:Hh("lucide",p,r),...!o&&!Cg(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(Mg,{ref:o,iconNode:n,className:Hh(`lucide-${Ng(Dd(e))}`,`lucide-${e}`,i),...r}));return s.displayName=Dd(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 Ag=[["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"}]],Rs=Ue("activity",Ag);/**
|
|
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 Rg=[["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"}]],To=Ue("archive",Rg);/**
|
|
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 Tg=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],wr=Ue("arrow-down",Tg);/**
|
|
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 Pg=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],_a=Ue("arrow-left",Pg);/**
|
|
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 Ig=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],Nr=Ue("arrow-right",Ig);/**
|
|
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 $g=[["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"}]],qh=Ue("arrow-up-down",$g);/**
|
|
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 Dg=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],zi=Ue("arrow-up",Dg);/**
|
|
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 Lg=[["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"}]],zg=Ue("book-open",Lg);/**
|
|
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 Og=[["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"}]],kn=Ue("bot",Og);/**
|
|
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 Fg=[["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"}]],xc=Ue("box",Fg);/**
|
|
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 Ug=[["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"}]],fo=Ue("brain",Ug);/**
|
|
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 Bg=[["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"}]],Vh=Ue("calendar",Bg);/**
|
|
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 Hg=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],qg=Ue("check-check",Hg);/**
|
|
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 Vg=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],$n=Ue("check",Vg);/**
|
|
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 Wg=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Yt=Ue("chevron-down",Wg);/**
|
|
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 Kg=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],Po=Ue("chevron-left",Kg);/**
|
|
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 Gg=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],bn=Ue("chevron-right",Gg);/**
|
|
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 Jg=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],ui=Ue("chevron-up",Jg);/**
|
|
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 Yg=[["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"}]],ss=Ue("circle-alert",Yg);/**
|
|
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 Qg=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],vn=Ue("circle-check-big",Qg);/**
|
|
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 Xg=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],Io=Ue("circle-dot",Xg);/**
|
|
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 Zg=[["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"}]],bc=Ue("circle-question-mark",Zg);/**
|
|
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 ex=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],tx=Ue("circle-stop",ex);/**
|
|
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 nx=[["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"}]],Sr=Ue("circle-x",nx);/**
|
|
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 sx=[["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"}]],ix=Ue("clipboard-list",sx);/**
|
|
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 ax=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],wi=Ue("clock",ax);/**
|
|
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 rx=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Wh=Ue("code",rx);/**
|
|
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 ox=[["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"}]],lx=Ue("columns-3",ox);/**
|
|
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 cx=[["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",cx);/**
|
|
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 dx=[["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"}]],ux=Ue("cpu",dx);/**
|
|
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 mx=[["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"}]],hx=Ue("download",mx);/**
|
|
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 px=[["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"}]],fx=Ue("ellipsis-vertical",px);/**
|
|
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 gx=[["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"}]],vc=Ue("ellipsis",gx);/**
|
|
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 xx=[["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"}]],bx=Ue("external-link",xx);/**
|
|
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 vx=[["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"}]],yc=Ue("eye-off",vx);/**
|
|
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 yx=[["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"}]],fa=Ue("eye",yx);/**
|
|
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 jx=[["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"}]],Os=Ue("file-code",jx);/**
|
|
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 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:"M9 10h6",key:"9gxzsh"}],["path",{d:"M12 13V7",key:"h0r20n"}],["path",{d:"M9 17h6",key:"r8uit2"}]],jc=Ue("file-diff",kx);/**
|
|
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 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"}],["path",{d:"M9 15h6",key:"cctwl0"}]],Nx=Ue("file-minus",wx);/**
|
|
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 Sx=[["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"}]],Kh=Ue("file-pen",Sx);/**
|
|
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 Cx=[["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"}]],Ex=Ue("file-plus",Cx);/**
|
|
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 _x=[["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"}]],Mx=Ue("file-question-mark",_x);/**
|
|
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 Ax=[["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"}]],Ui=Ue("file-text",Ax);/**
|
|
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 Rx=[["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"}]],Tx=Ue("file-type",Rx);/**
|
|
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 Px=[["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"}]],Gh=Ue("file",Px);/**
|
|
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 Ix=[["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"}]],kc=Ue("folder-git-2",Ix);/**
|
|
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 $x=[["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"}]],Ld=Ue("folder-root",$x);/**
|
|
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 Dx=[["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"}]],Un=Ue("folder",Dx);/**
|
|
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 Lx=[["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"}]],go=Ue("funnel",Lx);/**
|
|
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 zx=[["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"}]],Xs=Ue("git-branch",zx);/**
|
|
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 Ox=[["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"}]],Cr=Ue("git-commit-horizontal",Ox);/**
|
|
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 Fx=[["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"}]],Jh=Ue("git-merge",Fx);/**
|
|
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 Ux=[["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"}]],xs=Ue("git-pull-request",Ux);/**
|
|
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 Bx=[["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"}]],$o=Ue("globe",Bx);/**
|
|
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 Hx=[["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"}]],Yh=Ue("grid-3x3",Hx);/**
|
|
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 qx=[["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"}]],td=Ue("grip-vertical",qx);/**
|
|
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 Vx=[["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"}]],Wx=Ue("hard-drive",Vx);/**
|
|
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 Kx=[["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"}]],Gx=Ue("heart",Kx);/**
|
|
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 Jx=[["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"}]],mr=Ue("history",Jx);/**
|
|
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 Yx=[["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"}]],sr=Ue("inbox",Yx);/**
|
|
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 Qx=[["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"}]],Qh=Ue("key",Qx);/**
|
|
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 Xx=[["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"}]],Zx=Ue("keyboard",Xx);/**
|
|
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 eb=[["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"}]],Bi=Ue("layers",eb);/**
|
|
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 tb=[["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"}]],Hi=Ue("layout-grid",tb);/**
|
|
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 nb=[["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"}]],Zs=Ue("lightbulb",nb);/**
|
|
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 sb=[["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"}]],ga=Ue("link",sb);/**
|
|
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 ib=[["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"}]],ab=Ue("list-plus",ib);/**
|
|
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 rb=[["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"}]],Do=Ue("list-tree",rb);/**
|
|
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 ob=[["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"}]],wc=Ue("list",ob);/**
|
|
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 lb=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],rt=Ue("loader-circle",lb);/**
|
|
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 cb=[["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"}]],Lo=Ue("lock",cb);/**
|
|
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 db=[["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"}]],xa=Ue("mail",db);/**
|
|
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 ub=[["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"}]],Nc=Ue("map",ub);/**
|
|
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 mb=[["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"}]],zo=Ue("maximize-2",mb);/**
|
|
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 hb=[["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"}]],pb=Ue("message-square-plus",hb);/**
|
|
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 fb=[["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"}]],ji=Ue("message-square",fb);/**
|
|
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 gb=[["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"}]],Er=Ue("minimize-2",gb);/**
|
|
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 xb=[["path",{d:"M5 12h14",key:"1ays0h"}]],bb=Ue("minus",xb);/**
|
|
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 vb=[["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"}]],hr=Ue("monitor",vb);/**
|
|
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 yb=[["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"}]],jb=Ue("move",yb);/**
|
|
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 kb=[["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"}]],Sc=Ue("package",kb);/**
|
|
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 wb=[["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"}]],Xh=Ue("paperclip",wb);/**
|
|
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 Nb=[["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"}]],Fs=Ue("pause",Nb);/**
|
|
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 Sb=[["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"}]],ts=Ue("pencil",Sb);/**
|
|
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 Cb=[["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"}]],wn=Ue("play",Cb);/**
|
|
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 Eb=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],sn=Ue("plus",Eb);/**
|
|
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 _b=[["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"}]],Zh=Ue("radio",_b);/**
|
|
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 Mb=[["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"}]],Mn=Ue("refresh-cw",Mb);/**
|
|
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 Ab=[["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"}]],zd=Ue("rocket",Ab);/**
|
|
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 Rb=[["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"}]],Tb=Ue("rotate-ccw",Rb);/**
|
|
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 Pb=[["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"}]],Ib=Ue("rotate-cw",Pb);/**
|
|
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 $b=[["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"}]],ep=Ue("save",$b);/**
|
|
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 Db=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],ma=Ue("search",Db);/**
|
|
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 Lb=[["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"}]],Li=Ue("send",Lb);/**
|
|
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 zb=[["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"}]],pr=Ue("server",zb);/**
|
|
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 Ob=[["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"}]],or=Ue("settings",Ob);/**
|
|
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 Fb=[["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"}]],Ub=Ue("shield-alert",Fb);/**
|
|
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 Bb=[["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"}]],Hb=Ue("shield",Bb);/**
|
|
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 qb=[["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"}]],Vb=Ue("skull",qb);/**
|
|
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 Wb=[["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",Wb);/**
|
|
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 Kb=[["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"}]],tp=Ue("square-check-big",Kb);/**
|
|
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 Gb=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],gs=Ue("square",Gb);/**
|
|
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 Jb=[["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"}]],cs=Ue("target",Jb);/**
|
|
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 Yb=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],ci=Ue("terminal",Yb);/**
|
|
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 Qb=[["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"}]],xo=Ue("text-wrap",Qb);/**
|
|
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 Xb=[["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"}]],nn=Ue("trash-2",Xb);/**
|
|
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 Zb=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],ev=Ue("trending-up",Zb);/**
|
|
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 tv=[["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"}]],nd=Ue("triangle-alert",tv);/**
|
|
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 nv=[["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"}]],Od=Ue("unlink",nv);/**
|
|
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 sv=[["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"}]],ta=Ue("user",sv);/**
|
|
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 iv=[["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"}]],np=Ue("webhook",iv);/**
|
|
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 av=[["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"}]],Cc=Ue("workflow",av);/**
|
|
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 rv=[["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"}]],Fd=Ue("wrench",rv);/**
|
|
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 ov=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Kt=Ue("x",ov);/**
|
|
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 lv=[["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"}]],Fn=Ue("zap",lv),Ec="fusion:version-reload",_c="fusion:version-update";function cv(){try{if(sessionStorage.getItem(_c))return sessionStorage.removeItem(_c),!0}catch{}return!1}function sp(e){if(sessionStorage.getItem(Ec)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}sessionStorage.setItem(Ec,"1"),console.info("[versionCheck] reloading:",e),window.location.reload()}function dv(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 uv(e){return dv(e)?(sp(`chunk load error: ${e?.message??e}`),!0):!1}async function mv(){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 ll=!1;async function cl(){if(!(ll||document.visibilityState!=="visible")){ll=!0;try{const e=await mv();if(e&&e!=="mokosg52-e1bad735"){try{sessionStorage.setItem(_c,"1")}catch{}sp(`build version changed: mokosg52-e1bad735 -> ${e}`)}}finally{ll=!1}}}function hv(){window.setTimeout(()=>sessionStorage.removeItem(Ec),5e3),document.addEventListener("visibilitychange",()=>{cl()}),window.addEventListener("focus",()=>{cl()}),window.setTimeout(()=>void cl(),2e3)}class Oo 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),!uv(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(nd,{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 es({children:e,onError:n}){return t.jsx(Oo,{level:"page",onError:n,children:e})}function Pi({children:e,onError:n}){return t.jsx(Oo,{level:"modal",onError:n,children:e})}function pv({children:e,onError:n}){return t.jsx(Oo,{level:"root",onError:n,children:e})}const fv="modulepreload",gv=function(e){return"/"+e},Ud={},ln=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=gv(d),d in Ud)return;Ud[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":fv,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)})},sd="fn.authToken",Bd="token",xv="fn_token";let ha,Hd=!1,bo=!1;const Mc="fn:auth-token-recovery-required";function bv(){try{const e=window.localStorage.getItem(sd);return e&&e.length>0?e:void 0}catch{return}}function ip(e){try{window.localStorage.setItem(sd,e)}catch{}}function vv(){if(!(Hd||typeof window>"u")){Hd=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(Bd);if(!n)return;ip(n),e.searchParams.delete(Bd);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function ba(){if(ha!==void 0)return ha;const e=vv();if(e)return ha=e,e;const n=bv();if(n)return ha=n,n}function yv(e){ha=e,bo=!1,ip(e)}function jv(){ha=void 0,bo=!1;try{window.localStorage.removeItem(sd)}catch{}}function qd(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function kv(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function wv(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!kv(e.protocol))return!1;const s=e.hostname===n.hostname,i=e.port===n.port,r=qd(e.protocol)===qd(n.protocol);return s&&i&&r}function Nv(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 ei(e){const n=ba();if(!n||typeof window>"u")return e;const s=Nv(e);return!s||!wv(s.parsed)?e:(s.parsed.searchParams.set(xv,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function mi(e){const n=ba();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function Sv(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function Cv(){typeof window>"u"||bo||(bo=!0,window.dispatchEvent(new CustomEvent(Mc)))}async function Ev(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();Sv(i)&&Cv()}catch{}}function _v(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,ba();const e=window.fetch.bind(window);window.fetch=function(s,i){const r=ba(),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=>(Ev(u),u))}}class Mv extends Error{status;details;constructor(n,s,i){super(n),this.name="ApiRequestError",this.status=s,this.details=i}}function Av(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function is(e){return`/api${e}`}async function L(e,n={}){const s=is(e),i=ba(),r=(()=>{if(i){const g=new Headers(n.headers??{});return g.has("Content-Type")||g.set("Content-Type","application/json"),mi(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")||Av(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 Mv(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function sI(){return L("/health")}function iI(){return L("/updates/check")}function Rv(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 fr(e,n){const i=is(G(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(i,{headers:mi({"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 ap(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(G("/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 Qs(e,n,s){return L(G(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Tv(e,n,s,i,r,o,l,c,u){return L(G("/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 Pv(e,n,s){return L(G(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n})})}function Iv(e,n,s){const i=new URLSearchParams,r=i.size>0?`?${i.toString()}`:"";return L(G(`/tasks/${e}${r}`,n),{method:"DELETE"})}function $v(e,n){return L(G(`/tasks/${e}/merge`,n),{method:"POST"})}function Dv(e,n){return L(G(`/tasks/${e}/retry`,n),{method:"POST"})}function Lv(e,n){return L(G(`/tasks/${e}/duplicate`,n),{method:"POST"})}function rp(e,n){return L(G(`/tasks/${e}/pause`,n),{method:"POST"})}function zv(e,n){return L(G(`/tasks/${e}/unpause`,n),{method:"POST"})}function Ov(e,n){return L(G(`/tasks/${e}/archive`,n),{method:"POST"})}function Fv(e,n){return L(G(`/tasks/${e}/unarchive`,n),{method:"POST"})}function Uv(e){return L(G("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function Bv(e,n){return L(G(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function Hv(e,n){return L(G(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function qv(e){return L(G("/config",e))}function Fo(e){return L(G("/settings",e))}function Br(e,n){return L(G("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function Vv(e){return L(G("/update-check",e))}function aI(e){return L(G("/remote/settings",e))}function rI(e,n){return L(G("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function oI(e){return L(G("/remote/status",e))}function lI(e){return L(G("/remote/install-cloudflared",e),{method:"POST"})}function cI(e){return L(G("/remote/tunnel/start",e),{method:"POST"})}function dI(e){return L(G("/remote/tunnel/stop",e),{method:"POST"})}function uI(e){return L(G("/remote/token/persistent/regenerate",e),{method:"POST"})}function mI(e,n){return L(G("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function op(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 hI(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:i}=e,r=op(null,s,i);return L(G(`/remote/url${r}`,n))}function pI(e="text",n={}){const{projectId:s,tokenType:i="persistent",ttlMs:r}=n,o=op(e,i,r);return L(G(`/remote/qr${o}`,s))}function fI(e){return L(G("/memory",e))}function gI(e,n){return L(G("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function xI(e){return L(G("/memory/files",e))}function bI(e,n){const s=`path=${encodeURIComponent(e)}`;return L(G(`/memory/file?${s}`,n))}function vI(e,n,s){return L(G("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function yI(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(G("/memory/compact",i),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function jI(e){return L(G("/memory/dream",e),{method:"POST"})}function kI(e){return L(G("/memory/insights",e))}function wI(e,n){return L(G("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function NI(e){return L(G("/memory/extract",e),{method:"POST"})}function SI(e){return L(G("/memory/audit",e))}function CI(e){return L(G("/memory/stats",e))}function EI(e){return L(G("/memory/backend",e))}function _I(e){return L(G("/memory/install-qmd",e),{method:"POST"})}function MI(e,n){return L(G("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function Ki(){return L("/settings/global")}function cn(e){return L("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function AI(e){return L(G("/settings/scopes",e))}function RI(e){return L(G("/settings/pi-extensions",e))}function TI(e,n){return L(G("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function PI(e,n,s){return L(G("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function II(){return L("/pi-settings")}async function $I(e){return L("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function DI(e){return L("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function LI(e){return L(G("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function gr(e,n,s){const i=new FormData;i.append("file",n);const r=await fetch(is(G(`/tasks/${e}/attachments`,s)),{method:"POST",headers:mi(),body:i}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function Wv(e,n,s){return L(G(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function Vd(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=G(`/tasks/${e}/logs${r}`,n),l=await fetch(is(o),{headers:mi()});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 Kv(e,n,s,i){return L(G(`/tasks/${e}/comments/${n}`,i),{method:"PATCH",body:JSON.stringify({text:s})})}function Gv(e,n,s){return L(G(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function Jv(e,n){return L(G(`/tasks/${e}/documents`,n))}function Yv(e,n,s){return L(G(`/tasks/${e}/documents/${n}/revisions`,s))}async function zI(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(G(r,n))}function OI(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const i=s.toString(),r=`/files/markdown-list${i?`?${i}`:""}`;return L(G(r,e))}function Wd(e,n,s,i,r){return L(G(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:i?.author,metadata:i?.metadata})})}function Qv(e,n,s){return L(G(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function Xv(e,n,s){return L(G(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function Zv(e,n,s){return L(G(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function ey(e,n){return L(G(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function ty(e,n,s){return L(G(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function ds(){return L("/models")}function ny(){return L("/usage")}function sy(){return L("/providers/claude-cli/status")}async function FI(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return L(`/providers/hermes/status${n}`)}async function UI(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await L(`/providers/hermes/profiles${n}`)).profiles??[]}async function BI(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return L(`/providers/openclaw/status${n}`)}async function HI(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),L(`/providers/paperclip/status?${n.toString()}`)}async function qI(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 VI(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 WI(e){return L("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function KI(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 GI(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 JI(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 YI(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 iy(e){return L("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function xr(){return L("/auth/status")}function ay(e){return L("/auth/login",{method:"POST",body:JSON.stringify({provider:e,origin:window.location.origin})})}function ry(e){return L("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function oy(e,n){return L("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function ly(e){return L("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function cy(e,n,s,i){return L("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:i})})}function dy(e,n,s,i){return L(G("/github/issues/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function uy(e,n,s){return L("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function my(e,n,s,i){return L(G("/github/pulls/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function hy(e){return L(G("/git/remotes",e))}function py(e){return L(G("/git/remotes/detailed",e))}function fy(e,n,s){return L(G("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function gy(e,n){return L(G(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function xy(e,n,s){return L(G(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function by(e,n,s){return L(G(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function vy(e,n,s){return L(G(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function yy(e,n){return L(G(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function jy(e,n){return(await L(G("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function Hr(e,n,s,i){return L(G("/terminal/sessions",i),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function Kd(e,n){return L(G(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ky(e){return L(G("/terminal/sessions",e))}function zs(e){return L(G("/git/status",e))}function wy(e,n){const s=e?`?limit=${e}`:"";return L(G(`/git/commits${s}`,n))}function vo(e,n){return L(G(`/git/commits/${e}/diff`,n))}function Ny(e){return L(G("/git/commits/ahead",e))}function Sy(e,n,s,i){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return L(G(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,i))}function za(e){return L(G("/git/branches",e))}function Cy(e,n,s){const i=`?limit=${n}`;return L(G(`/git/branches/${encodeURIComponent(e)}/commits${i}`,s))}function Ey(e){return L(G("/git/worktrees",e))}function _y(e,n,s){return L(G("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function My(e,n){return L(G(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function Gd(e,n,s){const i=n?"?force=true":"";return L(G(`/git/branches/${encodeURIComponent(e)}${i}`,s),{method:"DELETE"})}function Ay(e,n){return L(G("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function Ry(e){return L(G("/git/pull",e),{method:"POST"})}function Ty(e){return L(G("/git/push",e),{method:"POST"})}function qr(e){return L(G("/git/stashes",e))}function Py(e,n){return L(G("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function Iy(e,n,s){return L(G(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function $y(e,n){return L(G(`/git/stashes/${e}`,n),{method:"DELETE"})}function Dy(e,n,s){const i=new URLSearchParams;return i.set("path",e),i.set("staged",String(n)),L(G(`/git/diff/file?${i.toString()}`,s))}function na(e){return L(G("/git/changes",e))}function Jd(e,n){return L(G("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function Ly(e,n){return L(G("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function Yd(e,n){return L(G("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function zy(e,n){return L(G("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function Oy(e){return L(G("/workspaces",e))}function Fy(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 Uy(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),L(`/files/${encodeURIComponent(n)}?${i.toString()}`)}function By(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 Hy(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 qy(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 Vy(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 Wy(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 Ky(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 lp(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${i.toString()}`}function Gy(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${i.toString()}`}function Jy(e,n,s){return L(G("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function Yy(e,n,s,i){return L(G("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Qy(e,n,s){return L(G(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Xy(e,n,s){return L(G(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function cp(e,n,s){return L(G("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function Zy(e,n,s){return L(G("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function ej(e,n,s){return L(G("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function tj(e,n,s){return L(G("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const Ac=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(Ac))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function nj(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function _r(e,n,s={}){const 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=nj(e,u),f=new EventSource(ei(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(),Ac.delete(g)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return Ac.add(g),g}function Qd(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 va(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 sj(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 ij(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((i,r)=>sj(i,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function aj(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 Xd(e){return Array.isArray(e)?e.map(Qd):(e.candidates??[]).map(Qd)}async function rj(e){try{const n=await L(G("/dev-server/candidates",e));return Xd(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await L(G("/dev-server/detect",e));return Xd(s)}throw n}}function id(e){return L(G("/dev-server/status",e)).then(va)}async function QI(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(G(`/dev-server/logs/history${i}`,n));return ij(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await id(n);return aj(o.logs,e)}throw r}}function oj(e,n){const s=e.cwd??e.packagePath??".",i=e.scriptName;return L(G("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:i,scriptId:i,cwd:s,packagePath:e.packagePath})}).then(va)}function lj(e){return L(G("/dev-server/stop",e),{method:"POST"}).then(va)}function cj(e){return L(G("/dev-server/restart",e),{method:"POST"}).then(va)}async function dj(e,n){const s=typeof e=="string"?{url:e}:e;try{const i=await L(G("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return va(i)}catch(i){if(i instanceof Error&&/\/dev-server\/preview-url/.test(i.message)){const r=await L(G("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return va(r)}throw i}}function XI(e){return is(G("/dev-server/logs/stream",e))}async function ZI(e){try{return(await L(G("/devserver",e))).sessions??[]}catch{try{const n=await id(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 e$(e,n){try{return await L(G(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await id(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 t$(e,n){try{return await L(G(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await oj({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 n$(e,n){try{return await L(G(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await lj(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 s$(e,n){try{return await L(G(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await cj(n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}}async function i$(e,n,s){try{const i=await L(G(`/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 dj({url:n},s);return{url:i.previewUrl??i.manualUrl??null,source:"manual"}}}async function a$(e){try{return(await L(G("/devserver/detect",e))).candidates??[]}catch{try{return(await rj(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function r$(e,n){return is(G(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function Mr(e,n,s=25e3){const i=setInterval(()=>{qk(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(i)}}}function uj(e,n){return is(G(`/planning/${encodeURIComponent(e)}/stream`,n))}function mj(e,n,s,i){const r=uj(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},u=_r(r,{onOpen:()=>{c(),o=Mr(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 Ar(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 hj(e){return L(Ar("/routines",e))}function pj(e,n){return L(Ar("/routines",n),{method:"POST",body:JSON.stringify(e)})}function Zd(e,n,s){return L(Ar(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function fj(e,n){await L(Ar(`/routines/${e}`,n),{method:"DELETE"})}function gj(e,n){return L(Ar(`/routines/${e}/trigger`,n),{method:"POST"})}function eu(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 xj(e){const n=G("/activity",e);return L(n,{method:"DELETE"})}function Uo(e){return L(G("/workflow-steps",e))}function tu(e,n){return L(G("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function bj(e,n,s){return L(G(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function vj(e,n){return L(G(`/workflow-steps/${e}`,n),{method:"DELETE"})}function nu(e,n){return L(G(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function yj(e,n){return L(G(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function jj(){return L("/workflow-step-templates")}function kj(e,n){return L(G(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function br(e){return L(G("/scripts",e))}function wj(e,n,s){return L(G("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function Nj(e,n){return L(G(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function dp(e,n,s){return(await L(G("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const Vr={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 up(e){if(!(e instanceof Error))return Vr.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?Vr.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?Vr.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:Vr.NETWORK}function Sj(e,n){return L(G("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function Cj(e,n,s){return L(G(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Ej(e,n){return is(G(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function _j(e,n,s,i){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=_r(Ej(e,n),{onOpen:()=>{l(),r=Mr(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 Mj(e,n,s,i){return L(G("/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 mp(e,n,s){return L(G("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function G(e,n){if(!n)return e;const s=e.includes("?")?"&":"?";return`${e}${s}projectId=${encodeURIComponent(n)}`}function Aj(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 Bo(e,n){const{nodeId:s,localNodeId:i,...r}=n??{},o=Aj(e,s,i);return L(o,r)}function Ma(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 hp(e,n){return L(G(`/agents/${encodeURIComponent(e)}`,n))}function Rj(e,n){return L(G("/agents",n),{method:"POST",body:JSON.stringify(e)})}function Tj(e,n,s){return L(G(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function o$(e,n,s){return L(G(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function l$(e,n,s){return L(G(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function c$(e,n,s){return L(G(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function d$(e,n){return L(G(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function u$(e,n,s){const i=`path=${encodeURIComponent(n)}`;return L(G(`/agents/${encodeURIComponent(e)}/memory/file?${i}`,s))}function m$(e,n,s,i){return L(G(`/agents/${encodeURIComponent(e)}/memory/file`,i),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function Pj(e,n,s){return L(G(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function Ij(e,n){return L(G(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function h$(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 p$(e,n,s){return L(G(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function f$(e,n,s){return L(G(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function g$(e,n,s){const i=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return L(G(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:i,triggerDetail:r})})}function x$(e,n){return L(G(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function $j(e){return L(G("/agents/stats",e))}function b$(e,n){return L(G(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function v$(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 y$(e,n){return L(G(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function su(e,n,s){return L(G(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function j$(e,n){return L(G(`/agents/${encodeURIComponent(e)}/tasks`,n))}function k$(){return L("/agents/companies")}function w$(e,n){return L(G("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function N$(e,n){return L(G("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function S$(e,n){return L(G(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function C$(e){return L(G("/backups",e))}function E$(e){return L(G("/backups",e),{method:"POST"})}function _$(e,n){const s=G("/settings/export",n),i=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return L(i)}function M$(e,n,s){return L(G("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function iu(){return L("/projects/across-nodes")}function lr(e,n){L("/_perf/dashboard-load",{method:"POST",body:JSON.stringify({source:e,message:n})}).catch(()=>{})}function yo(){return L("/nodes")}function Dj(e){return L("/nodes",{method:"POST",body:JSON.stringify(e)})}function Lj(e,n){return L(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function zj(e){return L(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Oj(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 A$(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=ba();l&&o.set("fn_token",l);const c=o.toString(),u=`/browse-directory${c?`?${c}`:""}`;return L(u)}function Fj(e){return L("/projects",{method:"POST",body:JSON.stringify(e)})}function pp(e){return L(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function au(e){return L(`/projects/${encodeURIComponent(e)}/health`)}function Uj(e){return L(G("/executor/stats",e))}function Bj(e){return L(G("/system-stats",e))}function Hj(e){return L(G("/kill-vitest",e),{method:"POST"})}function ru(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 qj(e){return L(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function Vj(e){return L(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function R$(){return L("/global-concurrency")}function T$(e){return L("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function Wj(e,n){return L(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function fp(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 Kj(e){return L(G("/missions",e))}function Gj(e,n){return L(G("/missions",n),{method:"POST",body:JSON.stringify(e)})}function gp(e,n){return L(G(`/missions/${encodeURIComponent(e)}`,n))}function Jj(e,n,s){return L(G(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Yj(e,n){return L(G(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Qj(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(G(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function Xj(e){return L(G("/missions/health",e))}function Zj(e,n,s){return L(G(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function ek(e,n,s){return L(G(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function tk(e,n){return L(G(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function nk(e,n,s){return L(G(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function sk(e,n,s){return L(G(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function ik(e,n){return L(G(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ak(e,n){return L(G(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function rk(e,n,s){return L(G(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function ok(e,n,s){return L(G(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function lk(e,n){return L(G(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ck(e,n,s){return L(G(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function dk(e,n){return L(G(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function uk(e,n,s,i){return L(G(`/missions/features/${encodeURIComponent(e)}/triage`,i),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function mk(e,n){return L(G(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST"})}function dl(e,n){return L(G(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function hk(e,n,s){return L(G(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function pk(e,n,s){return L(G(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function fk(e,n,s){return L(G(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function gk(e,n,s){return L(G(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function xk(e,n){return L(G(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function ul(e,n){return L(G(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function ou(e,n){return L(G(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function bk(e,n){return L(G(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function lu(e,n){return L(G(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function vk(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(G(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function yk(e,n){return L(G(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function jk(e,n){return L(G(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function kk(e,n){return L(G(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function wk(e,n){return L(G(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function Nk(e,n,s){return L(G(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function Sk(e,n,s){return L(G("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function Ck(e,n,s,i){return L(G("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Ek(e,n,s){return L(G(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function xp(e,n,s){return L(G("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function _k(e,n,s){return L(G("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Mk(e,n,s,i){const r=is(G(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=_r(r,{onOpen:()=>{c(),o=Mr(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 Rr(e,n,s){return G(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function Tr(e,n,s){return G(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function Ak(e,n){return L(Rr(e,"/start",n),{method:"POST"})}function Rk(e,n,s,i){return L(Rr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Tk(e,n,s,i){const r=is(Rr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=_r(r,{onOpen:()=>{c(),o=Mr(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 Pk(e,n,s){return L(Rr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Ik(e,n){return L(Rr(e,"/skip",n),{method:"POST"})}function $k(e,n){return L(Tr(e,"/start",n),{method:"POST"})}function Dk(e,n,s,i){return L(Tr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Lk(e,n,s,i){const r=is(Tr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=_r(r,{onOpen:()=>{c(),o=Mr(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 zk(e,n,s){return L(Tr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Ok(e,n){return L(Tr(e,"/skip",n),{method:"POST"})}async function Fk(e,n){try{return await L(G(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function P$(e){return L(G("/roadmaps",e))}function I$(e,n){return L(G("/roadmaps",n),{method:"POST",body:JSON.stringify(e)})}function $$(e,n){return L(G(`/roadmaps/${encodeURIComponent(e)}`,n))}function D$(e,n,s){return L(G(`/roadmaps/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function L$(e,n){return L(G(`/roadmaps/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function z$(e,n,s){return L(G(`/roadmaps/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function O$(e,n,s){return L(G(`/roadmaps/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function F$(e,n){return L(G(`/roadmaps/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function U$(e,n,s){return L(G(`/roadmaps/milestones/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function B$(e,n,s){return L(G(`/roadmaps/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function H$(e,n){return L(G(`/roadmaps/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function q$(e,n,s){return L(G(`/roadmaps/${encodeURIComponent(e)}/milestones/reorder`,s),{method:"POST",body:JSON.stringify({orderedMilestoneIds:n})})}function V$(e,n,s){return L(G(`/roadmaps/milestones/${encodeURIComponent(e)}/features/reorder`,s),{method:"POST",body:JSON.stringify({orderedFeatureIds:n})})}function W$(e,n,s,i){return L(G(`/roadmaps/features/${encodeURIComponent(e)}/move`,i),{method:"POST",body:JSON.stringify({targetMilestoneId:n,targetIndex:s})})}function K$(e,n){return L(G(`/roadmaps/${encodeURIComponent(e)}/handoff`,n))}function G$(e,n,s,i){return L(G(`/roadmaps/${encodeURIComponent(e)}/suggestions/milestones`,i),{method:"POST",body:JSON.stringify({goalPrompt:n.trim(),...s!==void 0?{count:s}:{}})})}function J$(e,n,s){return L(G(`/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 Y$(e){return L(G("/todos",e))}function Q$(e,n){const s={title:e};return L(G("/todos",n),{method:"POST",body:JSON.stringify(s)})}function X$(e,n,s){const i={title:n};return L(G(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function Z$(e,n){return L(G(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function eD(e,n,s){const i={text:n};return L(G(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(i)})}function tD(e,n,s){const i=n;return L(G(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function nD(e,n){return L(G(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function sD(e,n,s){return L(G(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function ya(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function ad(e){const n=e?`?projectId=${encodeURIComponent(e)}`:"",s=await fetch(is(`/ai-sessions${n}`),{headers:mi()});return s.ok?(await s.json()).sessions??[]:[]}async function di(e){const n=await fetch(is(`/ai-sessions/${encodeURIComponent(e)}`),{headers:mi()});return n.ok?n.json():null}async function Uk(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 Bk(e,n){return L(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function Hk(e,n){return L(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function bp(e){await fetch(is(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:mi()})}function qk(e,n){return L(G(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function Vk(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 Wk(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 vp(e){return L(G("/messages/unread-count",e))}function Kk(e,n){return L(G("/messages",n),{method:"POST",body:JSON.stringify(e)})}function Gk(e,n){return L(G(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function Jk(e){return L(G("/messages/read-all",e),{method:"POST"})}function Yk(e,n){return L(G(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Qk(e,n,s){const i=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return L(G(i,s))}function Xk(e,n){return L(G(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function iD(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 aD(e,n){return L(G(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function rD(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 oD(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 lD(e,n,s){return L(G(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function cD(e,n){return L(G(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function dD(e,n,s){return L(G(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function uD(e,n){return L(G(`/agents/${encodeURIComponent(e)}/budget`,n))}function mD(e,n){return L(G(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function hD(e){return L(G("/plugins",e))}async function pD(e,n){return L(G("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function fD(e,n){return L(G(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function gD(e,n){return L(G(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function xD(e,n){return L(G(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function bD(e,n){return L(G(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function vD(e,n,s){return L(G(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function yD(e,n){return L(G(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function Zk(e){return L(G("/plugins/ui-slots",e))}async function jD(e){return L(G("/plugins/runtimes",e))}async function kD(e){return(await L(G("/skills/discovered",e))).skills}async function wD(e,n,s){return L(G("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function ND(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(G(`/skills/catalog${r}`,s))}async function SD(e,n){return(await L(G(`/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 ew(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 tw(e,n){return L(G("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function ED(e,n,s){return L(G(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function _D(e,n){return L(G(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function cu(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(G(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function nw(e,n){return L(G(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function sw(e,n,s,i,r,o){const l=is(G(`/chat/sessions/${encodeURIComponent(e)}/messages`,r)),c=new AbortController;let u=!1;const d=(m,h)=>{if(!(!m||!h))switch(m){case"thinking":try{s.onThinking?.(JSON.parse(h))}catch{s.onThinking?.(h)}break;case"text":try{s.onText?.(JSON.parse(h))}catch{s.onText?.(h)}break;case"tool_start":try{s.onToolStart?.(JSON.parse(h))}catch{}break;case"tool_end":try{s.onToolEnd?.(JSON.parse(h))}catch{}break;case"done":try{s.onDone?.(JSON.parse(h))}catch{s.onDone?.({messageId:""})}break;case"error":try{const g=JSON.parse(h);s.onError?.(g.message||g)}catch{s.onError?.(h||"Stream error")}break}};return(async()=>{try{const m=Array.isArray(i)&&i.length>0,h=m?(()=>{const S=new FormData;return S.append("content",n),i.forEach(k=>S.append("attachments",k)),S})():JSON.stringify({content:n}),g=await fetch(l,{method:"POST",headers:m?mi():mi({"Content-Type":"application/json"}),body:h,signal:c.signal});if(!g.ok){const S=await g.text();let k=`Request failed: ${g.status}`;try{k=JSON.parse(S).error||k}catch{}s.onError?.(k);return}if(!g.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected");const p=g.body.getReader(),f=new TextDecoder;let x="",v="",b=[];const y=(S,k=!1)=>{x+=S;const A=x.split(`
|
|
613
|
-
`);x=A.pop()||"",k&&x.length>0&&(A.push(x),x="");for(const w of A){const E=w.endsWith("\r")?w.slice(0,-1):w;if(E.startsWith("event:"))v=E.slice(6).trim();else if(E.startsWith("data:")){const C=E.slice(5);b.push(C.startsWith(" ")?C.slice(1):C)}else if(E===""){const C=b.join(`
|
|
614
|
-
`);d(v,C),v="",b=[]}}if(k&&v&&b.length>0){const w=b.join(`
|
|
615
|
-
`);d(v,w),v="",b=[]}};for(;;){const{done:S,value:k}=await p.read();if(S){y(f.decode(),!0);break}y(f.decode(k,{stream:!0}))}}catch(m){if(m instanceof DOMException&&m.name==="AbortError"){u||s.onError?.("Connection aborted");return}if(u)return;s.onError?.(m instanceof Error?m.message:"Connection error")}})(),{close:()=>{u=!0,c.abort()},isConnected:()=>!u}}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(G(`/insights${i}`,n))}function AD(e,n){return L(G(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function RD(e="manual",n,s){return L(G("/insights/run",s),{method:"POST",body:JSON.stringify({trigger:e,inputMetadata:n})})}function TD(e){return L(G("/insights/runs",e))}function PD(e,n){return L(G(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function iw(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 aw({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}=iw(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]})]})}function rw(e){return e.charAt(0).toUpperCase()+e.slice(1)}function qi({status:e,showLabel:n=!1,className:s,compact:i=!1}){const r=rw(e);return t.jsxs("span",{className:`node-health-dot${i?" node-health-dot--compact":""}${s?` ${s}`:""}`,title:r,"aria-label":`Node status: ${r}`,children:[t.jsx("span",{className:`status-dot status-dot--${e}`}),n?t.jsx("span",{className:"node-health-dot__label",children:r}):null]})}const du=new Map,ow=6e4;function yp(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=du.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 Zk(e);if(h||u.current)return;du.set(m,{slots:x,expiresAt:Date.now()+ow}),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 Ho({slotId:e,projectId:n}){const{getSlotsForId:s,loading:i,error:r}=yp(n);if(i||r||!e)return null;const o=s(e);return o.length===0?null:t.jsx(Oo,{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 lw(){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 Pr(){const[e,n]=a.useState(lw);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}function Aa(e){return e.replace(/\\/g,"/")}function rd(e){return e.replace(/[\\/]+$/g,"")}function od(e){const n=Aa(rd(e));return n?n.split("/").filter(Boolean):[]}function ld(e){const n=Aa(rd(e));if(!n)return e;const s=n.split("/").filter(Boolean);return s[s.length-1]||n}function jp(e,n){const s=od(e);return s.length===0?Aa(e):s.slice(-2).join("/")}function cw(e){const n=Aa(rd(e)),s=n.lastIndexOf("/");return s<0?"":n.slice(0,s+1)}function dw(e,n){return!e||e==="."?n:[...od(e),n].join("/")}function uw(e){const n=od(e);return n.length===0?".":(n.pop(),n.length===0?".":n.join("/"))}function ID(e){const n=Aa(e),s=n.match(/^([A-Za-z]:)(?:\/(.*))?$/);if(s){const r=`${s[1]}/`,o=(s[2]??"").split("/").filter(Boolean),l=[{label:s[1],path:r}];for(let c=0;c<o.length;c+=1)l.push({label:o[c],path:`${r}${o.slice(0,c+1).join("/")}`});return l}if(n.startsWith("/")){const r=n.split("/").filter(Boolean),o=[{label:"/",path:"/"}];for(let l=0;l<r.length;l+=1)o.push({label:r[l],path:`/${r.slice(0,l+1).join("/")}`});return o}const i=n.split("/").filter(Boolean);return i.map((r,o)=>({label:r,path:i.slice(0,o+1).join("/")}))}const kp={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function mw({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(Yt,{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=kp[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:jp(u.path)})]}),d&&t.jsx($n,{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 uu({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 hw({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:A,onToggleGlobalPause:w,onToggleEnginePause:E,view:C="board",onChangeView:z,showSkillsTab:_,showAgentsTab:$,searchQuery:F="",onSearchChange:V,projects:D=[],currentProject:T,onSelectProject:I,onViewAllProjects:U,projectId:Y,isElectron:ne=!1,mobileNavEnabled:N,availableNodes:P=[],currentNode:R,onSelectNode:j,isRemote:W=!1,experimentalFeatures:K}){const ke=Pr(),be=ke==="mobile",ve=be||ke==="tablet",O=be&&N,[oe,te]=a.useState(!1),[pe,de]=a.useState(!1),[ge,ie]=a.useState(!1),[Ee,Le]=a.useState(!1),[qe,et]=a.useState(!1),[Xe,Ze]=a.useState(!1),[it,Ie]=a.useState(!1),[Ke,re]=a.useState(!1),[xe,se]=a.useState(!1),[Ae,ze]=a.useState(!1),[me,_e]=a.useState(!1),[Fe,nt]=a.useState({}),[we,le]=a.useState(!1),[Te,he]=a.useState(-1),[Me,We]=a.useState(null),[Re,ut]=a.useState({}),[Q,ue]=a.useState(!1),ye=a.useRef(null),at=a.useRef(null),X=a.useRef(null),Ye=a.useRef(null),ot=a.useRef(null),ht=a.useRef(null),yt=a.useRef(!1),vt=a.useRef(null),pt=a.useRef(null),Et=a.useRef(null),It=a.useRef(null),Bt=a.useRef(null),_t=a.useRef(null),Pt=a.useRef(null),$t=a.useRef(null),Ht=a.useRef(!1),Gt=a.useMemo(()=>P.filter(Ne=>Ne.type==="remote"),[P]),Dt=Gt.length>0,Tt=a.useMemo(()=>Object.entries(Fe).sort(([Ne],[ae])=>Ne.localeCompare(ae)),[Fe]),jt=Tt.length>0,Mt=Tt.length+(jt?1:0),Zt=a.useMemo(()=>Object.entries(Re).sort(([Ne],[ae])=>Ne.localeCompare(ae)),[Re]),At=a.useMemo(()=>!!(K?.todoView||K?.insights||K?.roadmap||_||K?.memoryView||K?.devServerView),[K,_]),H=a.useCallback(()=>{const Ne=window.visualViewport;return Ne&&Ne.width>0&&Ne.height>0?{width:Ne.width,height:Ne.height,offsetTop:Ne.offsetTop,offsetLeft:Ne.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),fe=a.useCallback(()=>{const Ne=Pt.current;if(!Ne)return;const ae=Ne.getBoundingClientRect(),Ge=$t.current,{width:ct,height:Lt,offsetTop:qt,offsetLeft:En}=H(),hn=16,Vt=16,J=6,Pe=Ge?.offsetWidth||Math.max(ae.width,260),Qe=Math.min(Pe,Math.max(ct-hn*2,160)),tt=Ge?.offsetHeight||280,mt=Math.min(tt,Math.max(Lt-Vt*2,160)),St=ae.top-qt,zt=ae.bottom-qt,Sn=ae.right-En,an=Lt-zt,kt=St,as=an<mt&&kt>an,js=Math.min(Math.max(Sn-Qe,hn),ct-hn-Qe)+En,Ps=as?Math.max(Vt+qt,St-mt-J+qt):Math.min(zt+J+qt,Lt+qt-Vt-mt);We({top:Ps,left:js,width:Qe})},[H]),$e=a.useCallback((Ne,ae)=>{v?.(Ne,ae),_e(!1),he(-1)},[v]),M=a.useCallback(()=>{x?.(),_e(!1),he(-1)},[x]),ee=a.useCallback(Ne=>{switch(Ne.key){case"ArrowDown":Ne.preventDefault(),Mt>0&&he(ae=>ae<Mt-1?ae+1:0);break;case"ArrowUp":Ne.preventDefault(),Mt>0&&he(ae=>ae>0?ae-1:Mt-1);break;case"Enter":if(Ne.preventDefault(),Te>=0)if(Te<Tt.length){const[ae,Ge]=Tt[Te];$e(ae,Ge)}else jt&&Te===Tt.length&&M();break;case"Home":Ne.preventDefault(),Mt>0&&he(0);break;case"End":Ne.preventDefault(),Mt>0&&he(Mt-1);break}},[M,$e,Te,Tt,jt,Mt]);a.useEffect(()=>{yt.current=qe},[qe]),a.useEffect(()=>{Ht.current=me},[me]),a.useEffect(()=>{if(!qe||!ve)return;let Ne=!1;return ue(!0),br(Y).then(ae=>{Ne||ut(ae)}).catch(()=>{Ne||ut({})}).finally(()=>{Ne||ue(!1)}),()=>{Ne=!0}},[qe,ve,Y]),a.useEffect(()=>{if(!me||ve)return;let Ne=!1;return le(!0),br(Y).then(ae=>{Ne||nt(ae)}).catch(()=>{Ne||nt({})}).finally(()=>{Ne||le(!1)}),()=>{Ne=!0}},[me,ve,Y]),a.useEffect(()=>{if(!me)return;const Ne=ae=>{_t.current&&!_t.current.contains(ae.target)&&_e(!1)};return document.addEventListener("mousedown",Ne),()=>document.removeEventListener("mousedown",Ne)},[me]),a.useEffect(()=>{if(!me)return;const Ne=ae=>{ae.key==="Escape"&&(_e(!1),Pt.current?.focus())};return document.addEventListener("keydown",Ne),()=>document.removeEventListener("keydown",Ne)},[me]),a.useEffect(()=>{if(me){he(-1);const Ne=window.setTimeout(()=>$t.current?.focus(),0);return()=>window.clearTimeout(Ne)}We(null)},[me]),a.useEffect(()=>{if(!me)return;const Ne=requestAnimationFrame(()=>{fe()});return()=>cancelAnimationFrame(Ne)},[me,we,Tt.length,jt,fe]),a.useEffect(()=>{if(!me)return;const Ne=()=>fe();window.addEventListener("resize",Ne),window.addEventListener("scroll",Ne,!0);const ae=window.visualViewport;return ae&&(ae.addEventListener("resize",Ne),ae.addEventListener("scroll",Ne)),()=>{window.removeEventListener("resize",Ne),window.removeEventListener("scroll",Ne,!0),ae&&(ae.removeEventListener("resize",Ne),ae.removeEventListener("scroll",Ne))}},[me,fe]),a.useEffect(()=>{ve&&(_e(!1),he(-1))},[ve]);const Oe=oe||F.length>0,dt=(pe||F.length>0)&&!ge,Nt=(C==="board"||C==="list")&&!be&&V&&!ge&&F.length===0,Ct=(C==="board"||C==="list")&&!be&&V;a.useEffect(()=>{F===""&&ie(!1)},[F]),a.useEffect(()=>{if(!Ee)return;const Ne=ae=>{at.current&&!at.current.contains(ae.target)&&ye.current&&!ye.current.contains(ae.target)&&Le(!1)};return document.addEventListener("mousedown",Ne),()=>document.removeEventListener("mousedown",Ne)},[Ee]),a.useEffect(()=>{if(!xe)return;const Ne=ae=>{Ye.current&&!Ye.current.contains(ae.target)&&X.current&&!X.current.contains(ae.target)&&se(!1)};return document.addEventListener("mousedown",Ne),()=>document.removeEventListener("mousedown",Ne)},[xe]),a.useEffect(()=>{if(!Xe)return;const Ne=ae=>{vt.current&&!vt.current.contains(ae.target)&&Ze(!1)};return document.addEventListener("mousedown",Ne),()=>document.removeEventListener("mousedown",Ne)},[Xe]),a.useEffect(()=>{const Ne=ae=>{if(ae.key==="Escape"){if(re(!1),se(!1),yt.current){et(!1);return}if(Ht.current){_e(!1),Pt.current?.focus();return}Le(!1),te(!1),Ze(!1),Ie(!1)}};return document.addEventListener("keydown",Ne),()=>document.removeEventListener("keydown",Ne)},[]),a.useEffect(()=>{if(!it)return;const Ne=ae=>{pt.current&&!pt.current.contains(ae.target)&&Ie(!1)};return document.addEventListener("mousedown",Ne),()=>document.removeEventListener("mousedown",Ne)},[it]),a.useEffect(()=>{if(!Ae)return;const Ne=ae=>{Bt.current&&!Bt.current.contains(ae.target)&&ze(!1)};return document.addEventListener("mousedown",Ne),()=>document.removeEventListener("mousedown",Ne)},[Ae]),a.useEffect(()=>{if(!Ae)return;const Ne=ae=>{ae.key==="Escape"&&ze(!1)};return document.addEventListener("keydown",Ne),()=>document.removeEventListener("keydown",Ne)},[Ae]),a.useEffect(()=>{if(!Ke)return;const Ne=ae=>{Et.current&&!Et.current.contains(ae.target)&&It.current&&!It.current.contains(ae.target)&&re(!1)};return document.addEventListener("mousedown",Ne),()=>document.removeEventListener("mousedown",Ne)},[Ke]);const Rt=a.useCallback(()=>{te(Ne=>!Ne)},[]),un=a.useCallback(()=>{de(!0),ie(!1)},[]),mn=a.useCallback(()=>{de(!1),ie(!0),V&&V("")},[V]),Nn=a.useCallback(()=>{Le(Ne=>!Ne)},[]),Qt=a.useCallback(Ne=>{Ne&&Ne(),Le(!1),et(!1)},[]),An=a.useCallback(()=>{te(!1),V&&V("")},[V]);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"})]}),be&&D.length>=1&&I&&t.jsxs("div",{className:"mobile-project-switch",ref:pt,children:[t.jsx("button",{className:`mobile-project-switch-trigger${it?" mobile-project-switch-trigger--open":""}`,onClick:()=>Ie(Ne=>!Ne),title:"Switch project","aria-label":"Switch project","aria-expanded":it,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(Yt,{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:D.map(Ne=>{const ae=T?.id===Ne.id,Ge=kp[Ne.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${ae?" mobile-project-switch-item--current":""}`,onClick:()=>{I(Ne),Ie(!1)},role:"option","aria-selected":ae,"data-testid":`mobile-project-switch-item-${Ne.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:Ge||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:Ne.name}),t.jsx("span",{className:"mobile-project-switch-path",children:jp(Ne.path)})]}),ae&&t.jsx($n,{size:14,className:"mobile-project-switch-check"})]},Ne.id)})})]}),!ve&&D.length>=1&&U&&t.jsx(mw,{projects:D,currentProject:T??null,onViewAll:U,onSelectProject:I}),Dt&&t.jsxs("div",{className:`header-node-selector${be?" header-node-selector--mobile":""}`,ref:be?void 0:vt,children:[t.jsx(aw,{node:R??null,showDetails:!be}),!be&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${Xe?" node-selector-trigger--open":""}`,onClick:()=>Ze(Ne=>!Ne),title:"Switch node","aria-label":"Switch node","aria-expanded":Xe,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(bn,{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${W?"":" node-selector-option--active"}`,onClick:()=>{j?.(null),Ze(!1)},role:"option","aria-selected":!W,"data-testid":"node-option-local",children:[t.jsx(qi,{status:"online",compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),Gt.map(Ne=>t.jsxs("button",{className:`node-selector-option${R?.id===Ne.id?" node-selector-option--active":""}`,onClick:()=>{j?.(Ne),Ze(!1)},role:"option","aria-selected":R?.id===Ne.id,"data-testid":`node-option-${Ne.id}`,children:[t.jsx(qi,{status:Ne.status,compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:Ne.name}),t.jsx("span",{className:"node-selector-option-status",children:Ne.status})]},Ne.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[O&&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(Hi,{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(wc,{size:16})})]}),V&&be&&(O||C==="board"||C==="list")&&!Oe&&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(ma,{size:16})}),Nt&&t.jsx("button",{className:"btn-icon",onClick:un,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(ma,{size:16})}),be&&O&&o&&t.jsx("button",{className:"btn-icon",onClick:Ne=>o(Ne.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(Rs,{size:16})}),!O&&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(Hi,{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(wc,{size:16})}),$&&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(kn,{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(cs,{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(ji,{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(Ui,{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(xa,{size:16})}),At&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:It,className:`view-toggle-btn${["skills","roadmaps","insights","memory","dev-server","devserver"].includes(C)||K?.todoView&&C==="todos"?" active":""}`,onClick:()=>re(Ne=>!Ne),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":Ke,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(Yt,{size:12})}),Ke&&t.jsxs("div",{ref:Et,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[K?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="insights"?" active":""}`,onClick:()=>{z("insights"),re(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(Qn,{size:14}),t.jsx("span",{children:"Insights"})]}),K?.roadmap&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="roadmaps"?" active":""}`,onClick:()=>{z("roadmaps"),re(!1)},role:"menuitem","data-testid":"view-overflow-roadmaps",children:[t.jsx(Nc,{size:14}),t.jsx("span",{children:"Roadmaps"})]}),_&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="skills"?" active":""}`,onClick:()=>{z("skills"),re(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(Fn,{size:14}),t.jsx("span",{children:"Skills"})]}),K?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="memory"?" active":""}`,onClick:()=>{z("memory"),re(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(fo,{size:14}),t.jsx("span",{children:"Memory"})]}),K?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="dev-server"||C==="devserver"?" active":""}`,onClick:()=>{z("devserver"),re(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(hr,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]}),K?.todoView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="todos"?" active":""}`,onClick:()=>{z("todos"),re(!1)},role:"menuitem","data-testid":"view-overflow-todos",children:[t.jsx(tp,{size:14}),t.jsx("span",{children:"Todos"})]})]})]})]}),!ve&&o&&t.jsx("button",{className:"btn-icon",onClick:Ne=>o(Ne.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"desktop-header-usage-btn",children:t.jsx(Rs,{size:16})}),!ve&&c&&t.jsx("button",{className:"btn-icon",onClick:c,title:"System Stats","data-testid":"desktop-header-system-stats-btn",children:t.jsx(hr,{size:16})}),!ve&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(mr,{size:16})}),!ve&&!ne&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(uu,{size:16})}),!ve&&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(Zs,{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})]}),!ve&&t.jsxs("div",{className:"terminal-split-btn",ref:_t,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(ci,{size:16})}),x&&v&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"terminal-split-btn__divider"}),t.jsx("button",{ref:Pt,className:`btn-icon terminal-split-btn__chevron${me?" btn-icon--active":""}`,onClick:()=>_e(Ne=>!Ne),title:"Scripts","aria-haspopup":"listbox","aria-expanded":me,"aria-label":"Quick scripts","data-testid":"scripts-btn",children:t.jsx(Yt,{size:12,className:`quick-scripts-dropdown__trigger-chevron${me?" rotate":""}`})}),me&&t.jsx("div",{ref:$t,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:ee,"data-testid":"quick-scripts-dropdown",style:Me?{position:"fixed",top:`${Me.top}px`,left:`${Me.left}px`,width:`${Me.width}px`,right:"auto"}:void 0,children:we?t.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[t.jsx(rt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):Tt.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(ci,{size:16})}),t.jsx("p",{children:"No scripts configured"}),t.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:M,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:Tt.map(([Ne,ae],Ge)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${Te===Ge?"highlighted":""}`,onClick:()=>$e(Ne,ae),role:"option","aria-selected":Te===Ge,"data-testid":`quick-script-item-${Ne}`,children:[t.jsx(wn,{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:Ne}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:ae,children:ae.length>50?`${ae.slice(0,50)}...`:ae})]})]},Ne))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${jt&&Te===Tt.length?"highlighted":""}`,onClick:M,"data-testid":"quick-scripts-manage",children:[t.jsx(or,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})]}),!ve&&y&&t.jsx("button",{className:`btn-icon${S?" btn-icon--active":""}`,onClick:y,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(Un,{size:16})}),!ve&&h&&t.jsx("button",{className:"btn-icon",onClick:h,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Xs,{size:16})}),!ve&&f&&t.jsx("button",{className:"btn-icon",onClick:f,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(Cc,{size:16})}),!ve&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:X,className:"btn-icon",onClick:()=>se(Ne=>!Ne),title:"More actions","aria-label":"More actions","aria-expanded":xe,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(vc,{size:16})}),xe&&t.jsxs("div",{ref:Ye,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[g&&p!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{g(),se(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx(pr,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{Qt(m),se(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(wi,{size:14}),t.jsx("span",{children:"Automation"})]})]})]}),t.jsxs("div",{className:"engine-control-split-btn",ref:Bt,children:[t.jsx("button",{className:`btn-icon engine-control-split-btn__main${k?" btn-icon--stopped":""}`,onClick:w,title:k?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:k?t.jsx(wn,{size:16}):t.jsx(gs,{size:16})}),t.jsx("span",{className:"engine-control-split-btn__divider"}),t.jsx("button",{className:`btn-icon engine-control-split-btn__chevron${Ae?" btn-icon--active":""}`,onClick:()=>ze(Ne=>!Ne),title:"Engine options","aria-haspopup":"menu","aria-expanded":Ae,"data-testid":"engine-control-chevron-btn",children:t.jsx(Yt,{size:12})}),Ae&&t.jsx("div",{className:"engine-control-split-btn__menu",role:"menu",children:t.jsxs("button",{className:`engine-control-split-btn__menu-item${A?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{E?.(),ze(!1)},role:"menuitem",title:A?"Resume scheduling":"Pause triage",disabled:!!k,"data-testid":"engine-control-pause-triage-btn",children:[A?t.jsx(wn,{size:14}):t.jsx(Fs,{size:14}),t.jsx("span",{children:A?"Resume scheduling":"Pause triage"})]})})]}),!ve&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(or,{size:16})}),t.jsx(Ho,{slotId:"header-action",projectId:Y}),ve&&!O&&t.jsx("button",{ref:ye,className:"btn-icon compact-overflow-trigger",onClick:Nn,title:"More header actions","aria-label":"More header actions","aria-expanded":Ee,"aria-haspopup":"menu",children:t.jsx(vc,{size:16})}),ve&&!O&&Ee&&t.jsxs("div",{ref:at,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[D.length>=1&&U&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Qt(U),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(Yh,{size:16}),t.jsx("span",{children:"Projects"})]}),y&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Qt(y),role:"menuitem","data-testid":"overflow-files-btn",children:[t.jsx(Un,{size:16}),t.jsx("span",{children:"Browse Files"})]}),t.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>Qt(r>0&&i?i:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx(Zs,{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:()=>Qt(h),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(Xs,{size:16}),t.jsx("span",{children:"Git Manager"})]}),g&&p!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Qt(g),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(pr,{size:16}),t.jsx("span",{children:"Nodes"})]}),!ne&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Qt(n),role:"menuitem",children:[t.jsx(uu,{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:()=>Qt(b),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[t.jsx(ci,{size:16}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>et(Ne=>!Ne),role:"menuitem","aria-expanded":qe,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(bn,{size:14,className:`mobile-overflow-chevron${qe?" mobile-overflow-chevron--open":""}`})})]}),qe&&t.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:Q?t.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[t.jsx(rt,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):Zt.length>0?t.jsxs(t.Fragment,{children:[Zt.map(([Ne,ae])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{v&&v(Ne,ae),Le(!1),et(!1)},role:"menuitem","data-testid":`overflow-script-item-${Ne}`,children:[t.jsx(wn,{size:14}),t.jsx("span",{children:Ne})]},Ne)),x&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>Qt(x),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Os,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):x&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>Qt(x),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Os,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Qt(m),role:"menuitem","data-testid":"overflow-schedules-btn",children:[t.jsx(wi,{size:16}),t.jsx("span",{children:"Automation"})]}),l&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Qt(l),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[t.jsx(mr,{size:16}),t.jsx("span",{children:"View Activity Log"})]}),u&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Qt(u),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(xa,{size:16}),t.jsxs("span",{children:["Mailbox",d>0?` (${d})`:""]})]}),o&&t.jsxs("button",{className:"mobile-overflow-item",onClick:Ne=>Qt(()=>o(Ne.currentTarget.getBoundingClientRect())),role:"menuitem","data-testid":"overflow-usage-btn",children:[t.jsx(Rs,{size:16}),t.jsx("span",{children:"View Usage"})]}),f&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Qt(f),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(Cc,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Qt(e),role:"menuitem",children:[t.jsx(or,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),Ct&&dt&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{className:"header-search",children:[t.jsx(ma,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:F,onChange:Ne=>V(Ne.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:mn,"aria-label":"Close search",children:t.jsx(Kt,{size:14})})]})}),V&&be&&Oe&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{ref:ot,className:"header-search mobile-search-expanded",children:[t.jsx(ma,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:ht,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:F,onChange:Ne=>V(Ne.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:An,"aria-label":"Close search",children:t.jsx(Kt,{size:14})})]})})]})}const pw={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},fw={globalPause:!1,globalPauseReason:void 0,enginePaused:!1,maxConcurrent:2,maxTriageConcurrent:2,globalMaxConcurrent:4,maxWorktrees:4,pollIntervalMs:15e3,heartbeatMultiplier:1,groupOverlappingFiles:!0,overlapIgnorePaths:[],autoMerge:!0,mergeStrategy:"direct",requirePrApproval:!1,pushAfterMerge:!1,pushRemote:"origin",unavailableNodePolicy:"block",defaultNodeId:void 0,worktreeInitCommand:void 0,testCommand:void 0,buildCommand:void 0,recycleWorktrees:!1,worktreeNaming:"random",taskPrefix:"FN",includeTaskIdInCommit:!0,commitAuthorEnabled:!0,commitAuthorName:"Fusion",commitAuthorEmail:"noreply@runfusion.ai",planningProvider:void 0,planningModelId:void 0,planningFallbackProvider:void 0,planningFallbackModelId:void 0,defaultProviderOverride:void 0,defaultModelIdOverride:void 0,executionProvider:void 0,executionModelId:void 0,validatorProvider:void 0,validatorModelId:void 0,validatorFallbackProvider:void 0,validatorFallbackModelId:void 0,modelPresets:[],autoSelectModelPreset:!1,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,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:{}},gw=Object.freeze(Object.keys(pw)),xw=Object.freeze(Object.keys(fw));function $D(e){return gw.includes(e)}function DD(e){return xw.includes(e)}function Se(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function bw(e){return!!(e?.provider&&e?.modelId)}function Ni(...e){for(const n of e)if(bw(n))return{provider:n.provider,modelId:n.modelId};return{}}function qo(e){return Ni({provider:e?.defaultProviderOverride,modelId:e?.defaultModelIdOverride},{provider:e?.defaultProvider,modelId:e?.defaultModelId})}function vw(e){return Ni({provider:e?.executionProvider,modelId:e?.executionModelId},{provider:e?.executionGlobalProvider,modelId:e?.executionGlobalModelId},qo(e))}function yw(e){return Ni({provider:e?.planningProvider,modelId:e?.planningModelId},{provider:e?.planningGlobalProvider,modelId:e?.planningGlobalModelId},qo(e))}function jw(e){return Ni({provider:e?.validatorProvider,modelId:e?.validatorModelId},{provider:e?.validatorGlobalProvider,modelId:e?.validatorGlobalModelId},qo(e))}function LD(e){return Ni({provider:e?.titleSummarizerProvider,modelId:e?.titleSummarizerModelId},{provider:e?.titleSummarizerGlobalProvider,modelId:e?.titleSummarizerGlobalModelId},{provider:e?.planningProvider,modelId:e?.planningModelId},qo(e))}function wp(e,n){return Ni({provider:e.modelProvider,modelId:e.modelId},vw(n))}function Np(e,n){return Ni({provider:e.validatorModelProvider,modelId:e.validatorModelId},jw(n))}function Sp(e,n){return Ni({provider:e.planningModelProvider,modelId:e.planningModelId},yw(n))}const zD=["off","minimal","low","medium","high"],Oi=["triage","todo","in-progress","in-review","done","archived"],cd=["low","normal","high","urgent"],bs="normal",kw=["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"],Pn={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},ww={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"},Rc={triage:["todo"],todo:["in-progress","triage"],"in-progress":["in-review","todo","triage","done"],"in-review":["done","in-progress","todo","triage"],done:["todo","triage","archived"],archived:["done"]};function Nw(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 Sw(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 Cw({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 Cp=a.createContext(null);function Ew({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 po.createElement(Cp.Provider,{value:u},e,po.createElement(Cw,{isOpen:c!==null,options:c?.options??null,onConfirm:()=>l(!0),onCancel:()=>l(!1)}))}function Bs(){const e=a.useContext(Cp);return e||{confirm:async n=>!1}}function _w(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 Ep({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(xs,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("span",{className:`card-github-badge ${_w(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,onClick:r,children:[t.jsx(Io,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function Wr(e,n){return`${e??"default"}:${n}`}class Mw{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=Wr(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const i=Wr(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=Wr(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(ei(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=Wr(this.projectId,l.taskId),u=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:mu(l,"prInfo")?l.prInfo??null:u?.prInfo,issueInfo:mu(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 Ii=new Mw;let Aw=0;function mu(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function _p(e){const n=a.useRef(null);n.current===null&&(n.current=`badge-hook-${Aw++}`);const s=a.useSyncExternalStore(o=>Ii.subscribe(o),()=>Ii.getSnapshot(),()=>Ii.getSnapshot()),i=a.useCallback(o=>{Ii.subscribeTask(n.current,o)},[]),r=a.useCallback(o=>{Ii.unsubscribeTask(n.current,o)},[]);return a.useEffect(()=>{Ii.setProjectId(e??null)},[e]),a.useEffect(()=>()=>{Ii.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:i,unsubscribeFromBadge:r}}function jo(e,n,s,i){return e===void 0||!n?s:!i||n>=i?e??void 0:s}function Rw({taskId:e,prInfo:n,issueInfo:s,updatedAt:i,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:u}=_p(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=jo(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??i),g=jo(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??i);return!h&&!g?null:t.jsx(Ep,{prInfo:h,issueInfo:g})}const Tw=a.memo(Rw);Tw.displayName="TaskCardBadge";const Pw={sm:16,md:20,lg:24};function Iw({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 hu({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 Ws({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 $w({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 pu({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 Dw({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 ml({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 fu({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 gu({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 xu({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 Oa({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 bu({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 hl({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 vu({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 pl({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 Lw({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 zw({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 yu({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 fl({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 Ow({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 ju({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 gl({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 ku({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 xl({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 wu({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 Fw={anthropic:{component:Iw,color:"var(--provider-anthropic)"},"claude-cli":{component:wu,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:wu,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},openai:{component:hu,color:"var(--provider-openai)"},"openai-codex":{component:hu,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:Ws,color:"var(--provider-gemini)"},gemini:{component:Ws,color:"var(--provider-gemini)"},"google-antigravity":{component:Ws,color:"var(--provider-gemini)",label:"Google Gemini"},antigravity:{component:Ws,color:"var(--provider-gemini)",label:"Google Gemini"},"google-vertex":{component:Ws,color:"var(--provider-gemini)",label:"Google Vertex AI"},vertex:{component:Ws,color:"var(--provider-gemini)",label:"Google Vertex AI"},"google-cloud-code":{component:Ws,color:"var(--provider-gemini)",label:"Google Cloud Code"},"cloud-code":{component:Ws,color:"var(--provider-gemini)",label:"Google Cloud Code"},"google-gemini-cli":{component:Ws,color:"var(--provider-gemini)",label:"Google Gemini CLI"},"google-generative-ai":{component:Ws,color:"var(--provider-gemini)",label:"Google Generative AI"},ollama:{component:$w,color:"var(--text)"},github:{component:ju,color:"var(--text)"},"github-copilot":{component:ju,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:Ow,color:"var(--provider-openrouter)"},minimax:{component:pu,color:"var(--provider-minimax)"},"minimax-cn":{component:pu,color:"var(--provider-minimax)",label:"MiniMax (CN)"},zai:{component:Dw,color:"var(--provider-zai)"},kimi:{component:ml,color:"var(--provider-kimi)"},moonshot:{component:ml,color:"var(--provider-kimi)"},"kimi-coding":{component:ml,color:"var(--provider-kimi)",label:"Kimi"},bedrock:{component:fu,color:"var(--provider-bedrock)"},"amazon-bedrock":{component:fu,color:"var(--provider-bedrock)",label:"Amazon Bedrock"},xai:{component:gu,color:"var(--text)"},grok:{component:gu,color:"var(--text)",label:"xAI"},opencode:{component:xu,color:"var(--provider-opencode)"},"opencode-go":{component:xu,color:"var(--provider-opencode)",label:"Opencode (Go)"},qwen:{component:Oa,color:"var(--provider-qwen)"},"qwen-ai":{component:Oa,color:"var(--provider-qwen)",label:"Qwen"},"qwen-coder":{component:Oa,color:"var(--provider-qwen)",label:"Qwen Coder"},alibaba:{component:Oa,color:"var(--provider-qwen)",label:"Qwen"},tongyi:{component:Oa,color:"var(--provider-qwen)",label:"Qwen"},lmstudio:{component:bu,color:"var(--provider-lmstudio)",label:"LM Studio"},"lm-studio":{component:bu,color:"var(--provider-lmstudio)",label:"LM Studio"},huggingface:{component:hl,color:"var(--provider-huggingface)",label:"Hugging Face"},"hugging-face":{component:hl,color:"var(--provider-huggingface)",label:"Hugging Face"},hf:{component:hl,color:"var(--provider-huggingface)",label:"Hugging Face"},mistral:{component:vu,color:"var(--provider-mistral)",label:"Mistral AI"},"mistral-ai":{component:vu,color:"var(--provider-mistral)",label:"Mistral AI"},azure:{component:pl,color:"var(--provider-azure)"},"azure-openai":{component:pl,color:"var(--provider-azure)",label:"Azure OpenAI"},"azure-openai-responses":{component:pl,color:"var(--provider-azure)",label:"Azure OpenAI"},fireworks:{component:fl,color:"var(--provider-fireworks)",label:"Fireworks AI"},"fireworks-ai":{component:fl,color:"var(--provider-fireworks)",label:"Fireworks AI"},fireworksai:{component:fl,color:"var(--provider-fireworks)",label:"Fireworks AI"},cerebras:{component:Lw,color:"var(--provider-cerebras)"},groq:{component:zw,color:"var(--provider-groq)"},vercel:{component:yu,color:"var(--provider-vercel)"},"vercel-ai-gateway":{component:yu,color:"var(--provider-vercel)",label:"Vercel AI Gateway"},hermes:{component:gl,color:"var(--provider-hermes)",label:"Hermes"},"hermes-agent":{component:gl,color:"var(--provider-hermes)",label:"Hermes"},hermesagent:{component:gl,color:"var(--provider-hermes)",label:"Hermes"},openclaw:{component:ku,color:"var(--provider-openclaw)",label:"OpenClaw"},"open-claw":{component:ku,color:"var(--provider-openclaw)",label:"OpenClaw"},paperclip:{component:xl,color:"var(--provider-paperclip)",label:"Paperclip"},paperclipai:{component:xl,color:"var(--provider-paperclip)",label:"Paperclip"},"paperclip-ai":{component:xl,color:"var(--provider-paperclip)",label:"Paperclip"}};function Dn({provider:e,size:n="sm"}){const s=e.toLowerCase(),i=Fw[s],r=i?.component,o=i?.color??"var(--text-muted)",l=i?.label,c=Pw[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(ux,{size:c})})}const Es={data:new Map,pendingPromise:null,lastFetchTime:null},Uw=5e3;function uo(e,n){return n?`${n}::${e}`:e}function Bw(e,n){const s=Es.data.get(uo(e,n));if(!(!s||Date.now()-s.timestamp>Uw))return s}function Hw(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 jy(c,e)}catch(h){d=h instanceof Error?h:new Error(String(h));const g=Se(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=Es.data.get(uo(g,e));return p&&p.timestamp>d})&&Es.lastFetchTime&&Es.lastFetchTime>d)return;if(i.current&&(clearTimeout(i.current),i.current=null),Es.pendingPromise){s(!0);try{await Es.pendingPromise}finally{s(!1)}return}s(!0);const h=r(c);Es.pendingPromise=h;try{const g=await h,p=Date.now();for(const[f,x]of Object.entries(g))Es.data.set(uo(f,e),{result:x,timestamp:p});Es.lastFetchTime=p}catch{}finally{Es.pendingPromise=null,s(!1)}},[r,e]),l=a.useCallback(c=>Es.data.get(uo(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:Es.lastFetchTime,getBatchData:l}}const Tc=new Map,qw=3e4;function Mp(e,n,s,i){return`${e}:${n??""}:${s??""}:${i??""}`}function Vw(e,n,s,i){const r=Mp(e,n,s,i),o=Tc.get(r);return o?Date.now()>o.expiresAt?(Tc.delete(r),null):o.stats:null}function Ww(e,n,s,i,r){const o=Mp(e,n,s,i);Tc.set(o,{stats:r,expiresAt:Date.now()+qw})}function Kw(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 A=Vw(e,i,x,v);if(A){b||(m(A),g(!1));return}}g(!0);try{const A=await fp(e,x,i);b||(m(A.stats),Ww(e,i,x,v,A.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 Gw=new Set(["failed","stuck-killed"]);function ko(e,n,s){if(e.column!=="in-progress"||e.status&&Gw.has(e.status)||!n||n<=0)return!1;const i=new Date(e.updatedAt).getTime();return(s??Date.now())-i>n}function Jw(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function Yw(e){return e==="done"||e==="skipped"}function Qw(e,n,s){const i=s?.get(e)?.trim();if(i)return i;const r=n?.workflowStepName?.trim();return r||e}function Ap(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:Qw(u,d,n),status:d?Jw(d.status):"pending",source:"workflow",phase:d?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(u=>Yw(u.status)).length;return{total:l,completed:c,items:o}}function Xw(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 Rp(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:Xw(n)}})}function Zw(e){if(!e||e.length===0)return null;let n=0,s=0;for(const i of Rp(e))typeof i.durationMs=="number"&&(n+=i.durationMs,s+=1);return s>0?n:null}const Pc=new Map;async function eN(e,n){const s=Pc.get(e);if(s)return s;try{const i=await gp(e,n);return Pc.set(e,i.title),i.title}catch{return e}}const Nu=12;function tN(e){return e.length<=Nu?e:e.slice(0,Nu-3)+"..."}const Ic=new Map;async function nN(e,n){const s=Ic.get(e);if(s)return s;try{const i=await hp(e,n);return Ic.set(e,i.name),i.name}catch{return e}}function sN(e){return typeof e=="string"&&cd.includes(e)?e:bs}function iN(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}const aN=new Set(["triage","todo"]),Su=new Set(["planning","researching","executing","finalizing","merging"]),Cu=new Set(["merging","merging-pr"]),rN={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},oN=new Set(["in-progress","in-review","done"]),lN=3e4;function vr(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function cN(e){const n=vr(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function bl(e,n){const s=vr(e.columnMovedAt??e.updatedAt);return s==null?null:Math.max(0,n-s)}function dN(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=vr(o.startedAt);if(l==null)continue;let c;if(o.completedAt){const u=vr(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 Kr(e,n){const s=typeof e.timedExecutionMs=="number"?e.timedExecutionMs:Zw(e.log),i=dN(e,n);return s==null&&i==null?null:(s??0)+(i??0)}function Eu(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 uN(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 _u(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 mN(e,n){return e.length!==n.length?!1:e.every((s,i)=>s.name===n[i]?.name&&s.status===n[i]?.status)}function hN(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function pN(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function fN(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 gN(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 xN(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 bN(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 vN(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&&xN(s.attachments,i.attachments)&&bN(s.comments,i.comments)&&hN(s.dependencies,i.dependencies)&&mN(s.steps,i.steps)&&pN(s.enabledWorkflowSteps,i.enabledWorkflowSteps)&&gN(s.workflowStepResults,i.workflowStepResults)&&_u(s.prInfo,i.prInfo)&&_u(s.issueInfo,i.issueInfo)}function yN({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),[A,w]=a.useState(!1),[E,C]=a.useState(e.description||""),[z,_]=a.useState(!1),[$,F]=a.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(M=>M.status==="done"||M.status==="skipped")),[V,D]=a.useState(null),[T,I]=a.useState(null),[U,Y]=a.useState(!1),[ne,N]=a.useState(!1),[P,R]=a.useState(()=>Date.now()),j=a.useRef(null),W=a.useRef(!1),K=a.useRef(null),ke=a.useRef(null),[be,ce]=a.useState(!1),{badgeUpdates:ve,subscribeToBadge:O,unsubscribeFromBadge:oe}=_p(n),{confirm:te}=Bs(),pe=a.useRef(null),de=a.useRef(!1),ge=a.useCallback(M=>M instanceof Element?!!M.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);a.useEffect(()=>{C(e.description||"")},[e.id,e.description]),a.useEffect(()=>{if(!U)return;const M=ee=>{ke.current&&!ke.current.contains(ee.target)&&Y(!1)};return document.addEventListener("click",M),()=>document.removeEventListener("click",M)},[U]),a.useEffect(()=>{if(!e.missionId){D(null);return}const M=Pc.get(e.missionId);if(M){D(M);return}let ee=!1;return eN(e.missionId,n).then(Oe=>{ee||D(Oe)}),()=>{ee=!0}},[e.missionId,n]),a.useEffect(()=>{if(!e.assignedAgentId){I(null);return}const M=Ic.get(e.assignedAgentId);if(M){I(M);return}I(null);let ee=!1;return nN(e.assignedAgentId,n).then(Oe=>{ee||I(Oe)}),()=>{ee=!0}},[e.assignedAgentId,n]),a.useEffect(()=>{if(A&&j.current){const M=j.current;M.focus(),M.style.height="auto",M.style.height=M.scrollHeight+"px"}},[A]),a.useEffect(()=>{if(typeof IntersectionObserver>"u"){ce(!0);return}const M=K.current;if(!M)return;const ee=new IntersectionObserver(([Oe])=>{ce(Oe?.isIntersecting??!0)},{rootMargin:"200px"});return ee.observe(M),()=>ee.disconnect()},[A,e.id]);const ie=a.useCallback(M=>{M.dataTransfer.setData("text/plain",e.id),M.dataTransfer.effectAllowed="move",y(!0)},[e.id]),Ee=a.useCallback(()=>{y(!1)},[]),Le=a.useCallback(M=>M.dataTransfer.types.includes("Files"),[]),qe=a.useCallback(M=>{Le(M)&&(M.preventDefault(),M.stopPropagation(),M.dataTransfer.dropEffect="copy",k(!0))},[Le]),et=a.useCallback(M=>{Le(M)&&(M.preventDefault(),M.stopPropagation(),k(!1))},[Le]),Xe=a.useCallback(async M=>{if(!Le(M))return;M.preventDefault(),M.stopPropagation(),k(!1);const ee=Array.from(M.dataTransfer.files);for(const Oe of ee)try{await gr(e.id,Oe,n),r(`Attached ${Oe.name} to ${e.id}`,"success")}catch(dt){r(`Failed to attach ${Oe.name}: ${Se(dt)}`,"error")}},[e.id,Le,r]),Ze=a.useCallback(()=>{A||i(e)},[e,i,A]),it=a.useCallback(M=>{if(W.current){W.current=!1;return}ge(M.target)||Ze()},[Ze,ge]),Ie=a.useCallback(M=>{const ee=M.touches[0];ee&&(pe.current={x:ee.clientX,y:ee.clientY,time:Date.now()},de.current=!1)},[]),Ke=a.useCallback(M=>{if(!pe.current)return;const ee=M.touches[0];if(!ee)return;const Oe=Math.abs(ee.clientX-pe.current.x),dt=Math.abs(ee.clientY-pe.current.y);(Oe>Mu||dt>Mu)&&(de.current=!0)},[]),re=a.useCallback(M=>{if(ge(M.target)||!pe.current)return;const Oe=Date.now()-pe.current.time<jN,dt=!de.current;Oe&&dt&&(W.current=!0,Ze()),pe.current=null,de.current=!1},[Ze,ge]),xe=a.useCallback(async(M,ee)=>{M.stopPropagation();try{const Oe=await fr(ee,n);i(Oe)}catch{r(`Failed to load dependency ${ee}`,"error")}},[i,r]),se=e.status==="failed",Ae=e.paused===!0,ze=sN(e.priority),me=ze!==bs,_e=ko(e,g,x),Fe=e.column==="triage"&&e.status==="awaiting-approval",nt=e.column==="archived",we=!o&&!s&&!se&&!Ae&&!_e&&!Fe&&(e.column==="in-progress"||Su.has(e.status)),le=!s&&!Ae&&!A&&!nt,Te=aN.has(e.column)&&!we&&!Ae&&!s&&l,he=!!(e.prInfo||e.issueInfo),Me=!!(e.assignedAgentId&&T===null),We=a.useMemo(()=>{const M=[];return e.modelProvider&&M.push(e.modelProvider),e.validatorModelProvider&&!M.includes(e.validatorModelProvider)&&M.push(e.validatorModelProvider),e.planningModelProvider&&!M.includes(e.planningModelProvider)&&M.push(e.planningModelProvider),M},[e.modelProvider,e.validatorModelProvider,e.planningModelProvider]),Re=a.useMemo(()=>Ap(e,v),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,v]),ut=Re.total>0&&(e.status==="executing"||e.column==="in-progress");a.useEffect(()=>{if(e.column!=="in-progress"&&e.column!=="in-review")return;const M=e.status!=null&&Cu.has(e.status);if(!M&&e.column==="in-progress"){const Oe=bl(e,Date.now()),dt=Kr(e,Date.now());if(Oe==null&&dt==null)return}if(!M&&e.column==="in-review"&&Kr(e,Date.now())==null)return;R(Date.now());const ee=window.setInterval(()=>{R(Date.now())},lN);return()=>window.clearInterval(ee)},[e.column,e.status,e.columnMovedAt,e.updatedAt,e.workflowStepResults,e.timedExecutionMs]);const Q=a.useMemo(()=>{if(!oN.has(e.column))return null;if(e.status!=null&&Cu.has(e.status)){const Nt=vr(e.updatedAt);if(Nt!=null){const Ct=Math.max(0,P-Nt),Rt=Eu(Ct);if(Rt)return{label:Rt,title:`Merging ${Rt}`,ariaLabel:`Merging ${Rt}`}}}if(e.column==="in-progress"){const Nt=bl(e,P)??Kr(e,P);if(Nt==null)return null;const Ct=Eu(Nt);if(!Ct)return null;const Rt=bl(e,P)!=null;return{label:Ct,title:Rt?`In progress ${Ct}`:`Execution time ${Ct}`,ariaLabel:Rt?`In progress ${Ct}`:`Execution time ${Ct}`}}const M=Kr(e,P);if(M==null)return null;const ee=uN(M);if(!ee)return null;const Oe=cN(e);if(Oe==null)return{label:ee,title:`Execution time ${ee}`,ariaLabel:`Execution time ${ee}`};const dt=new Date(Oe).toLocaleString();return{label:ee,title:`Execution time ${ee}. Completed ${dt}`,ariaLabel:`Execution time ${ee}. Completed ${dt}`}},[e.column,e.status,e.columnMovedAt,e.timedExecutionMs,e.updatedAt,e.workflowStepResults,e.log,P]);a.useEffect(()=>{if(!he||!be){oe(e.id);return}return O(e.id),()=>{oe(e.id)}},[he,be,O,e.id,oe]);const ue=ve.get(`${n??"default"}:${e.id}`),ye=e.column==="in-progress"||e.column==="in-review",at=a.useMemo(()=>e.steps.map(M=>`${M.name}:${M.status}`).join("|"),[e.steps]),{stats:X}=Kw(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:be,worktree:e.worktree,stepVersion:ye?at:void 0,pollIntervalMs:ye?3e4:void 0}),Ye=a.useMemo(()=>Bw(e.id,n),[e.id,n]),ot=a.useMemo(()=>{const M=ue?.prInfo,ee=ue?.timestamp,Oe=Ye?.result?.prInfo,dt=Ye?.timestamp?new Date(Ye.timestamp).toISOString():void 0,Nt=e.prInfo,Ct=e.prInfo?.lastCheckedAt??e.updatedAt;let Rt=jo(M,ee,Nt,Ct);const un=ee&&ee>=Ct?ee:Ct;return Oe&&dt&&(!un||dt>un)&&(Rt=Oe),Rt},[ue,Ye,e.prInfo,e.updatedAt]),ht=a.useMemo(()=>{const M=ue?.issueInfo,ee=ue?.timestamp,Oe=Ye?.result?.issueInfo,dt=Ye?.timestamp?new Date(Ye.timestamp).toISOString():void 0,Nt=e.issueInfo,Ct=e.issueInfo?.lastCheckedAt??e.updatedAt;let Rt=jo(M,ee,Nt,Ct);const un=ee&&ee>=Ct?ee:Ct;return Oe&&dt&&(!un||dt>un)&&(Rt=Oe),Rt},[ue,Ye,e.issueInfo,e.updatedAt]),yt=a.useCallback(M=>{M?.stopPropagation(),!(!Te||z)&&(w(!0),C(e.description||""))},[Te,z,e.description]),vt=a.useCallback(()=>{w(!1),C(e.description||"")},[e.description]),pt=a.useCallback(()=>E!==(e.description||""),[E,e.description]),Et=a.useCallback(async()=>{if(!(!l||z)){if(!pt()){vt();return}_(!0);try{await l(e.id,{description:E.trim()||void 0}),r(`Updated ${e.id}`,"success"),w(!1)}catch(M){r(`Failed to update ${e.id}: ${Se(M)}`,"error")}finally{_(!1)}}},[l,e.id,E,z,pt,vt,r]),It=a.useCallback(M=>{M.key==="Enter"&&!M.shiftKey?(M.preventDefault(),Et()):M.key==="Escape"&&(M.preventDefault(),vt())},[Et,vt]),Bt=a.useCallback(()=>{setTimeout(()=>{const M=document.activeElement;M===j.current||M?.closest(".card-editing-content")||(pt()?Et():vt())},0)},[pt,Et,vt]),_t=a.useCallback(M=>{Te&&(M.stopPropagation(),yt(M))},[Te,yt]),Pt=a.useCallback(M=>{M.stopPropagation(),yt(M)},[yt]),$t=a.useCallback(M=>{C(M.target.value);const ee=M.target;ee.style.height="auto",ee.style.height=ee.scrollHeight+"px"},[]),Ht=a.useCallback(M=>{M.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch(ee=>{r(`Failed to archive ${e.id}: ${Se(ee)}`,"error")})},[r,c,e.id]),Gt=a.useCallback(M=>{M.stopPropagation(),u&&u(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch(ee=>{r(`Failed to unarchive ${e.id}: ${Se(ee)}`,"error")})},[r,u,e.id]),Dt=a.useCallback(async M=>{if(M.stopPropagation(),!(!d||!await te({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0})))try{await d(e.id),r(`Deleted ${e.id}`,"success")}catch(Oe){const dt=fN(Oe);if(!dt||dt.dependentIds.length===0){r(`Failed to delete ${e.id}: ${Se(Oe)}`,"error");return}const Nt=dt.dependentIds.join(", ");if(!await te({title:"Force Delete Task",message:`${e.id} is a dependency of ${Nt}.
|
|
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}: ${Se(Rt)}`,"error")}}},[r,te,d,e.id]),Tt=a.useCallback(M=>{M.stopPropagation(),h?.(e,"changes")},[e,h]),jt=a.useCallback(M=>{M.stopPropagation(),F(ee=>!ee)},[]),Mt=a.useCallback(M=>{M.stopPropagation(),e.missionId&&p&&p(e.missionId)},[e.missionId,p]),Zt=a.useCallback(M=>{M.stopPropagation(),Y(ee=>!ee)},[]),At=a.useCallback((M,ee)=>{M.stopPropagation(),Y(!1),f&&f(e.id,ee).then(()=>{r(`Moved ${e.id} to ${Pn[ee]}`,"success")}).catch(Oe=>{r(`Failed to move ${e.id}: ${Se(Oe)}`,"error")})},[r,f,e.id]),H=a.useCallback(async M=>{if(M.stopPropagation(),!(!m||ne)){N(!0);try{await m(e.id)}catch(ee){r(`Failed to retry ${e.id}: ${Se(ee)}`,"error")}finally{N(!1)}}},[r,ne,m,e.id]),fe=`card${b?" dragging":""}${s?" queued":""}${we?" agent-active":""}${se?" failed":""}${Ae?" paused":""}${_e?" stuck":""}${Fe?" awaiting-approval":""}${S?" file-drop-target":""}${A?" card-editing":""}${z?" card-saving":""}`,$e=(()=>{if(e.column==="in-progress"){const M=X?.filesChanged,ee=M==null||M===0?e.modifiedFiles?.length:void 0,Oe=M!=null&&M>0?M:ee;return Oe==null||Oe===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Tt,disabled:!h,children:[t.jsx(Un,{size:12}),t.jsxs("span",{children:[Oe," ",Oe===1?"file":"files"," changed"]})]})}if(e.column==="in-review"){const M=X?.filesChanged,ee=M==null||M===0?e.modifiedFiles?.length:void 0,Oe=M!=null&&M>0?M:ee;return Oe==null||Oe===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Tt,disabled:!h,children:[t.jsx(Un,{size:12}),t.jsxs("span",{children:[Oe," ",Oe===1?"file":"files"," changed"]})]})}if(e.column==="done"){const M=X?.filesChanged,ee=e.mergeDetails?.filesChanged,Oe=M??ee;if(Oe!=null&&Oe>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Tt,disabled:!h,children:[t.jsx(Un,{size:12}),t.jsxs("span",{children:[Oe," ",Oe===1?"file":"files"," changed"]})]});const dt=e.modifiedFiles?.length;if(dt!=null&&dt>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Tt,disabled:!h,children:[t.jsx(Un,{size:12}),t.jsxs("span",{children:[dt," ",dt===1?"file":"files"," changed"]})]})}return null})();return A?t.jsx("div",{ref:K,className:fe,"data-id":e.id,onDoubleClick:_t,children:t.jsxs("div",{className:"card-editing-content",children:[t.jsx("textarea",{ref:j,className:"card-edit-desc-textarea",placeholder:"Task description",value:E,onChange:$t,onKeyDown:It,onBlur:Bt,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:K,className:fe,"data-id":e.id,draggable:le,onDragStart:le?ie:void 0,onDragEnd:le?Ee:void 0,onDragOver:qe,onDragLeave:et,onDrop:Xe,onClick:it,onTouchStart:Ie,onTouchMove:Ke,onTouchEnd:re,onDoubleClick:_t,children:[t.jsxs("div",{className:"card-header",children:[t.jsx("span",{className:"card-id",children:e.id}),Ae&&t.jsx("span",{className:"card-status-badge paused",children:"paused"}),!Ae&&e.status&&e.status!=="queued"&&t.jsx("span",{className:`card-status-badge card-status-badge--${e.column}${Fe?" awaiting-approval":""}${Su.has(e.status)?" pulsing":""}${se?" failed":""}${_e?" stuck":""}`,children:_e?"Stuck":Fe?"Awaiting Approval":e.status}),_e&&(Ae||!e.status||e.status==="queued")&&t.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),he&&t.jsx(Ep,{prInfo:ot,issueInfo:ht}),me&&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:Mt,title:`Mission: ${V??e.missionId}`,role:p?"button":void 0,tabIndex:p?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.jsx(cs,{size:11}),tN(V??e.missionId)]}),t.jsxs("div",{className:"card-header-actions",children:[Te&&t.jsx("button",{className:"card-edit-btn",onClick:Pt,title:"Edit task","aria-label":"Edit task",children:t.jsx(ts,{size:12})}),e.column==="triage"&&d&&t.jsx("button",{className:"card-delete-btn",onClick:Dt,title:"Delete task","aria-label":"Delete task",children:t.jsx(nn,{size:12})}),e.column==="done"&&c&&t.jsx("button",{className:"card-archive-btn",onClick:Ht,title:"Archive task","aria-label":"Archive task",children:"Archive"}),e.column==="archived"&&u&&t.jsx("button",{className:"card-unarchive-btn",onClick:Gt,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),e.column==="in-progress"&&f&&t.jsxs("div",{className:"card-send-back",ref:ke,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:Zt,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":U,children:["Send back",t.jsx(Yt,{size:10})]}),U&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:Rc["in-progress"].filter(M=>M!=="in-review").map(M=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:ee=>At(ee,M),children:Pn[M]},M))})]}),e.column==="in-review"&&f&&t.jsxs("div",{className:"card-send-back",ref:ke,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:Zt,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":U,children:["Move",t.jsx(Yt,{size:10})]}),U&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:Rc["in-review"].map(M=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:ee=>At(ee,M),children:M==="done"?"Done (no merge)":Pn[M]},M))})]}),e.size&&t.jsx("span",{className:`card-size-badge size-${e.size.toLowerCase()}`,children:e.size})]})]}),se&&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:H,disabled:ne,children:[t.jsx(Ib,{size:12}),ne?"Retrying…":"Retry"]})]}),t.jsx("div",{className:"card-title",title:e.title||e.description||void 0,children:Ru(e.title,Au)||Ru(e.description,Au)||e.id}),ut&&(()=>{const M=Re.completed/Re.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:`${M}%`,backgroundColor:rN[e.column]}})}),t.jsxs("span",{className:"card-progress-label",children:[Re.completed,"/",Re.total]})]}),t.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:jt,"aria-expanded":$,"aria-label":$?"Hide steps":"Show steps",children:[t.jsxs("span",{children:[Re.total," step",Re.total===1?"":"s"]}),t.jsx(Yt,{size:14,className:`card-steps-toggle-icon${$?" expanded":""}`})]}),$&&t.jsx("div",{className:"card-steps-list",children:Re.items.map(ee=>{const Oe=ee.source==="workflow"&&ee.status==="failed";return t.jsxs("div",{className:"card-step-item",children:[t.jsx("span",{className:`card-step-dot card-step-dot--${ee.status}${Oe?" card-step-dot--workflow-failed":""}`,"aria-hidden":"true"}),t.jsx("span",{className:`card-step-name${ee.status==="done"?" completed":""}`,children:ee.name}),ee.source==="workflow"&&t.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${ee.phase}`,title:"Workflow check",children:"workflow"})]},ee.id)})})]})})(),($e||Q)&&t.jsxs("div",{className:"card-footer-row",children:[$e,Q&&t.jsxs("span",{className:"card-time-indicator",title:Q.title,"aria-label":Q.ariaLabel,children:[t.jsx(wi,{size:12}),t.jsx("span",{children:Q.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(M=>t.jsxs("span",{className:"card-dep-badge clickable",onClick:ee=>void xe(ee,M),title:`Click to view ${M}`,children:[t.jsx(ga,{size:12,style:{verticalAlign:"middle"}})," ",M]},M))}),e.blockedBy&&t.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${e.blockedBy} (file overlap)`,children:[t.jsx(Bi,{size:12,style:{verticalAlign:"middle"}})," ",e.blockedBy]}),(s||e.status==="queued")&&e.column!=="in-progress"&&t.jsxs("span",{className:"queued-badge",children:[t.jsx(wi,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),(e.assignedAgentId||We.length>0)&&t.jsxs("div",{className:"card-agent-row",children:[We.length>0&&t.jsx("span",{className:"card-provider-icons","data-testid":"card-provider-icons",children:We.map(M=>t.jsx(Dn,{provider:M,size:"sm"},M))}),e.assignedAgentId&&t.jsxs("span",{className:`card-agent-badge${Me?" card-agent-badge--loading":""}`,title:`Assigned to ${T??e.assignedAgentId}`,children:[t.jsx(kn,{size:11}),t.jsx("span",{className:"card-agent-badge-text",children:iN(T??e.assignedAgentId,15)})]})]}),t.jsx(Ho,{slotId:"task-card-badge",projectId:n})]})}const Mu=10,jN=300,Au=140;function Ru(e,n){return e?e.length>n?e.slice(0,n)+"…":e:""}const wo=a.memo(yN,vN);wo.displayName="TaskCard";function kN({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(ix,{size:14}):t.jsx(Xs,{size:14})}),t.jsx("span",{className:"worktree-label",children:e})]}),n.map(f=>t.jsx(wo,{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(wo,{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 Tp=a.memo(kN);Tp.displayName="WorktreeGroup";function Tu(e){return e.toLowerCase().replace(/[-_./]/g,"")}function wN(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 NN(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 SN(e,n){const s=Tu(e),i=Tu(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&&wN(s,o)||s.length>=4&&NN(s,o,1))return!0;return!1}function CN(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=>SN(o,r))})}function Bn({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),[A,w]=a.useState(null),E=a.useRef(null),C=a.useRef(null),z=a.useRef(null),_=a.useRef(null),$=a.useRef(null),F=a.useMemo(()=>CN(e,x),[e,x]),V=a.useMemo(()=>F.reduce((te,pe)=>((te[pe.provider]??=[]).push(pe),te),{}),[F]),D=a.useMemo(()=>{const te=[];for(const pe of d){const de=pe.indexOf("/");if(de===-1)continue;const ge=pe.slice(0,de),ie=pe.slice(de+1),Ee=F.find(Le=>Le.provider===ge&&Le.id===ie);Ee&&te.push({model:Ee,fullId:pe})}return te},[d,F]),T=a.useMemo(()=>{const te=Object.entries(V),pe=new Set(c);return te.sort(([de],[ge])=>{const ie=pe.has(de),Ee=pe.has(ge);if(ie&&!Ee)return-1;if(!ie&&Ee)return 1;if(ie&&Ee){const Le=c.indexOf(de),qe=c.indexOf(ge);if(Le!==qe)return Le-qe}return de.localeCompare(ge)})},[V,c]),I=typeof h=="string"&&h.length>0,U=a.useMemo(()=>{if(!n||I&&n===h)return null;const te=n.indexOf("/");return te===-1?null:n.slice(0,te)},[I,h,n]),Y=a.useMemo(()=>{const te=[];return I&&te.push({type:"no-change",value:h,label:g}),te.push({type:"default",value:"",label:"Use default"}),te},[I,g,h]),ne=a.useMemo(()=>{const te=[...Y];for(const{model:pe,fullId:de}of D)te.push({type:"favorite",value:de,label:pe.name,provider:pe.provider});return T.forEach(([pe,de])=>{te.push({type:"provider",value:`__group_${pe}`,label:pe,provider:pe}),de.forEach(ge=>{te.push({type:"model",value:`${ge.provider}/${ge.id}`,label:ge.name,provider:ge.provider})})}),te},[D,T,Y]),N=a.useMemo(()=>{if(I&&n===h)return g;if(!n)return"Use default";const te=n.indexOf("/");if(te===-1)return n;const pe=n.slice(0,te),de=n.slice(te+1);return e.find(ie=>ie.provider===pe&&ie.id===de)?.name||n},[I,g,h,n,e]),P=a.useMemo(()=>ne.findIndex(te=>te.value===n),[ne,n]),R=a.useCallback(()=>{const te=window.visualViewport;return te&&te.height>0&&te.width>0?{width:te.width,height:te.height,offsetTop:te.offsetTop,offsetLeft:te.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),j=a.useCallback(()=>{const{height:te}=R(),pe=typeof window.matchMedia=="function",de=pe?window.matchMedia("(max-width: 640px)").matches:!1,ge=pe?window.matchMedia("(max-width: 768px)").matches:!1;return te<=0?320:de?Math.min(te*.6,360):ge?Math.min(te*.7,420):320},[R]),W=a.useCallback(()=>{const te=C.current;if(!te)return;const pe=te.getBoundingClientRect(),{width:de,height:ge,offsetTop:ie,offsetLeft:Ee}=R(),Le=16,qe=16,et=4,Xe=j(),Ze=pe.bottom-ie,it=pe.top-ie,Ie=pe.left-Ee,Ke=ge-Ze,re=it,xe=Math.max(Ke-qe-et,160),se=Math.max(re-qe-et,160),Ae=Ke<Xe&&re>Ke,ze=Math.max(Math.min(Ae?se:xe,Xe),160),me=Math.min(pe.width,de-Le*2),_e=Math.min(Math.max(Ie,Le),de-Le-me)+Ee,Fe=Ae?Math.max(qe+ie,it-ze-et+ie):Math.min(Ze+et+ie,ge+ie-qe-ze);k({top:Fe,left:_e,width:me,maxHeight:ze})},[R,j]);a.useEffect(()=>{w(document.body)},[]);const K=a.useRef(!1);a.useEffect(()=>{if(!p){K.current=!1;return}if(K.current||ne.length===0)return;const te=ne.findIndex((pe,de)=>de>=(P>=0?P:0)&&pe.type!=="provider");y(te>=0?te:0),K.current=!0},[p,ne,P]),a.useEffect(()=>{p&&K.current&&(y(0),$.current&&($.current.scrollTop=0))},[x,p]),a.useEffect(()=>{if(!p)return;W();const te=requestAnimationFrame(()=>_.current?.focus());return()=>cancelAnimationFrame(te)},[p,W]),a.useEffect(()=>{if(!p)return;const te=()=>W();window.addEventListener("resize",te),window.addEventListener("scroll",te,!0);const pe=window.visualViewport;return pe&&(pe.addEventListener("resize",te),pe.addEventListener("scroll",te)),()=>{window.removeEventListener("resize",te),window.removeEventListener("scroll",te,!0),pe&&(pe.removeEventListener("resize",te),pe.removeEventListener("scroll",te))}},[p,W]),a.useEffect(()=>{if(!p)return;const te=pe=>{const de=pe.target,ge=E.current?.contains(de),ie=z.current?.contains(de);!ge&&!ie&&(f(!1),v(""))};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[p]);const ke=a.useCallback(te=>{switch(te.key){case"ArrowDown":if(te.preventDefault(),!p)f(!0);else{let pe=b;for(let de=1;de<=ne.length;de++){const ge=(b+de)%ne.length;if(ne[ge]?.type!=="provider"){pe=ge;break}}y(pe)}break;case"ArrowUp":if(te.preventDefault(),p){let pe=b;for(let de=1;de<=ne.length;de++){const ge=(b-de+ne.length)%ne.length;if(ne[ge]?.type!=="provider"){pe=ge;break}}y(pe)}break;case"Enter":if(te.preventDefault(),p){const pe=ne[b];pe&&pe.type!=="provider"&&pe.type!=="favorite"&&(s(pe.value),f(!1),v(""))}else f(!0);break;case"Escape":te.preventDefault(),f(!1),v("");break;case"Tab":p&&(f(!1),v(""));break}},[p,b,ne,s]),be=a.useCallback(te=>{s(te),f(!1),v("")},[s]),ce=a.useCallback(()=>{v(""),_.current?.focus()},[]),ve=a.useCallback(()=>{r||f(te=>!te)},[r]);a.useEffect(()=>{if(p&&$.current){const te=$.current.querySelector(`[data-index="${b}"]`);te&&typeof te.scrollIntoView=="function"&&te.scrollIntoView({block:"nearest"})}},[b,p]);const O=x.length>0,oe=p&&S?t.jsxs("div",{ref:z,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:ke,style:{top:`${S.top}px`,left:`${S.left}px`,width:`${S.width}px`,maxHeight:`${S.maxHeight}px`},children:[t.jsxs("div",{className:"model-combobox-search-wrapper",children:[t.jsx("input",{ref:_,type:"text",className:"model-combobox-search",placeholder:"Filter models…",value:x,onChange:te=>v(te.target.value),onClick:te=>te.stopPropagation()}),O&&t.jsx("button",{type:"button",className:"model-combobox-clear",onClick:ce,"aria-label":"Clear filter",children:"×"})]}),t.jsxs("div",{className:"model-combobox-results-count",children:[F.length," model",F.length!==1?"s":""]}),t.jsxs("div",{ref:$,className:"model-combobox-list",children:[Y.map((te,pe)=>t.jsx("div",{"data-index":pe,className:`model-combobox-option ${b===pe?"model-combobox-option--highlighted":""} ${n===te.value?"model-combobox-option--selected":""}`,onClick:()=>be(te.value),onMouseEnter:()=>y(pe),role:"option","aria-selected":n===te.value,children:t.jsx("span",{className:"model-combobox-option-text model-combobox-option-text--default",children:te.label})},`${te.type}-${te.value}`)),D.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"model-combobox-divider"}),D.map(({model:te,fullId:pe},de)=>{const ge=de+Y.length,ie=b===ge,Ee=n===pe;return t.jsxs("div",{"data-index":ge,className:`model-combobox-option model-combobox-option--favorite ${ie?"model-combobox-option--highlighted":""} ${Ee?"model-combobox-option--selected":""}`,onClick:()=>be(pe),onMouseEnter:()=>y(ge),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(Dn,{provider:te.provider,size:"sm"})}),t.jsx("span",{className:"model-combobox-option-text",children:te.name})]}),t.jsx("span",{className:"model-combobox-option-id",children:te.id}),m&&t.jsx("button",{type:"button",className:"model-combobox-option-favorite model-combobox-option-favorite--active",onClick:Le=>{Le.stopPropagation(),m(pe)},title:"Remove from favorites","aria-label":`Remove ${te.name} from favorites`,children:"★"})]},pe)}),t.jsx("div",{className:"model-combobox-divider"})]}),T.map(([te,pe])=>{const de=ne.findIndex(Ee=>Ee.value===`__group_${te}`),ge=c.includes(te),ie=pe.filter(Ee=>{const Le=`${Ee.provider}/${Ee.id}`;return!d.includes(Le)});return ie.length===0?null:t.jsxs("div",{className:"model-combobox-group",children:[t.jsxs("div",{className:"model-combobox-optgroup","data-index":de,children:[t.jsx(Dn,{provider:te,size:"sm"}),t.jsx("span",{className:"model-combobox-optgroup-text",children:te}),u&&t.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${ge?"model-combobox-optgroup-favorite--active":""}`,onClick:Ee=>{Ee.stopPropagation(),u(te)},title:ge?"Remove from favorites":"Add to favorites","aria-label":ge?`Remove ${te} from favorites`:`Add ${te} to favorites`,children:"★"})]}),ie.map(Ee=>{const Le=`${Ee.provider}/${Ee.id}`,qe=ne.findIndex(it=>it.value===Le),et=b===qe,Xe=n===Le,Ze=d.includes(Le);return t.jsxs("div",{"data-index":qe,className:`model-combobox-option ${et?"model-combobox-option--highlighted":""} ${Xe?"model-combobox-option--selected":""}`,onClick:()=>be(Le),onMouseEnter:()=>y(qe),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 ${Ze?"model-combobox-option-favorite--active":""}`,onClick:it=>{it.stopPropagation(),m(Le)},title:Ze?"Remove from favorites":"Add to favorites","aria-label":Ze?`Remove ${Ee.name} from favorites`:`Add ${Ee.name} to favorites`,children:Ze?"★":"☆"})]},Le)})]},te)}),F.length===0&&O&&t.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",x,"'"]})]})]}):null;return t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:E,className:"model-combobox",onKeyDown:ke,children:t.jsxs("button",{ref:C,type:"button",id:o,className:"model-combobox-trigger",onClick:ve,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":l,children:[U&&t.jsx("span",{className:"model-combobox-trigger-icon",children:t.jsx(Dn,{provider:U,size:"sm"})}),t.jsx("span",{className:"model-combobox-trigger-text",children:N||i}),t.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),A&&oe?da.createPortal(oe,A):null]})}function dd(e,n){return typeof n!="string"||n.length===0?e:`kb:${n}:${e}`}function Hn(e,n){return typeof window>"u"?null:window.localStorage.getItem(dd(e,n))}function ls(e,n,s){typeof window>"u"||window.localStorage.setItem(dd(e,s),n)}function yr(e,n){typeof window>"u"||window.localStorage.removeItem(dd(e,n))}const EN=1e4,_N=1e3;function Vo(){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 yo();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 yo();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<_N||(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()},EN),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async p=>{const f=await Dj(p);return n(x=>[...x,f]),f},[]),m=a.useCallback(async(p,f)=>{const x=await Lj(p,f);return n(v=>v.map(b=>b.id===p?x:b)),x},[]),h=a.useCallback(async p=>{await zj(p),n(f=>f.filter(x=>x.id!==p))},[]),g=a.useCallback(async p=>{const f=await Oj(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 Fa="kb-quick-entry-text",MN=["image/png","image/jpeg","image/gif","image/webp"];function AN(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function vl(e,n){return e&&n?`${e}/${n}`:""}function yl(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 Pp({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"&&Hn(Fa,l)||""),[f,x]=a.useState(!1),[v,b]=a.useState(!1),[y,S]=a.useState(!1),k=a.useRef(null),A=a.useRef(null),w=a.useRef(!1),E=a.useRef(l),[C,z]=a.useState([]),_=a.useRef([]),[$,F]=a.useState([]),[V,D]=a.useState(!1),[T,I]=a.useState(""),[U,Y]=a.useState(null),[ne,N]=a.useState([]),[P,R]=a.useState(void 0),[j,W]=a.useState(!1),[K,ke]=a.useState(!1),[be,ce]=a.useState(!1),[ve,O]=a.useState(!1),[oe,te]=a.useState(null),[pe,de]=a.useState(void 0),[ge,ie]=a.useState(void 0),[Ee,Le]=a.useState(void 0),[qe,et]=a.useState(void 0),[Xe,Ze]=a.useState(void 0),[it,Ie]=a.useState(void 0),Ke=a.useRef(null),re=a.useRef(null),xe=a.useRef(null),se=a.useRef(null),Ae=a.useRef(null),ze=a.useRef(null),[me,_e]=a.useState(null),[Fe,nt]=a.useState(null),[we,le]=a.useState(null),Te=a.useRef(null),he=a.useRef(null),[Me,We]=a.useState(null),[Re]=a.useState(()=>typeof document<"u"?document.body:null),[ut,Q]=a.useState(!1),[ue,ye]=a.useState(null),[at,X]=a.useState(i??[]),[Ye,ot]=a.useState([]),[ht,yt]=a.useState([]),[vt,pt]=a.useState(null),[Et,It]=a.useState(void 0),[Bt,_t]=a.useState(!1),[Pt,$t]=a.useState(void 0),{nodes:Ht}=Vo(),[Gt,Dt]=a.useState(!1),[Tt,jt]=a.useState(!1),Mt=a.useRef(null),Zt=a.useRef(null),[At,H]=a.useState(null),fe=u??Ye,$e=d??ht,M=!e;a.useEffect(()=>{if(i)X(i),Q(!1),ye(null);else{let q=!1;return Q(!0),ye(null),ds().then(je=>{q||(X(je.models),u||ot(je.favoriteProviders),d||yt(je.favoriteModels))}).catch(je=>{q||ye(Se(je)||"Failed to load models")}).finally(()=>{q||Q(!1)}),Fo(l).then(je=>{q||pt(je)}).catch(()=>{}),()=>{q=!0}}},[i,u,d,l]);const ee=vl(pe,ge),Oe=vl(Ee,qe),dt=vl(Xe,it),Nt=!!(pe&&ge),Ct=!!(Ee&&qe),Rt=!!(Xe&&it),un=Number(Nt)+Number(Ct)+Number(Rt),mn=Et?vt?.modelPresets?.find(q=>q.id===Et)?.name??"Models":un>0?`${un} model${un===1?"":"s"}`:"Models",Nn=a.useCallback((q,je)=>{if(!q||!je)return"Using default";const Je=at.find(bt=>bt.provider===q&&bt.id===je);return Je?`${Je.provider}/${Je.id}`:`${q}/${je}`},[at]);a.useEffect(()=>{p(Hn(Fa,l)||"")},[l]),a.useEffect(()=>{typeof window<"u"&&ls(Fa,g,l)},[g,l]),a.useEffect(()=>{E.current!==l&&(E.current=l,N([]),R(void 0),Y(null),W(!1),_e(null))},[l]),a.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),a.useEffect(()=>{_.current=C},[C]),a.useEffect(()=>()=>{_.current.forEach(q=>URL.revokeObjectURL(q.previewUrl))},[]);const Qt=a.useCallback(()=>{const q=k.current;if(!q)return;q.style.height="auto";const je=Math.min(q.scrollHeight,200);q.style.height=`${je}px`},[]);a.useEffect(()=>{v&&Qt()},[g,v,Qt]),a.useEffect(()=>{if(!f&&g===""&&k.current){const q=setTimeout(()=>{k.current?.focus()},0);return()=>clearTimeout(q)}},[f,g]),a.useEffect(()=>{V||I("")},[V]),a.useEffect(()=>{if(!Gt)return;const q=je=>{const Je=je.target,bt=Mt.current?.contains(Je),gt=Zt.current?.contains(Je);!bt&&!gt&&Dt(!1)};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[Gt]),a.useEffect(()=>{if(!ve)return;const q=je=>{const Je=je.target,bt=Ke.current?.contains(Je),gt=re.current?.contains(Je),yn=Je instanceof Element&&Je.closest?.(".model-combobox-dropdown--portal")!=null;!bt&&!gt&&!yn&&(O(!1),te(null))};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[ve]),a.useEffect(()=>{if(!K)return;const q=je=>{const Je=je.target;Ae.current?.contains(Je)||ze.current?.contains(Je)||(ke(!1),nt(null))};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[K]),a.useEffect(()=>{if(!j)return;const q=je=>{const Je=je.target;xe.current?.contains(Je)||se.current?.contains(Je)||(W(!1),_e(null))};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[j]);const An=a.useCallback(()=>{C.forEach(q=>URL.revokeObjectURL(q.previewUrl)),z([]),A.current&&(A.current.value=""),p(""),F([]),Y(null),W(!1),_e(null),ke(!1),nt(null),de(void 0),ie(void 0),Le(void 0),et(void 0),Ze(void 0),Ie(void 0),It(void 0),_t(!1),$t(void 0),D(!1),O(!1),le(null),te(null),Dt(!1),jt(!1),b(!1),S(!1),w.current=!0,k.current&&(k.current.style.height="auto"),typeof window<"u"&&yr(Fa,l)},[C,l]),Ne=a.useCallback(q=>{if(!q||q.length===0)return;const je=[];for(let Je=0;Je<q.length;Je++){const bt=q[Je];MN.includes(bt.type)&&je.push({file:bt,previewUrl:URL.createObjectURL(bt)})}je.length>0&&z(Je=>[...Je,...je])},[]),ae=a.useCallback(q=>{f||Ne(q.clipboardData?.files)},[Ne,f]),Ge=a.useCallback(q=>{z(je=>{const Je=je[q];return Je&&URL.revokeObjectURL(Je.previewUrl),je.filter((bt,gt)=>gt!==q)})},[]),ct=a.useCallback(async()=>{const q=g.trim();if(!q||f||!e)return;const je=g;x(!0),p("");try{const Je=await e({description:q,column:"triage",dependencies:$.length?$:void 0,...U?{assignedAgentId:U}:{},modelPresetId:Et,modelProvider:Nt?pe:void 0,modelId:Nt?ge:void 0,validatorModelProvider:Ct?Ee:void 0,validatorModelId:Ct?qe:void 0,planningModelProvider:Rt?Xe:void 0,planningModelId:Rt?it:void 0,...Bt?{executionMode:"fast"}:{},nodeId:Pt});if(Je&&C.length>0){const bt=[];for(const gt of C)try{await gr(Je.id,gt.file,l)}catch{bt.push(gt.file.name)}bt.length>0&&n(`Failed to upload: ${bt.join(", ")}`,"error")}An()}catch(Je){p(je),n(Se(Je)||"Failed to create task","error")}finally{x(!1)}},[g,f,e,$,U,Nt,pe,ge,Ct,Ee,qe,Rt,Xe,it,C,l,n,An,Bt,Pt]),Lt=a.useCallback(q=>{if(q.key==="Enter"){if(q.shiftKey&&v)return;q.preventDefault(),ct()}else if(q.key==="Escape"){if(q.preventDefault(),oe){te(null);return}if(ve){O(!1),le(null);return}if(V){D(!1);return}if(Gt){Dt(!1);return}if(K){ke(!1),nt(null);return}if(j){W(!1),_e(null);return}g.trim()&&(p(""),k.current&&(k.current.style.height="auto"),typeof window<"u"&&yr(Fa,l)),b(!1),S(!1),k.current?.blur()}},[ct,g,v,V,j,K,ve,oe,Gt,l,S]),qt=a.useCallback(()=>{w.current&&(w.current=!1)},[]),En=a.useCallback(()=>{c&&b(!0)},[c]),hn=a.useCallback(q=>{F(je=>je.includes(q)?je.filter(Je=>Je!==q):[...je,q])},[]),Vt=a.useCallback(()=>{const q=window.visualViewport;return q&&q.width>0&&q.height>0?{width:q.width,height:q.height,offsetTop:q.offsetTop,offsetLeft:q.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),J=a.useCallback(()=>{const q=Ke.current;if(!q)return;const je=q.getBoundingClientRect(),{width:Je,height:bt,offsetTop:gt,offsetLeft:yn}=Vt(),en=16,rn=16,pn=4,In=Je<=768,qn=Math.min(In?bt*.6:bt*.5,360),Vn=In?Math.min(Je-en*2,360):Math.max(je.width,240),_n=Math.min(Vn,Math.max(Je-en*2,200)),Wn=je.top-gt,Ln=je.bottom-gt,hs=je.left-yn,jn=bt-Ln,zn=Wn,rs=Math.max(jn-rn-pn,160),ws=Math.max(zn-rn-pn,160),Zn=jn<qn&&zn>jn,on=Math.max(Math.min(Zn?ws:rs,qn),160),On=Math.min(Math.max(hs,en),Je-en-_n)+yn,Ds=Zn?Math.max(rn+gt,Wn-on-pn+gt):Math.min(Ln+pn+gt,bt+gt-rn-on);le({top:Ds,left:On,width:_n,maxHeight:on})},[Vt]),Pe=a.useCallback(()=>{const q=Mt.current?.querySelector(".refine-button");if(!q)return;const je=q.getBoundingClientRect(),{width:Je,height:bt,offsetTop:gt,offsetLeft:yn}=Vt(),en=8,rn=12,pn=4,In=Math.min(200,Math.max(bt-rn*2,160)),qn=Math.min(200,Je-en*2),Vn=je.top-gt,_n=je.bottom-gt,Wn=je.left-yn,Ln=bt-_n,hs=Vn,jn=Ln<In&&hs>Ln,zn=Math.min(Math.max(Wn,en),Je-en-qn)+yn,rs=jn?Math.max(rn+gt,Vn-In-pn+gt):Math.min(_n+pn+gt,bt+gt-rn-In);H({top:rs,left:zn})},[Vt]),Qe=a.useCallback(()=>{const q=Te.current;if(!q)return;const je=q.getBoundingClientRect(),{width:Je,height:bt,offsetTop:gt,offsetLeft:yn}=Vt(),en=16,rn=16,pn=4,In=Je<=768,qn=Math.min(In?bt*.6:bt*.5,320),Vn=In?Math.min(Je-en*2,360):Math.max(je.width,280),_n=Math.min(Vn,Math.max(Je-en*2,240)),Wn=je.top-gt,Ln=je.bottom-gt,hs=je.left-yn,jn=bt-Ln,zn=Wn,rs=Math.max(jn-rn-pn,200),ws=Math.max(zn-rn-pn,200),Zn=jn<qn&&zn>jn,on=Math.max(Math.min(Zn?ws:rs,qn),200),On=Math.min(Math.max(hs,en),Je-en-_n)+yn,Ds=Zn?Math.max(rn+gt,Wn-on-pn+gt):Math.min(Ln+pn+gt,bt+gt-rn-on);We({top:Ds,left:On,width:_n,maxHeight:on})},[Vt]),tt=a.useCallback(()=>{const q=xe.current?.querySelector("button");if(!q)return;const je=q.getBoundingClientRect(),{width:Je,height:bt,offsetTop:gt,offsetLeft:yn}=Vt(),en=16,rn=16,pn=4,In=Je<=768,qn=Math.min(In?bt*.6:bt*.5,320),Vn=In?Math.min(Je-en*2,280):Math.max(je.width,240),_n=Math.min(Vn,Math.max(Je-en*2,200)),Wn=je.top-gt,Ln=je.bottom-gt,hs=je.left-yn,jn=bt-Ln,zn=Wn,rs=Math.max(jn-rn-pn,160),ws=Math.max(zn-rn-pn,160),Zn=jn<qn&&zn>jn,on=Math.max(Math.min(Zn?ws:rs,qn),160),On=Math.min(Math.max(hs,en),Je-en-_n)+yn,Ds=Zn?Math.max(rn+gt,Wn-on-pn+gt):Math.min(Ln+pn+gt,bt+gt-rn-on);_e({top:Ds,left:On,width:_n,maxHeight:on})},[Vt]),mt=a.useCallback(()=>{const q=Ae.current?.querySelector("button");if(!q)return;const je=q.getBoundingClientRect(),{width:Je,height:bt,offsetTop:gt,offsetLeft:yn}=Vt(),en=16,rn=16,pn=4,In=Je<=768,qn=Math.min(In?bt*.6:bt*.5,320),Vn=In?Math.min(Je-en*2,280):Math.max(je.width,240),_n=Math.min(Vn,Math.max(Je-en*2,200)),Wn=je.top-gt,Ln=je.bottom-gt,hs=je.left-yn,jn=bt-Ln,zn=Wn,rs=Math.max(jn-rn-pn,160),ws=Math.max(zn-rn-pn,160),Zn=jn<qn&&zn>jn,on=Math.max(Math.min(Zn?ws:rs,qn),160),On=Math.min(Math.max(hs,en),Je-en-_n)+yn,Ds=Zn?Math.max(rn+gt,Wn-on-pn+gt):Math.min(Ln+pn+gt,bt+gt-rn-on);nt({top:Ds,left:On,width:_n,maxHeight:on})},[Vt]);a.useEffect(()=>{if(!ve)return;const q=()=>J();window.addEventListener("resize",q),window.addEventListener("scroll",q,!0);const je=window.visualViewport;return je&&(je.addEventListener("resize",q),je.addEventListener("scroll",q)),()=>{window.removeEventListener("resize",q),window.removeEventListener("scroll",q,!0),je&&(je.removeEventListener("resize",q),je.removeEventListener("scroll",q))}},[ve,J]),a.useEffect(()=>{if(!Gt)return;const q=()=>Pe();window.addEventListener("resize",q),window.addEventListener("scroll",q,!0);const je=window.visualViewport;return je&&(je.addEventListener("resize",q),je.addEventListener("scroll",q)),()=>{window.removeEventListener("resize",q),window.removeEventListener("scroll",q,!0),je&&(je.removeEventListener("resize",q),je.removeEventListener("scroll",q))}},[Gt,Pe]),a.useEffect(()=>{if(!V)return;const q=()=>Qe();window.addEventListener("resize",q),window.addEventListener("scroll",q,!0);const je=window.visualViewport;return je&&(je.addEventListener("resize",q),je.addEventListener("scroll",q)),()=>{window.removeEventListener("resize",q),window.removeEventListener("scroll",q,!0),je&&(je.removeEventListener("resize",q),je.removeEventListener("scroll",q))}},[V,Qe]),a.useEffect(()=>{if(!j)return;const q=()=>tt();window.addEventListener("resize",q),window.addEventListener("scroll",q,!0);const je=window.visualViewport;return je&&(je.addEventListener("resize",q),je.addEventListener("scroll",q)),()=>{window.removeEventListener("resize",q),window.removeEventListener("scroll",q,!0),je&&(je.removeEventListener("resize",q),je.removeEventListener("scroll",q))}},[j,tt]),a.useEffect(()=>{if(!K)return;const q=()=>mt();window.addEventListener("resize",q),window.addEventListener("scroll",q,!0);const je=window.visualViewport;return je&&(je.addEventListener("resize",q),je.addEventListener("scroll",q)),()=>{window.removeEventListener("resize",q),window.removeEventListener("scroll",q,!0),je&&(je.removeEventListener("resize",q),je.removeEventListener("scroll",q))}},[K,mt]);const St=a.useCallback(q=>{const je=yl(q);Ze(je.provider),Ie(je.modelId)},[]),zt=a.useCallback(q=>{const je=yl(q);de(je.provider),ie(je.modelId)},[]),Sn=a.useCallback(q=>{const je=yl(q);Le(je.provider),et(je.modelId)},[]),an=a.useCallback(async q=>{if(m){m(q);return}const je=Ye,bt=je.includes(q)?je.filter(gt=>gt!==q):[q,...je];ot(bt);try{await cn({favoriteProviders:bt,favoriteModels:ht})}catch{ot(je)}},[Ye,ht,m]),kt=a.useCallback(async q=>{if(h){h(q);return}const je=ht,bt=je.includes(q)?je.filter(gt=>gt!==q):[q,...je];yt(bt);try{await cn({favoriteProviders:Ye,favoriteModels:bt})}catch{yt(je)}},[ht,Ye,h]),as=a.useCallback(()=>{const q=g.trim();if(!q){n("Enter a description first","error");return}r?.(q),An()},[g,r,n,An]),js=a.useCallback(()=>{const q=g.trim();if(!q){n("Enter a description first","error");return}o?.(q),An()},[g,o,n,An]),Ps=a.useCallback(()=>{ct()},[ct]),Is=a.useCallback(async q=>{const je=g.trim();if(!(!je||Tt)){Dt(!1),jt(!0);try{const Je=await dp(je,q,l);p(Je),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(Je){const bt=up(Je);n(bt,"error")}finally{jt(!1)}}},[g,Tt,n,l]),si=(q,je)=>q.length>je?q.slice(0,je)+"…":q,ks=a.useCallback(async()=>{if(i){X(i),ye(null),Q(!1);return}Q(!0),ye(null);try{const q=await ds();X(q.models),u||ot(q.favoriteProviders),d||yt(q.favoriteModels)}catch(q){ye(Se(q)||"Failed to load models")}finally{Q(!1)}},[i,u,d]),$s=a.useCallback(async()=>{if(ne.length>0&&P===l){W(!0),tt();return}ce(!0);try{const q=await Ma(void 0,l);N(q),R(l),W(!0),tt()}catch(q){const je=Se(q);n(je?`Failed to load agents: ${je}`:"Failed to load agents","error"),W(!1)}finally{ce(!1)}},[ne.length,P,l,n,tt]),gi=(U?ne.find(q=>q.id===U):void 0)?.name??U,ii=Pt?Ht.find(q=>q.id===Pt):void 0,ms=y,qs=a.useCallback(()=>{S(q=>{const je=!q;return b(je),je})},[]);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:q=>p(q.target.value),onKeyDown:Lt,onPaste:ae,onFocus:En,onBlur:qt,disabled:f||M,"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:qs,"aria-expanded":y,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:y?"Collapse":"Expand",children:y?t.jsx(ui,{size:14}):t.jsx(Yt,{size:14})})]})}),t.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!ms,"aria-hidden":!ms,children:[ms&&!f&&t.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:as,onMouseDown:q=>q.preventDefault(),disabled:!g.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[t.jsx(Zs,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:js,onMouseDown:q=>q.preventDefault(),disabled:!g.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[t.jsx(Do,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),t.jsxs("div",{className:"refine-trigger-wrap",ref:Mt,children:[t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${Tt?"refine-button--loading":""}`,onClick:()=>{Dt(q=>{const je=!q;return je?Pe():H(null),je})},disabled:!g.trim()||Tt,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(Qn,{size:12,style:{verticalAlign:"middle"}}),Tt?"Refining...":"Refine"]}),Gt&&Re&&At&&da.createPortal(t.jsxs("div",{ref:Zt,className:"refine-menu refine-menu--portal",onMouseDown:q=>q.preventDefault(),style:{position:"fixed",top:`${At.top}px`,left:`${At.left}px`},children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>Is("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:()=>Is("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:()=>Is("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:()=>Is("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"})]})]}),Re)]}),t.jsx("div",{className:"dep-trigger-wrap",children:t.jsxs("button",{ref:Te,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{D(q=>{const je=!q;return je?(O(!1),le(null),te(null),W(!1),_e(null),ke(!1),nt(null),Qe()):We(null),je})},children:[t.jsx(ga,{size:12,style:{verticalAlign:"middle"}}),$.length>0?`${$.length} deps`:"Deps"]})}),V&&Re&&Me&&(()=>{const q=T.toLowerCase(),je=(q?s.filter(Je=>Je.id.toLowerCase().includes(q)||Je.title&&Je.title.toLowerCase().includes(q)||Je.description&&Je.description.toLowerCase().includes(q)):[...s]).sort((Je,bt)=>{const gt=bt.createdAt.localeCompare(Je.createdAt);if(gt!==0)return gt;const yn=parseInt(Je.id.slice(Je.id.lastIndexOf("-")+1),10)||0;return(parseInt(bt.id.slice(bt.id.lastIndexOf("-")+1),10)||0)-yn});return da.createPortal(t.jsxs("div",{ref:he,className:"dep-dropdown dep-dropdown--portal",onMouseDown:Je=>Je.preventDefault(),style:{position:"fixed",top:`${Me.top}px`,left:`${Me.left}px`,width:`${Me.width}px`,maxHeight:Me.maxHeight?`${Me.maxHeight}px`:void 0,overflowY:Me.maxHeight?"auto":void 0},children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:T,onChange:Je=>I(Je.target.value),onClick:Je=>Je.stopPropagation()}),je.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):je.map(Je=>t.jsxs("div",{className:`dep-dropdown-item${$.includes(Je.id)?" selected":""}`,onMouseDown:bt=>bt.preventDefault(),onClick:()=>hn(Je.id),children:[t.jsx("span",{className:"dep-dropdown-id",children:Je.id}),t.jsx("span",{className:"dep-dropdown-title",children:si(Je.title||Je.description||Je.id,60)})]},Je.id))]}),Re)})(),t.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>A.current?.click(),children:[t.jsx(Xh,{size:12,style:{verticalAlign:"middle"}}),C.length>0?`Attach (${C.length})`:"Attach"]}),t.jsxs("button",{ref:Ke,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{D(!1),W(!1),_e(null),ke(!1),nt(null),te(null),O(!0),J()},children:[t.jsx(fo,{size:12,style:{verticalAlign:"middle"}}),mn]}),t.jsx("div",{className:"node-trigger-wrap",ref:Ae,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-node-button",onClick:()=>{D(!1),W(!1),_e(null),O(!1),le(null),te(null),ke(q=>{const je=!q;return je?mt():nt(null),je})},children:[t.jsx(pr,{size:12,style:{verticalAlign:"middle"}}),` ${ii?.name??"Node"}`,ii&&t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(qi,{status:ii.status,showLabel:!0})})]})}),K&&Re&&Fe&&da.createPortal(t.jsxs("div",{ref:ze,className:"dep-dropdown node-picker-dropdown node-picker-dropdown--portal",onMouseDown:q=>q.preventDefault(),style:{position:"fixed",top:`${Fe.top}px`,left:`${Fe.left}px`,width:`${Fe.width}px`,maxHeight:Fe.maxHeight?`${Fe.maxHeight}px`:void 0,overflowY:Fe.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select execution node"}),t.jsx("div",{className:`dep-dropdown-item node-picker-item${Pt==null?" selected":""}`,onMouseDown:q=>q.preventDefault(),onClick:()=>{$t(void 0),ke(!1),nt(null)},children:t.jsx("span",{className:"node-picker-item-name",children:"Project default / local"})}),Ht.map(q=>t.jsxs("div",{className:`dep-dropdown-item node-picker-item${Pt===q.id?" selected":""}`,onMouseDown:je=>je.preventDefault(),onClick:()=>{$t(q.id),ke(!1),nt(null)},children:[t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(qi,{status:q.status})}),t.jsx("span",{className:"node-picker-item-name",children:q.name}),t.jsx("span",{className:"node-picker-item-status",children:AN(q.status)})]},q.id))]}),Re),t.jsx("div",{className:"agent-trigger-wrap",ref:xe,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{j?(W(!1),_e(null)):(ke(!1),nt(null),$s())},"data-testid":"quick-entry-agent-button",children:[t.jsx(kn,{size:12,style:{verticalAlign:"middle"}}),gi?` ${gi}`:" Agent"]})}),j&&Re&&me&&da.createPortal(t.jsxs("div",{ref:se,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:q=>q.preventDefault(),style:{position:"fixed",top:`${me.top}px`,left:`${me.left}px`,width:`${me.width}px`,maxHeight:me.maxHeight?`${me.maxHeight}px`:void 0,overflowY:me.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),be&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!be&&ne.filter(q=>q.state!=="terminated").map(q=>t.jsxs("div",{className:`dep-dropdown-item${U===q.id?" selected":""}`,onMouseDown:je=>je.preventDefault(),onClick:()=>{Y(q.id===U?null:q.id),W(!1),_e(null)},children:[t.jsx(kn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:q.role}),t.jsx("span",{className:"dep-dropdown-title",children:q.name})]},q.id)),!be&&ne.filter(q=>q.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),U&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:q=>q.preventDefault(),onClick:()=>{Y(null),W(!1),_e(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),Re),t.jsx("button",{type:"button",className:`btn btn-sm ${Bt?"btn-primary":""}`,onClick:()=>_t(q=>!q),onMouseDown:q=>q.preventDefault(),"aria-pressed":Bt,"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:Ps,onMouseDown:q=>q.preventDefault(),disabled:!g.trim()||f,"data-testid":"quick-entry-save",title:"Create task",children:[t.jsx(ep,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),C.length>0&&t.jsx("div",{className:"inline-create-previews",children:C.map((q,je)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:q.previewUrl,alt:q.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>Ge(je),disabled:f,title:"Remove image","data-testid":`quick-entry-preview-remove-${je}`,children:"×"})]},q.previewUrl))}),ve&&Re&&we&&da.createPortal(t.jsx("div",{ref:re,className:"model-nested-menu model-nested-menu--portal",onMouseDown:q=>q.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${we.top}px`,left:`${we.left}px`,width:`${we.width}px`,maxHeight:we.maxHeight?`${we.maxHeight}px`:void 0,overflowY:we.maxHeight?"auto":void 0},children:oe===null?t.jsxs("div",{className:"model-menu-items",children:[t.jsxs("button",{type:"button",className:`model-menu-item ${Rt?"model-menu-item--active":""}`,onClick:()=>te("plan"),"data-testid":"model-menu-plan",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Zs,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),t.jsx("span",{className:"model-menu-item-value",children:Rt?Nn(Xe,it):"Using default"}),t.jsx(bn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${Nt?"model-menu-item--active":""}`,onClick:()=>te("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:Nt?Nn(pe,ge):"Using default"}),t.jsx(bn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${Ct?"model-menu-item--active":""}`,onClick:()=>te("validator"),"data-testid":"model-menu-validator",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(fo,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Reviewer"]}),t.jsx("span",{className:"model-menu-item-value",children:Ct?Nn(Ee,qe):"Using default"}),t.jsx(bn,{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:()=>te(null),"data-testid":"model-submenu-back",children:[t.jsx(Yt,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),t.jsxs("div",{className:"model-submenu-header",children:[oe==="plan"&&"Plan Model",oe==="executor"&&"Executor Model",oe==="validator"&&"Reviewer Model"]}),t.jsx(Bn,{models:at,value:oe==="plan"?dt:oe==="executor"?ee:Oe,onChange:oe==="plan"?St:oe==="executor"?zt:Sn,placeholder:"Using default",disabled:ut,id:`model-${oe}-select`,label:`${oe} model`,favoriteProviders:fe,onToggleFavorite:an,favoriteModels:$e,onToggleModelFavorite:kt}),ue&&t.jsxs("div",{className:"model-submenu-error",children:[t.jsx("span",{children:ue}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:ks,children:"Retry"})]})]})}),Re)]}),t.jsx("input",{ref:A,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:q=>{Ne(q.target.files),q.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),t.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function RN(e){return ld(e)||e}function TN(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 PN(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=TN(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:RN(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 Pu=100,jl=50,Iu=25;function IN({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:A,availableModels:w,onPlanningMode:E,onSubtaskBreakdown:C,onOpenDetailWithTab:z,favoriteProviders:_,favoriteModels:$,onToggleFavorite:F,onToggleModelFavorite:V,isSearchActive:D,taskStuckTimeoutMs:T,onOpenMission:I,lastFetchTimeMs:U,workflowStepNameLookup:Y}){const[ne,N]=a.useState(!1),[P,R]=a.useState(jl),[j,W]=a.useState(!1),[K,ke]=a.useState(!1),[be,ce]=a.useState(!1),[ve,O]=a.useState(!1),oe=a.useRef(null),te=Sw(n.length),{confirm:pe}=Bs();a.useEffect(()=>{if(!j)return;function _e(nt){oe.current?.contains(nt.target)||W(!1)}function Fe(nt){nt.key==="Escape"&&W(!1)}return document.addEventListener("mousedown",_e),document.addEventListener("keydown",Fe),()=>{document.removeEventListener("mousedown",_e),document.removeEventListener("keydown",Fe)}},[j]);const de=e==="archived",ge=de&&S,ie=!de&&!D&&e!=="in-progress"&&n.length>Pu;a.useEffect(()=>{R(_e=>e==="in-progress"||de||n.length<=Pu?jl:Math.min(Math.max(_e,jl),n.length))},[e,de,n.length]);const Ee=a.useCallback(_e=>{de||(_e.preventDefault(),_e.dataTransfer.dropEffect="move",N(!0))},[de]),Le=a.useCallback(_e=>{_e.currentTarget.contains(_e.relatedTarget)||N(!1)},[]),qe=a.useCallback(async _e=>{_e.preventDefault(),N(!1);const Fe=_e.dataTransfer.getData("text/plain");if(!Fe)return;const nt=n.find(we=>we.id===Fe);if(!(nt&&nt.column===e))try{await r(Fe,e)}catch(we){c(Se(we),"error")}},[e,r,c,n]),et=a.useMemo(()=>e!=="in-progress"?[]:PN(n,n,i),[e,n,i]),Xe=a.useMemo(()=>ie?n.slice(0,P):n,[ie,n,P]),Ze=Math.max(0,n.length-Xe.length),it=a.useCallback(()=>{R(_e=>Math.min(_e+Iu,n.length))},[n.length]),Ie=a.useCallback(async()=>{if(W(!1),!(n.length===0||!await pe({title:"Replan All Tasks",message:`Move all ${n.length} todo task${n.length===1?"":"s"} back to planning to be replanned?`}))){ke(!0);try{const Fe=await Promise.allSettled(n.map(le=>r(le.id,"triage"))),nt=Fe.filter(le=>le.status==="rejected").length,we=Fe.length-nt;nt===0?c(`Moved ${we} task${we===1?"":"s"} to planning for replanning`,"success"):c(`Moved ${we} of ${Fe.length} tasks; ${nt} failed`,"error")}finally{ke(!1)}}},[n,r,c,pe]),Ke=a.useMemo(()=>n.filter(_e=>!_e.paused),[n]),re=Ke.length,xe=e==="todo"||e==="in-progress"||e==="in-review",se=K||be||ve,Ae=a.useCallback(async()=>{if(!(!o||(W(!1),re===0)||!await pe({title:"Stop All Tasks",message:`Stop all ${re} ${Pn[e].toLowerCase()} task${re===1?"":"s"}?`,danger:!0}))){ce(!0);try{const Fe=await Promise.allSettled(Ke.map(le=>o(le.id))),nt=Fe.filter(le=>le.status==="rejected").length,we=Fe.length-nt;nt===0?c(`Stopped ${we} task${we===1?"":"s"}`,"success"):c(`Stopped ${we} of ${Fe.length} tasks; ${nt} failed`,"error")}finally{ce(!1)}}},[o,re,e,Ke,c,pe]),ze=a.useCallback(async()=>{if(W(!1),!(n.length===0||!await pe({title:"Move All to Todo",message:`Move all ${n.length} ${Pn[e].toLowerCase()} task${n.length===1?"":"s"} to Todo?`}))){O(!0);try{const Fe=await Promise.allSettled(n.map(le=>r(le.id,"todo"))),nt=Fe.filter(le=>le.status==="rejected").length,we=Fe.length-nt;nt===0?c(`Moved ${we} task${we===1?"":"s"} to Todo`,"success"):c(`Moved ${we} of ${Fe.length} tasks to Todo; ${nt} failed`,"error")}finally{O(!1)}}},[n,e,r,c,pe]),me=a.useCallback(async()=>{if(!(!y||n.length===0||!await pe({title:"Archive All Done",message:`Archive all ${n.length} done tasks?`,danger:!0})))try{const Fe=await y();c(`Archived ${Fe.length} tasks`,"success")}catch(Fe){c(Se(Fe)||"Failed to archive tasks","error")}},[y,n.length,c,pe]);return t.jsxs("div",{className:`column${ne?" drag-over":""}${de?" column-archived":""}${ge?" column-collapsed":""}`,"data-column":e,onDragOver:Ee,onDragLeave:Le,onDrop:qe,children:[t.jsxs("div",{className:"column-header",children:[t.jsx("div",{className:`column-dot dot-${e}`}),t.jsx("h2",{children:Pn[e]}),t.jsx("span",{className:`column-count${te?" 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:me,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:t.jsx(To,{size:16})}),de&&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(Yt,{size:16}):t.jsx(ui,{size:16})}),xe&&t.jsxs("div",{className:"column-menu",ref:oe,children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>W(_e=>!_e),"aria-haspopup":"menu","aria-expanded":j,"aria-label":`${Pn[e]} column actions`,title:"Column actions",disabled:se,children:t.jsx(fx,{size:16})}),j&&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||K,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 Ae(),disabled:re===0||be||!o,children:["Stop All",t.jsx("span",{className:"column-menu-item-hint",children:n.length===0?"No tasks in this column":re===0?"All tasks are already paused":`Pause ${re} active task${re===1?"":"s"}`})]}),t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void ze(),disabled:n.length===0||ve,children:["Move All to Todo",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Todo"]})]})]})]})]})]}),!ge&&t.jsx("p",{className:"column-desc",children:ww[e]}),!ge&&t.jsxs("div",{className:"column-body",children:[e==="triage"&&u&&t.jsx(Pp,{onCreate:u,addToast:c,tasks:A??[],availableModels:w,onPlanningMode:E,onSubtaskBreakdown:C,projectId:s,autoExpand:!1,favoriteProviders:_,favoriteModels:$,onToggleFavorite:F,onToggleModelFavorite:V}),e==="in-progress"?et.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):et.map(_e=>t.jsx(Tp,{label:_e.label,activeTasks:_e.activeTasks,queuedTasks:_e.queuedTasks,projectId:s,onOpenDetail:l,addToast:c,globalPaused:g,onUpdateTask:p,onRetryTask:f,onOpenDetailWithTab:z,taskStuckTimeoutMs:T,onOpenMission:I,lastFetchTimeMs:U,workflowStepNameLookup:Y},_e.label)):n.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):t.jsxs(t.Fragment,{children:[Xe.map(_e=>t.jsx(wo,{task:_e,projectId:s,onOpenDetail:l,addToast:c,globalPaused:g,onUpdateTask:p,onRetryTask:f,onArchiveTask:x,onUnarchiveTask:v,onDeleteTask:b,onOpenDetailWithTab:z,taskStuckTimeoutMs:T,onOpenMission:I,onMoveTask:r,lastFetchTimeMs:U,workflowStepNameLookup:Y},_e.id)),ie&&Ze>0&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:it,children:["Load ",Math.min(Iu,Ze)," more (",Ze," remaining)"]})]}),t.jsx(Ho,{slotId:"board-column-footer",projectId:s})]})]})}const Ip=a.memo(IN);Ip.displayName="Column";function $N(e,n){return[...e].sort((s,i)=>{if(n==="in-review"){const r=s.status==="merging"||s.status==="merging-pr",o=i.status==="merging"||i.status==="merging-pr";if(r!==o)return r?-1:1}return s.columnMovedAt&&i.columnMovedAt?i.columnMovedAt.localeCompare(s.columnMovedAt):s.columnMovedAt&&!i.columnMovedAt?-1:!s.columnMovedAt&&i.columnMovedAt?1:s.createdAt.localeCompare(i.createdAt)})}function DN(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}const $u=new Map;function LN(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 zN({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:A,onSubtaskBreakdown:w,onOpenDetailWithTab:E,favoriteProviders:C,favoriteModels:z,onToggleFavorite:_,onToggleModelFavorite:$,taskStuckTimeoutMs:F,onOpenMission:V,lastFetchTimeMs:D}){const[T,I]=a.useState(!0),U=a.useRef(!1),{fetchBatch:Y}=Hw(n),ne=a.useRef(null),[N,P]=a.useState($u),R=S.trim()!=="",j=a.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),W=a.useCallback(()=>{I(be=>{const ce=!be;return!ce&&!U.current&&y&&(U.current=!0,y()),ce})},[y]),K=a.useMemo(()=>{const be=Object.fromEntries(Oi.map(O=>[O,[]]));for(const O of e)be[O.column].push(O);const ce=j.current,ve={};for(const O of Oi){const oe=$N(be[O],O);ve[O]=DN(ce[O],oe)?ce[O]:oe}return j.current=ve,ve},[e]);a.useEffect(()=>{let be=!1;return Uo(n).then(ce=>{if(be)return;const ve=new Map(ce.map(O=>[O.id,O.name]));P(O=>LN(O,ve)?O:ve)}).catch(()=>{be||P(ce=>ce.size===0?ce:$u)}),()=>{be=!0}},[n]);const ke=a.useMemo(()=>e.filter(be=>be.prInfo||be.issueInfo).map(be=>be.id),[e]);return a.useEffect(()=>{if(ke.length!==0)return ne.current&&clearTimeout(ne.current),ne.current=setTimeout(()=>{const be=[];for(let ce=0;ce<ke.length;ce+=50)be.push(ke.slice(ce,ce+50));be.forEach(ce=>{Y(ce)})},500),()=>{ne.current&&clearTimeout(ne.current)}},[ke,Y]),t.jsx(t.Fragment,{children:t.jsx("main",{className:"board",id:"board",children:Oi.map(be=>t.jsx(Ip,{column:be,tasks:K[be],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:E,favoriteProviders:C,favoriteModels:z,onToggleFavorite:_,onToggleModelFavorite:$,isSearchActive:R,taskStuckTimeoutMs:F,onOpenMission:V,lastFetchTimeMs:D,workflowStepNameLookup:N,...be==="triage"?{onQuickCreate:c,onNewTask:u,onPlanningMode:A,onSubtaskBreakdown:w}:{},...be==="in-review"?{autoMerge:d,onToggleAutoMerge:m}:{},...be==="done"?{onArchiveAllDone:b}:{},...be==="archived"?{collapsed:T,onToggleCollapse:W}:{}},be))})})}const Ua={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},Du=new Set(["planning","researching","executing","finalizing","merging"]),$c=["id","title","status","column","dependencies","progress"];function ON(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function FN(e){return e==="online"?"●":e==="connecting"?"◐":e==="error"?"✕":"○"}function Lu(e){try{const n=Hn("kb-dashboard-list-columns",e);if(n){const i=JSON.parse(n).filter(r=>$c.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set($c)}function zu(e){try{const n=Hn("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function Ou(e){try{const n=Hn("kb-dashboard-list-collapsed",e);if(n){const i=JSON.parse(n).filter(r=>Oi.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set}function Fu(e){try{const n=Hn("kb-dashboard-selected-tasks",e);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function UN(e){return e.status==="executing"||e.column==="in-progress"}function Uu(e){const n=Ap(e);return n.total===0||!UN(e)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function BN({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,A]=a.useState("id"),[w,E]=a.useState("desc"),[C,z]=a.useState(null),[_,$]=a.useState(null),[F,V]=a.useState(null),T=Pr()==="mobile",[I,U]=a.useState(()=>Lu(x)),[Y,ne]=a.useState(()=>zu(x)),[N,P]=a.useState(()=>Ou(x));a.useEffect(()=>{typeof window<"u"&&ls("kb-dashboard-list-columns",JSON.stringify([...I]),x)},[x,I]),a.useEffect(()=>{typeof window<"u"&&ls("kb-dashboard-hide-done",Y.toString(),x)},[Y,x]),a.useEffect(()=>{typeof window<"u"&&ls("kb-dashboard-list-collapsed",JSON.stringify([...N]),x)},[N,x]);const[R,j]=a.useState(!1),W=a.useRef(null),[K,ke]=a.useState(()=>Fu(x));a.useEffect(()=>{U(Lu(x)),ne(zu(x)),P(Ou(x)),ke(Fu(x))},[x]),a.useEffect(()=>{typeof window<"u"&&ls("kb-dashboard-selected-tasks",JSON.stringify([...K]),x)},[x,K]);const be=a.useCallback(Q=>{ke(ue=>{const ye=new Set(ue);return ye.has(Q)?ye.delete(Q):ye.add(Q),ye})},[]),ce=a.useCallback(()=>{ke(new Set)},[]),ve=a.useCallback(Q=>{U(ue=>{const ye=new Set(ue);return ye.has(Q)?ye.size>1&&ye.delete(Q):ye.add(Q),ye})},[]);a.useEffect(()=>{if(!R)return;const Q=ye=>{W.current&&!W.current.contains(ye.target)&&j(!1)},ue=ye=>{ye.key==="Escape"&&j(!1)};return document.addEventListener("mousedown",Q),document.addEventListener("keydown",ue),()=>{document.removeEventListener("mousedown",Q),document.removeEventListener("keydown",ue)}},[R]);const O={id:"ID",title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},oe=a.useCallback(Q=>{k===Q?E(ue=>ue==="asc"?"desc":"asc"):(A(Q),E("asc"))},[k]),te=a.useCallback(Q=>{V(ue=>ue===Q?null:Q)},[]),pe=a.useCallback(Q=>{P(ue=>{const ye=new Set(ue);return ye.has(Q)?ye.delete(Q):ye.add(Q),ye})},[]),de=a.useCallback(()=>{V(null)},[]),ge=a.useMemo(()=>{let Q=y?e.filter(X=>X.id.toLowerCase().includes(y.toLowerCase())||X.title&&X.title.toLowerCase().includes(y.toLowerCase())||X.description.toLowerCase().includes(y.toLowerCase())):[...e];Y&&!F&&(Q=Q.filter(X=>X.column!=="done"&&X.column!=="archived"));const ye=[...F?Q.filter(X=>X.column===F):Q].sort((X,Ye)=>{let ot=0;switch(k){case"id":ot=X.id.localeCompare(Ye.id);break;case"title":ot=(X.title||X.description).localeCompare(Ye.title||Ye.description);break;case"status":ot=(X.status||"").localeCompare(Ye.status||"");break;case"column":ot=X.column.localeCompare(Ye.column);break}return w==="asc"?ot:-ot}),at={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};return ye.forEach(X=>at[X.column].push(X)),at},[e,y,k,w,Y,F]),ie=a.useMemo(()=>Object.values(ge).reduce((Q,ue)=>Q+ue.length,0),[ge]),Ee=a.useMemo(()=>e.filter(Q=>Q.column==="done"||Q.column==="archived").length,[e]),Le=a.useMemo(()=>Y?Ee:0,[Y,Ee]),qe=a.useCallback(()=>{const Q=Object.values(ge).flat().filter(ue=>ue.column!=="archived").map(ue=>ue.id);ke(ue=>{if(Q.every(at=>ue.has(at))){const at=new Set(ue);return Q.forEach(X=>at.delete(X)),at}else return new Set([...ue,...Q])})},[ge]),et=a.useMemo(()=>{const Q=Object.values(ge).flat().filter(ue=>ue.column!=="archived");return Q.length===0?!1:Q.every(ue=>K.has(ue.id))},[ge,K]),Xe=a.useMemo(()=>{const Q=Object.values(ge).flat().filter(ye=>ye.column!=="archived");if(Q.length===0)return!1;const ue=Q.filter(ye=>K.has(ye.id)).length;return ue>0&&ue<Q.length},[ge,K]),[Ze,it]=a.useState("__no_change__"),[Ie,Ke]=a.useState("__no_change__"),[re,xe]=a.useState("__no_change__"),[se,Ae]=a.useState([]),[ze,me]=a.useState(!1),_e=a.useMemo(()=>re&&re!=="__no_change__"?se.find(Q=>Q.id===re):void 0,[se,re]),[Fe,nt]=a.useState(!1);a.useEffect(()=>{if(K.size===0)return;let Q=!1;return(async()=>{me(!0);try{const ye=await yo();Q||Ae(ye)}catch(ye){console.error("Failed to fetch nodes for bulk edit",ye),Q||Ae([])}finally{Q||me(!1)}})(),()=>{Q=!0}},[K.size]);const we=a.useCallback(async()=>{if(K.size===0)return;const Q=Array.from(K).filter(ye=>{const at=e.find(X=>X.id===ye);return at&&at.column!=="archived"});if(Q.length===0){i("No valid tasks to update (archived tasks cannot be modified)","error");return}const ue={taskIds:Q};if(Ze!=="__no_change__")if(Ze==="")ue.modelProvider=null,ue.modelId=null;else{const ye=Ze.indexOf("/");ye!==-1&&(ue.modelProvider=Ze.slice(0,ye),ue.modelId=Ze.slice(ye+1))}if(Ie!=="__no_change__")if(Ie==="")ue.validatorModelProvider=null,ue.validatorModelId=null;else{const ye=Ie.indexOf("/");ye!==-1&&(ue.validatorModelProvider=Ie.slice(0,ye),ue.validatorModelId=Ie.slice(ye+1))}if(re!=="__no_change__"&&(re===""?ue.nodeId=null:ue.nodeId=re),Object.keys(ue).length===1){i("No changes to apply","info");return}nt(!0);try{const ye=await Tv(ue.taskIds,ue.modelProvider,ue.modelId,ue.validatorModelProvider,ue.validatorModelId,void 0,void 0,ue.nodeId,x);f&&f(ye.updated),i(`Updated ${Q.length} task${Q.length===1?"":"s"}`,"success"),ce(),it("__no_change__"),Ke("__no_change__"),xe("__no_change__")}catch(ye){i(Se(ye)||"Failed to update models","error")}finally{nt(!1)}},[K,e,Ze,Ie,re,x,i,ce,f]),le=a.useCallback(Q=>{s(Q)},[s]),Te=a.useCallback((Q,ue)=>{if(ue.paused){Q.preventDefault();return}Q.dataTransfer.setData("text/plain",ue.id),Q.dataTransfer.effectAllowed="move",z(ue.id)},[]),he=a.useCallback(()=>{z(null),$(null)},[]),Me=a.useCallback((Q,ue)=>{Q.preventDefault(),Q.dataTransfer.dropEffect="move",$(ue)},[]),We=a.useCallback(()=>{$(null)},[]),Re=a.useCallback(async(Q,ue)=>{Q.preventDefault(),$(null);const ye=Q.dataTransfer.getData("text/plain");if(ye){if(ue==="archived"){i("Tasks can only be archived via the archive button","error");return}try{await n(ye,ue)}catch(at){i(Se(at),"error")}}},[n,i]),ut=Q=>k!==Q?t.jsx(qh,{size:14,className:"sort-icon"}):w==="asc"?t.jsx(zi,{size:14,className:"sort-icon active"}):t.jsx(wr,{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:W,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>j(Q=>!Q),"aria-expanded":R,"aria-haspopup":"menu",children:[t.jsx(lx,{size:14}),"Columns"]}),R&&t.jsx("div",{className:"list-column-dropdown",role:"menu",children:$c.map(Q=>{const ue=I.has(Q),ye=ue&&I.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${ye?" disabled":""}`,role:"menuitem",title:ye?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:ue,onChange:()=>ve(Q),disabled:ye}),t.jsx("span",{children:O[Q]})]},Q)})})]}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>ne(Q=>!Q),"aria-pressed":Y,title:Y?"Show done tasks":"Hide done tasks",children:[Y?t.jsx(fa,{size:14}):t.jsx(yc,{size:14}),Y?"Show Done":"Hide Done"]}),t.jsxs("div",{className:"list-stats",children:[F?`${ie} of ${e.length} tasks in ${Pn[F]}`:`${ie} of ${e.length} tasks`,Le>0&&!F&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",Le," hidden)"]}),F&&t.jsx("button",{className:"btn btn-sm",onClick:de,"aria-label":"Clear column filter",style:{marginLeft:"8px"},children:"Clear"})]}),K.size>0&&t.jsxs("div",{className:"list-selection-stats",children:[t.jsxs("span",{className:"selection-count",children:[K.size," selected"]}),t.jsx("button",{className:"btn btn-sm btn-link",onClick:ce,children:"Clear"})]}),K.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(Bn,{models:c,value:Ze,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(Bn,{models:c,value:Ie,onChange:Ke,label:"Reviewer Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:u,onToggleFavorite:m,favoriteModels:d,onToggleModelFavorite:h})}),t.jsxs("div",{className:"bulk-edit-dropdown bulk-edit-node-wrap",children:[t.jsxs("select",{className:"select bulk-node-select",value:re,onChange:Q=>xe(Q.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"}),se.map(Q=>t.jsx("option",{value:Q.id,children:`${FN(Q.status)} ${Q.name||Q.id} (${ON(Q.status)})`},Q.id))]}),_e?t.jsx(qi,{status:_e.status,showLabel:!0}):null]}),t.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:we,disabled:Fe||Ze==="__no_change__"&&Ie==="__no_change__"&&re==="__no_change__",children:Fe?"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:Oi.map(Q=>{const ue=e.filter(Ye=>Ye.column===Q).length,ye=Q==="done"||Q==="archived",at=Y&&ye?0:ue,X=Y&&ye&&ue>0;return t.jsxs("div",{className:`list-drop-zone${_===Q?" drag-over":""}${F===Q?" active":""}`,onClick:()=>te(Q),onDragOver:Ye=>Me(Ye,Q),onDragLeave:We,onDrop:Ye=>Re(Ye,Q),"data-column":Q,children:[t.jsx("span",{className:"drop-zone-dot",style:{background:Ua[Q]}}),t.jsx("span",{className:"drop-zone-label",children:Pn[Q]}),t.jsx("span",{className:"drop-zone-count",children:X?`${at} of ${ue}`:ue})]},Q)})}),t.jsxs("div",{className:"list-table-container",children:[t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx(Pp,{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})}),ie===0?t.jsx("div",{className:"list-empty",children:y?"No tasks match your filter":"No tasks yet"}):T?t.jsx("div",{className:"list-cards",children:Oi.map(Q=>{if(F&&Q!==F||Y&&(Q==="done"||Q==="archived")&&!F)return null;const ue=ge[Q],ye=ue.length===0;if(y&&ye)return null;const at=N.has(Q);return t.jsxs(a.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${at?" list-section-header--collapsed":""}`,onClick:()=>pe(Q),"aria-expanded":!at,role:"button",tabIndex:0,onKeyDown:X=>{(X.key==="Enter"||X.key===" ")&&(X.preventDefault(),pe(Q))},children:[t.jsx(bn,{size:14,className:`list-section-chevron${at?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${Q}`}),t.jsx("span",{className:"list-section-title",children:Pn[Q]}),t.jsx("span",{className:"list-section-count",children:ue.length})]}),!at&&t.jsx(t.Fragment,{children:ye?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):ue.map(X=>{const Ye=X.status==="failed",ot=X.paused===!0,ht=ko(X,b,S),yt=!r&&!Ye&&!ot&&!ht&&(X.column==="in-progress"||Du.has(X.status)),vt=typeof X.status=="string"&&X.status.trim().length>0,pt=!!(X.dependencies&&X.dependencies.length>0),Et=Uu(X),It=Et.hasProgress,Bt=K.size>0;return t.jsxs("div",{className:`list-card${yt?" agent-active":""}${Bt?" list-card--selectable":""}`,onClick:()=>le(X),"data-id":X.id,children:[Bt&&t.jsx("label",{className:"list-card-checkbox",onClick:_t=>_t.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:K.has(X.id),onChange:_t=>{_t.stopPropagation(),be(X.id)},onClick:_t=>_t.stopPropagation(),disabled:X.column==="archived","aria-label":`Select ${X.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:X.id}),X.executionMode==="fast"&&t.jsx("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",children:"Fast"}),t.jsx("span",{className:"list-card-spacer"}),ht?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):vt?t.jsx("span",{className:`list-status-badge list-status-badge--${X.column}${Ye?" failed":""}${yt?" pulsing":""}`,children:X.status}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:X.title||X.description})}),(pt||It)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[pt&&t.jsxs("span",{className:"list-dep-badge",title:X.dependencies.join(", "),children:[t.jsx(ga,{size:12})," ",X.dependencies.length]}),It&&t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${Et.percent}%`,backgroundColor:Ua[X.column]}})}),t.jsx("span",{className:"list-progress-label",children:Et.label})]})]})]},X.id)})})]},Q)})}):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:et,ref:Q=>{Q&&(Q.indeterminate=Xe)},onChange:qe,"aria-label":"Select all visible tasks"})}),I.has("id")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>oe("id"),children:["ID ",ut("id")]}),I.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>oe("title"),children:["Title ",ut("title")]}),I.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>oe("status"),children:["Status ",ut("status")]}),I.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>oe("column"),children:["Column ",ut("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:Oi.map(Q=>{if(F&&Q!==F||Y&&(Q==="done"||Q==="archived")&&!F)return null;const ue=ge[Q],ye=ue.length===0;if(y&&ye)return null;const at=N.has(Q);return t.jsxs(a.Fragment,{children:[t.jsx("tr",{className:`list-section-header${at?" list-section-header--collapsed":""}`,onClick:()=>pe(Q),"aria-expanded":!at,children:t.jsxs("th",{colSpan:I.size+1,className:"list-section-cell",children:[t.jsx(bn,{size:14,className:`list-section-chevron${at?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${Q}`}),t.jsx("span",{className:"list-section-title",children:Pn[Q]}),t.jsx("span",{className:"list-section-count",children:ue.length})]})}),!at&&t.jsx(t.Fragment,{children:ye?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:I.size+1,className:"list-empty-cell",children:"No tasks"})}):ue.map(X=>{const Ye=X.status==="failed",ot=X.paused===!0,ht=ko(X,b,S),yt=!r&&!Ye&&!ot&&!ht&&(X.column==="in-progress"||Du.has(X.status)),vt=C===X.id;return t.jsxs("tr",{className:`list-row${Ye?" failed":""}${ot?" paused":""}${ht?" stuck":""}${yt?" agent-active":""}${vt?" dragging":""}`,onClick:()=>le(X),draggable:!ot,onDragStart:pt=>Te(pt,X),onDragEnd:he,"data-id":X.id,children:[t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:K.has(X.id),onChange:pt=>{pt.stopPropagation(),be(X.id)},onClick:pt=>pt.stopPropagation(),disabled:X.column==="archived","aria-label":`Select ${X.id}`})}),I.has("id")&&t.jsx("td",{className:"list-cell list-cell-id",children:X.id}),I.has("title")&&t.jsx("td",{className:"list-cell list-cell-title",children:t.jsxs("div",{className:"list-title-content",children:[X.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:X.title||X.description})]})}),I.has("status")&&t.jsx("td",{className:"list-cell",children:ht?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):X.status?t.jsx("span",{className:`list-status-badge list-status-badge--${X.column}${Ye?" failed":""}${yt?" pulsing":""}`,children:X.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:`${Ua[X.column]}20`,color:Ua[X.column]},children:Pn[X.column]})}),I.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:X.dependencies&&X.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:X.dependencies.join(", "),children:[t.jsx(ga,{size:12})," ",X.dependencies.length]}):"-"}),I.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const pt=Uu(X);return pt.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:`${pt.percent}%`,backgroundColor:Ua[X.column]}})}),t.jsx("span",{className:"list-progress-label",children:pt.label})]}):"-"})()})]},X.id)})})]},Q)})})]})]})]})}const HN={active:{label:"Active",color:"var(--success)",icon:wn},paused:{label:"Paused",color:"var(--warning)",icon:Fs},errored:{label:"Error",color:"var(--color-error)",icon:ss},initializing:{label:"Initializing",color:"var(--info)",icon:rt}};function qN(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 VN(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 WN(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 KN({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=HN[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(Un,{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:VN(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:qN(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(wn,{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(Fs,{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(Nr,{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(nn,{size:14}),t.jsx("span",{children:d?"Confirm":""})]})]})]})]})}const GN=a.memo(KN,WN);function JN(){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(Un,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(Rs,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(vn,{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(ss,{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 YN=1e4,Bu=5;function QN(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+=Bu){const x=e.slice(f,f+Bu),v=await Promise.allSettled(x.map(async b=>{try{return await au(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 au(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()},YN),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[m,e.length]),{healthMap:n,loading:i,error:o,refresh:m,refreshProject:h}}function XN({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 V=localStorage.getItem("kb-dashboard-recent-projects");if(V)try{const D=JSON.parse(V);b(D)}catch{}},[]);const[v,b]=a.useState([]),y=a.useMemo(()=>e.map(V=>V.id),[e]),{healthMap:S,loading:k}=QN(y),A=a.useMemo(()=>e.map(V=>({project:V,health:S[V.id]||null})),[e,S]),w=a.useMemo(()=>{let V=[...A];return u!=="all"&&(V=V.filter(({project:D})=>D.status===u)),m!==null&&(V=V.filter(({project:D})=>D.nodeId===m)),V},[A,u,m]),E=a.useMemo(()=>{const V=[...w];return V.sort((D,T)=>{let I=0;switch(g){case"name":I=D.project.name.localeCompare(T.project.name);break;case"activity":{const U=D.project.lastActivityAt||D.health?.lastActivityAt||D.project.updatedAt,Y=T.project.lastActivityAt||T.health?.lastActivityAt||T.project.updatedAt;I=new Date(Y).getTime()-new Date(U).getTime();break}case"status":{const U={errored:0,initializing:1,paused:2,active:3};I=U[D.project.status]-U[T.project.status];break}}return f==="asc"?I:-I}),V},[w,g,f]),C=a.useMemo(()=>{const V=e.length,D=e.filter(P=>P.status==="active").length,T=e.filter(P=>P.status==="errored").length,I=new Set;e.forEach(P=>{P.nodeId&&I.add(P.nodeId)});const U=I.size||(V>0?1:0);let Y=0,ne=0,N=0;return Object.values(S).forEach(P=>{P&&(Y+=P.activeTaskCount,ne+=P.totalTasksCompleted,N+=P.inFlightAgentCount)}),{totalProjects:V,activeProjects:D,erroredProjects:T,totalNodes:U,totalActiveTasks:Y,totalCompletedTasks:ne,totalInFlightAgents:N}},[e,S]),z=a.useMemo(()=>({all:e.length,active:e.filter(V=>V.status==="active").length,paused:e.filter(V=>V.status==="paused").length,errored:e.filter(V=>V.status==="errored").length}),[e]),_=a.useMemo(()=>{const V=new Map;return e.forEach(D=>{const T=D.nodeId,I=V.get(T);if(I)I.count++;else{const Y=c.find(ne=>ne.id===T)?.name??D._sourceNodeName??"Local";V.set(T,{name:Y,count:1})}}),Array.from(V.entries()).map(([D,{name:T,count:I}])=>({nodeId:D??null,name:T,count:I}))},[e,c]),$=a.useCallback(V=>{const D=[V.id,...v.filter(T=>T!==V.id)].slice(0,3);b(D),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify(D)),s(V)},[s,v]);return n||k&&e.length>0&&Object.keys(S).length===0?t.jsx(JN,{}):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(sr,{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(sn,{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(Hi,{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(Un,{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(Rs,{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(vn,{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(ss,{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(pr,{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(sn,{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})]})]}),_.length>1&&t.jsxs("div",{className:"project-node-filter",children:[t.jsx(pr,{size:14}),t.jsxs("select",{value:m??"",onChange:V=>{h(V.target.value||null)},className:"project-node-filter-select","aria-label":"Filter by node",children:[t.jsx("option",{value:"",children:"All Nodes"}),_.map(({nodeId:V,name:D,count:T})=>t.jsxs("option",{value:V??"",children:[D," (",T,")"]},V??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(go,{size:14}),t.jsxs("select",{value:`${g}-${f}`,onChange:V=>{const[D,T]=V.target.value.split("-");p(D),x(T)},className:"project-sort-select","aria-label":"Sort projects",children:[t.jsx("option",{value:"activity-desc",children:"Last Activity (Newest)"}),t.jsx("option",{value:"activity-asc",children:"Last Activity (Oldest)"}),t.jsx("option",{value:"name-asc",children:"Name (A-Z)"}),t.jsx("option",{value:"name-desc",children:"Name (Z-A)"}),t.jsx("option",{value:"status-asc",children:"Status (Error → Active)"}),t.jsx("option",{value:"status-desc",children:"Status (Active → Error)"})]}),t.jsx(qh,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:E.map(({project:V,health:D})=>{const T=c.find(U=>U.id===V.nodeId),I=T?void 0:V._sourceNodeName;return t.jsx(GN,{project:V,health:D,node:T,nodeNameFallback:I,onSelect:$,onPause:r,onResume:o,onRemove:l},V.id)})}),E.length===0&&t.jsxs("div",{className:"project-overview__no-results",children:[t.jsx(go,{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 ZN=45e3,e1=3e3,t1=2e3,n1=1500,Hu="fusion:sse-client-id";let sa=null;const ki=new Map;function qu(){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 $p(){if(!(typeof window>"u")){if(sa)return sa;try{const e=window.sessionStorage.getItem(Hu);if(e)return sa=e,e;const n=qu();return window.sessionStorage.setItem(Hu,n),sa=n,n}catch{return sa=qu(),sa}}}function Dp(e){if(!(typeof window>"u"))try{return{parsed:new URL(e,window.location.origin),preserveRelativePath:e.startsWith("/")}}catch{return}}function Lp(e){return e.origin===window.location.origin&&e.pathname==="/api/events"}function s1(e){const n=$p();if(!n)return e;const s=Dp(e);return!s||!Lp(s.parsed)?e:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function ud(e,n){const s=$p();if(!s)return;const i=Dp(e);if(!i||!Lp(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),ei(`${r.pathname}${r.search}${r.hash}`)}function i1(e){if(typeof window>"u")return;const n=ud(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 Wo(e){e.keepaliveTimer&&(clearInterval(e.keepaliveTimer),e.keepaliveTimer=null)}function Vu(e){if(typeof window>"u"||typeof window.fetch!="function")return;const n=ud(e.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,i=s?window.setTimeout(()=>s.abort(),n1):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{i!==null&&window.clearTimeout(i)})}function a1(e){Wo(e),ud(e.url,"keepalive")&&(Vu(e),e.keepaliveTimer=window.setInterval(()=>{Vu(e)},t1))}if(typeof window<"u"){const e=()=>{for(const s of Array.from(ki.values()))if(!s.closed){if(Wo(s),i1(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(ki.values()))i.subscribers.size!==0&&(i.closed=!1,md(i))};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("pageshow",n)}function ir(e){e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),e.heartbeatTimer=setTimeout(()=>{zp(e)},ZN)}function zp(e){if(e.heartbeatTimer&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=null),e.es&&(e.es.close(),e.es=null),Wo(e),e.nativeListeners.clear(),e.closed||e.subscribers.size===0||e.reconnectTimer)return;const n=ki.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=ki.get(e.url);s&&s===e&&e.subscribers.size>0&&md(e)},e1)}}function md(e){if(e.es||e.closed)return;e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);const n=new EventSource(ei(s1(e.url)));e.es=n,a1(e),n.addEventListener("open",()=>{ir(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);zp(e)}),n.addEventListener("message",()=>ir(e)),n.addEventListener("heartbeat",()=>ir(e)),Op(e),ir(e)}function Op(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=>{ir(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 r1(e){e.closed=!0,e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),Wo(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.es&&e.es.close(),e.es=null,e.nativeListeners.clear(),ki.delete(e.url)}function Hs(e,n={}){let s=ki.get(e);s||(s={url:e,es:null,subscribers:new Set,nativeListeners:new Map,heartbeatTimer:null,keepaliveTimer:null,reconnectTimer:null,hasOpenedOnce:!1,closed:!1},ki.set(e,s));const i={events:new Map,onOpen:n.onOpen,onReconnect:n.onReconnect,onError:n.onError};if(n.events)for(const[l,c]of Object.entries(n.events)){let u=i.events.get(l);u||(u=new Set,i.events.set(l,u)),u.add(c)}s.subscribers.add(i);const r=!!s.es&&s.hasOpenedOnce;md(s),Op(s),r&&queueMicrotask(()=>{s.subscribers.has(i)&&i.onOpen?.()});let o=!0;return()=>{if(!o)return;o=!1;const l=ki.get(e);l&&(l.subscribers.delete(i),l.subscribers.size===0&&r1(l))}}const hd="kb-planning-last-description",pd="kb-subtask-last-description",fd="kb-mission-last-goal";function o1(e,n){ls(hd,e,n)}function l1(e){return Hn(hd,e)||""}function ia(e){yr(hd,e)}function c1(e,n){ls(pd,e,n)}function d1(e){return Hn(pd,e)||""}function kl(e){yr(pd,e)}function u1(e,n){ls(fd,e,n)}function m1(e){return Hn(fd,e)||""}function bi(e){yr(fd,e)}function h1(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 p1(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 f1(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 Ts({entries:e,defaultShowThinking:n=!1}){const[s,i]=a.useState({}),r=f1(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?h1(o):void 0,h=o.question&&m!==void 0?p1(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 Wu="fusion-tab-id";function g1(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Gi(){if(typeof window>"u")return"server-tab";const e=window.sessionStorage.getItem(Wu);if(e)return e;const n=g1();return window.sessionStorage.setItem(Wu,n),n}function Ko(e){const n=a.useMemo(()=>Gi(),[]),[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(Uk(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=Bk(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=ei(`/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:Hs("/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(Hk(e,n)),i(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:u,isLoading:l}}const x1="fusion:ai-session-sync",Ku="fusion:ai-session-sync",b1=3e4,v1=6e4;function Ks(){return Date.now()}function y1(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Gu(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 j1{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=y1(),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:Ks()})}broadcastUpdate(n){const s=n.timestamp??Ks();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??Ks();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=Ks();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=Ks();this.releaseTabOwnership(n,s,i),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:i})}broadcastHeartbeat(n){const s=Ks();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(x1),this.channel.onmessage=s=>{const i=Gu(s.data);i&&this.handleIncomingMessage(i)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==Ku||!s.newValue))try{const i=JSON.parse(s.newValue),r=Gu(i.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=Ks();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},b1)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,i]of this.ownedSessions.entries()){const r=Ks();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(Ku,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:Ks()});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=Ks(),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>v1;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 Gs=new j1;function Ra(){const e=a.useSyncExternalStore(c=>Gs.subscribe(c),()=>Gs.getSnapshot(),()=>Gs.getSnapshot());a.useEffect(()=>{Gs.requestSync()},[]);const n=a.useCallback(c=>{Gs.broadcastUpdate(c)},[]),s=a.useCallback(c=>{Gs.broadcastCompleted(c)},[]),i=a.useCallback((c,u)=>{Gs.broadcastLock(c,u)},[]),r=a.useCallback((c,u)=>{Gs.broadcastUnlock(c,u)},[]),o=a.useCallback(c=>{Gs.broadcastHeartbeat(c)},[]),l=a.useCallback(()=>{Gs.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:i,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function k1(e,n){return e&&n?`${e}/${n}`:""}function w1(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 N1=["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 S1({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),[A,w]=a.useState(""),[E,C]=a.useState(!0),[z,_]=a.useState(!1),[$,F]=a.useState(!1),[V,D]=a.useState(!1),T=a.useRef(null),I=a.useRef(null),U=a.useRef(null),Y=a.useRef(null),[ne,N]=a.useState(o??null),P=a.useMemo(()=>Gi(),[]),{isLockedByOther:R,takeControl:j,isLoading:W}=Ko(e?ne:null),{activeTabMap:K,broadcastUpdate:ke,broadcastCompleted:be,broadcastLock:ce,broadcastUnlock:ve,broadcastHeartbeat:O}=Ra(),{confirm:oe}=Bs(),[te,pe]=a.useState(void 0),[de,ge]=a.useState(void 0),[ie,Ee]=a.useState([]),[Le,qe]=a.useState(!0),[et,Xe]=a.useState(null),[Ze,it]=a.useState([]),[Ie,Ke]=a.useState([]),re=k1(te,de);a.useEffect(()=>{(async()=>{try{qe(!0);const ue=await ds();Ee(ue.models),it(ue.favoriteProviders),Ke(ue.favoriteModels)}catch(ue){Xe(Se(ue)||"Failed to load models")}finally{qe(!1)}})()},[]);const xe=a.useCallback(Q=>{it(ue=>{const ye=ue,X=ye.includes(Q)?ye.filter(Ye=>Ye!==Q):[Q,...ye];return cn({favoriteProviders:X,favoriteModels:Ie}).catch(()=>{it(ye)}),X})},[Ie]),se=a.useCallback(Q=>{Ke(ue=>{const ye=ue,X=ye.includes(Q)?ye.filter(Ye=>Ye!==Q):[Q,...ye];return cn({favoriteProviders:Ze,favoriteModels:X}).catch(()=>{Ke(ye)}),X})},[Ze]),Ae=a.useCallback((Q,ue)=>{if(!Q||!ue)return"Using default";const ye=ie.find(at=>at.provider===Q&&at.id===ue);return ye?`${ye.provider}/${ye.id}`:`${Q}/${ue}`},[ie]),ze=a.useCallback(Q=>{I.current?.close();const ue=Mk(Q,i,{onThinking:ye=>{w(at=>at+ye),ke({sessionId:Q,status:"generating",needsInput:!1,owningTabId:P,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onQuestion:ye=>{_(!1),F(!1),bi(i),d({type:"question",sessionId:Q,question:ye}),w(""),S(!0),ke({sessionId:Q,status:"awaiting_input",needsInput:!0,owningTabId:P,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onSummary:ye=>{_(!1),F(!1),bi(i),d({type:"summary",sessionId:Q,summary:ye}),b(ye),w(""),S(!0),ke({sessionId:Q,status:"complete",needsInput:!1,owningTabId:P,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onError:ye=>{const at=ye||"Session failed while contacting the AI.";_(!1),F(!1),h(null),d({type:"error",sessionId:Q,errorMessage:at}),w(""),S(!0),U.current=Q,ke({sessionId:Q,status:"error",needsInput:!1,owningTabId:P,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null}),be({sessionId:Q,status:"error"})},onComplete:()=>{_(!1),F(!1),U.current=null,be({sessionId:Q,status:"complete"})},onConnectionStateChange:ye=>{_(ye==="reconnecting")}});I.current=ue},[be,ke,l,i,P]),me=a.useCallback(async Q=>{const ue=Q??l;if(ue.trim()){h(null),w(""),p([]),x([]),_(!1),d({type:"loading"});try{const{sessionId:ye}=await Sk(ue.trim(),i,te&&de?{modelProvider:te,modelId:de}:void 0);U.current=ye,N(ye),bi(i),ze(ye),p([])}catch(ye){_(!1),h(Se(ye)||"Failed to start interview session"),d({type:"initial"}),U.current=null,N(null)}}},[ze,l,te,de,i]);a.useEffect(()=>{e&&u.type==="initial"&&T.current?.focus()},[e,u.type]),a.useEffect(()=>{if(e&&r&&!k.current&&u.type==="initial"){c(r);const Q=setTimeout(()=>{k.current=!0,me(r)},0);return()=>clearTimeout(Q)}else if(e&&!r&&!k.current&&u.type==="initial"){const Q=m1(i);Q&&c(Q)}},[e,r,u.type,me]),a.useEffect(()=>{e||(k.current=!1,_(!1),F(!1),N(null))},[e]),a.useEffect(()=>{if(!e||!o||u.type!=="initial")return;let Q=!1;return di(o).then(ue=>{if(Q||!ue)return;const ye=ya(ue.conversationHistory);if(x(ye),N(ue.id),p(ye.map(at=>at.response).filter(at=>!!(at&&typeof at=="object"&&!Array.isArray(at)))),ue.status==="awaiting_input"&&ue.currentQuestion)try{bi(i);const at=JSON.parse(ue.currentQuestion);U.current=ue.id,S(!0),d({type:"question",sessionId:ue.id,question:at})}catch{h("Failed to restore session question.")}else if(ue.status==="complete"&&ue.result)try{bi(i);const at=JSON.parse(ue.result);U.current=ue.id,S(!0),b(at),d({type:"summary",sessionId:ue.id,summary:at})}catch{h("Failed to restore session result.")}else ue.status==="generating"?(U.current=ue.id,S(!0),ue.thinkingOutput&&w(ue.thinkingOutput),d({type:"loading"}),ze(ue.id)):ue.status==="error"&&(U.current=ue.id,S(!0),h(null),d({type:"error",sessionId:ue.id,errorMessage:ue.error??"The session encountered an error."}))}).catch(()=>{Q||h("Failed to resume session.")}),()=>{Q=!0}},[ze,e,o,u.type,i]),a.useEffect(()=>{if(!e){Y.current&&(ve(Y.current,P),Y.current=null);return}if(ne&&Y.current!==ne){Y.current&&ve(Y.current,P),ce(ne,P),Y.current=ne;return}!ne&&Y.current&&(ve(Y.current,P),Y.current=null)},[ce,ve,e,ne,P]),a.useEffect(()=>{if(!e||!ne||Y.current!==ne)return;O(P);const Q=setInterval(()=>{O(P)},3e4);return()=>{clearInterval(Q)}},[O,e,ne,P]),a.useEffect(()=>()=>{I.current?.close(),I.current=null,Y.current&&(ve(Y.current,P),Y.current=null)},[ve,P]),a.useEffect(()=>{if(!e)return;const Q=ue=>{(u.type==="question"||u.type==="summary")&&(ue.preventDefault(),ue.returnValue=""),I.current?.close()};return window.addEventListener("beforeunload",Q),()=>window.removeEventListener("beforeunload",Q)},[e,u]);const _e=a.useCallback(()=>{I.current?.close(),I.current=null,n()},[n]),Fe=a.useCallback(async()=>{if(l&&u1(l,i),!(y&&!await oe({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 xp(u.sessionId,i,P)}catch{}c(""),d({type:"initial"}),h(null),p([]),x([]),b(null),w(""),_(!1),F(!1),S(!1),D(!1),pe(void 0),ge(void 0),U.current=null,N(null),n()}},[l,y,u,n,i,P,oe]);a.useEffect(()=>{if(!e)return;const Q=ue=>{ue.key==="Escape"&&Fe()};return document.addEventListener("keydown",Q),()=>document.removeEventListener("keydown",Q)},[e,Fe]);const nt=a.useCallback(async Q=>{if(u.type!=="question")return;const{sessionId:ue}=u;h(null),p(ye=>[...ye,Q]),x(ye=>[...ye,{question:u.question,response:Q}]),d({type:"loading"}),w("");try{ze(ue),await Ck(ue,Q,i,P),S(!0)}catch(ye){I.current?.close(),I.current=null,h(Se(ye)||"Failed to submit response"),d({type:"question",sessionId:ue,question:u.question})}},[u,i,P,ze]),we=a.useCallback(async()=>{if(u.type!=="error")return;const Q=u.sessionId;h(null),F(!0),w(""),d({type:"loading"}),ze(Q);try{U.current=Q,N(Q),await Ek(Q,i,P)}catch(ue){let ye=ue;if((Se(ue)||"").includes("not in an error state"))try{const X=await di(Q);if(!X)throw new Error("Failed to refresh interview session.");const Ye=ya(X.conversationHistory);if(x(Ye),p(Ye.map(ot=>ot.response).filter(ot=>!!(ot&&typeof ot=="object"&&!Array.isArray(ot)))),U.current=X.id,N(X.id),S(!0),X.status==="generating")w(X.thinkingOutput??""),d({type:"loading"}),I.current?.isConnected()||ze(X.id);else if(X.status==="awaiting_input"){if(!X.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");bi(i);const ot=JSON.parse(X.currentQuestion);d({type:"question",sessionId:X.id,question:ot}),I.current?.isConnected()||ze(X.id)}else if(X.status==="complete"){if(!X.result)throw new Error("Interview session is complete but has no result.");bi(i);const ot=JSON.parse(X.result);b(ot),d({type:"summary",sessionId:X.id,summary:ot})}else X.status==="error"&&d({type:"error",sessionId:X.id,errorMessage:X.error??"Retry failed. Please try again."});_(!1);return}catch(X){ye=X}I.current?.close(),I.current=null,d({type:"error",sessionId:Q,errorMessage:Se(ye)||"Retry failed. Please try again."}),_(!1)}finally{F(!1)}},[ze,i,P,u]),le=a.useCallback(async()=>{if(u.type==="summary"){h(null),D(!0);try{const Q=await _k(u.sessionId,v||void 0,i);s(Q),bi(i),I.current?.close(),I.current=null,c(""),d({type:"initial"}),h(null),p([]),x([]),b(null),w(""),_(!1),F(!1),S(!1),D(!1),U.current=null,N(null),n()}catch(Q){h(Se(Q)||"Failed to create mission"),D(!1)}}},[u,v,s,n,i]),Te=()=>u.type==="question"?Math.min(g.length+1,6):6,he=u.type==="loading"||u.type==="question"||u.type==="summary"||u.type==="error",Me=ne?K.get(ne):null,We=Me&&Me.tabId!==P,Re=!!(We&&!Me.stale),ut=R&&(!We||Me.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Q=>Q.target===Q.currentTarget&&Fe(),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(cs,{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:_e,title:"Send to background","aria-label":"Send to background",children:t.jsx(Er,{size:16})}),t.jsx("button",{className:"modal-close",onClick:Fe,"aria-label":"Close",children:t.jsx(Kt,{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…"}),Re&&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:T,id:"mission-goal",rows:4,className:"planning-textarea",placeholder:"e.g., Build a real-time collaborative document editor with presence, comments, and version history...",value:l,onChange:Q=>c(Q.target.value),onKeyDown:Q=>{Q.key==="Enter"&&!Q.shiftKey&&l.trim()&&(Q.preventDefault(),me())}})]}),t.jsxs("div",{className:"planning-examples",children:[t.jsx("span",{className:"planning-examples-label",children:"Try an example:"}),t.jsx("div",{className:"planning-example-chips",children:N1.map((Q,ue)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c(Q),children:Q.length>45?Q.slice(0,45)+"...":Q},ue))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",Le&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(Bn,{id:"mission-interview-modal-model",label:"Planning Model",value:re,onChange:Q=>{const{provider:ue,modelId:ye}=w1(Q);pe(ue),ge(ye)},models:ie,disabled:Le,favoriteProviders:Ze,onToggleFavorite:xe,favoriteModels:Ie,onToggleModelFavorite:se}),et&&t.jsxs("div",{className:"form-hint form-hint-error",children:[et," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{qe(!0);const Q=await ds();Ee(Q.models),it(Q.favoriteProviders),Ke(Q.favoriteModels),Xe(null)}catch(Q){Xe(Se(Q)||"Failed to load models")}finally{qe(!1)}})()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${te&&de?"model-badge-custom":"model-badge-default"}`,children:Ae(te,de)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>me(),disabled:!l.trim(),children:[t.jsx(cs,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),u.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(rt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:A?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>C(!E),type:"button",children:E?"Hide thinking":"Show thinking"}),E&&A&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:A})})]})]}),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(Ts,{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 we(),disabled:$,children:[$?t.jsx(rt,{size:14,className:"spin"}):t.jsx(Mn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:$?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Fe,disabled:$,children:"Cancel"})]})]})]})}),u.type==="question"&&t.jsx(C1,{question:u.question,progress:Te(),historyEntries:f,onSubmit:nt}),u.type==="summary"&&v&&t.jsx(E1,{summary:v,historyEntries:f,onSummaryChange:b,onApprove:le,onStartOver:()=>{d({type:"initial"}),S(!1),b(null),p([]),x([]),N(null),I.current?.close(),I.current=null},isCreating:V}),R&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Lo,{size:16}),t.jsx("span",{children:ut?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),ut&&t.jsx("button",{type:"button",onClick:()=>{j()},disabled:W,className:"btn btn-primary session-lock-take-control",children:W?"Taking control...":"Take Control"})]})})]})]})}):null}function C1({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(Ts,{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(vn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Kt,{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(Nr,{size:16,className:"icon-ml-4"})]})})]})}function E1({summary:e,historyEntries:n,onSummaryChange:s,onApprove:i,onStartOver:r,isCreating:o}){const[l,c]=a.useState(()=>new Set(e.milestones.map((k,A)=>A))),[u,d]=a.useState(()=>{const k=new Set;return e.milestones.forEach((A,w)=>{A.slices.forEach((E,C)=>k.add(`${w}-${C}`))}),k}),m=k=>{c(A=>{const w=new Set(A);return w.has(k)?w.delete(k):w.add(k),w})},h=k=>{d(A=>{const w=new Set(A);return w.has(k)?w.delete(k):w.add(k),w})},g=(k,A)=>{const w=[...e.milestones];w[k]={...w[k],...A},s({...e,milestones:w})},p=(k,A,w)=>{const E=[...e.milestones],C=[...E[k].slices];C[A]={...C[A],...w},E[k]={...E[k],slices:C},s({...e,milestones:E})},f=(k,A,w,E)=>{const C=[...e.milestones],z=[...C[k].slices],_=[...z[A].features];_[w]={..._[w],...E},z[A]={...z[A],features:_},C[k]={...C[k],slices:z},s({...e,milestones:C})},x=k=>{const A=e.milestones.filter((w,E)=>E!==k);s({...e,milestones:A})},v=(k,A)=>{const w=[...e.milestones];w[k]={...w[k],slices:w[k].slices.filter((E,C)=>C!==A)},s({...e,milestones:w})},b=(k,A,w)=>{const E=[...e.milestones],C=[...E[k].slices];C[A]={...C[A],features:C[A].features.filter((z,_)=>_!==w)},E[k]={...E[k],slices:C},s({...e,milestones:E})},y=(k,A)=>{const w=[...e.milestones],E=[...w[k].slices];E[A]={...E[A],features:[...E[A].features,{title:"New feature",description:""}]},w[k]={...w[k],slices:E},s({...e,milestones:w})},S=e.milestones.reduce((k,A)=>k+A.slices.reduce((w,E)=>w+E.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(Ts,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(vn,{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,A)=>t.jsxs("div",{className:"roadmap-card",children:[t.jsxs("div",{className:"roadmap-card-header",onClick:()=>m(A),children:[l.has(A)?t.jsx(Yt,{size:16,className:"icon-text-secondary"}):t.jsx(bn,{size:16,className:"icon-text-secondary"}),t.jsx(Bi,{size:16,className:"icon-milestone"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:k.title,onChange:w=>g(A,{title:w.target.value}),onClick:w=>w.stopPropagation()}),e.milestones.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:w=>{w.stopPropagation(),x(A)},title:"Remove milestone",children:t.jsx(nn,{size:14,className:"icon-text-secondary"})})]}),l.has(A)&&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:w=>g(A,{description:w.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:w=>g(A,{verification:w.target.value})})]}),k.slices.map((w,E)=>{const C=`${A}-${E}`;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(Yt,{size:14,className:"icon-text-secondary"}):t.jsx(bn,{size:14,className:"icon-text-secondary"}),t.jsx(Sc,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:w.title,onChange:z=>p(A,E,{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(A,E)},title:"Remove slice",children:t.jsx(nn,{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:w.verification||"",onChange:z=>p(A,E,{verification:z.target.value})})]}),w.features.map((z,_)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(xc,{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:$=>f(A,E,_,{title:$.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(A,E,_),title:"Remove feature",children:t.jsx(nn,{size:12,className:"icon-text-secondary"})})]},_)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>y(A,E),children:[t.jsx(sn,{size:12}),"Add Feature"]})]})]},E)})]})]},A))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:o,children:[t.jsx(_a,{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(rt,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):t.jsxs(t.Fragment,{children:[t.jsx(vn,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}function _1({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(""),[A,w]=a.useState(!0),[E,C]=a.useState(!1),[z,_]=a.useState(!1),$=a.useRef(null),F=a.useRef(null),V=a.useRef(null),D=a.useRef(null),[T,I]=a.useState(null),U=a.useMemo(()=>Gi(),[]);Ko(e?T:null);const{activeTabMap:Y,broadcastUpdate:ne,broadcastCompleted:N,broadcastLock:P,broadcastUnlock:R,broadcastHeartbeat:j}=Ra(),W=i==="milestone"?Ak:$k,K=i==="milestone"?Rk:Dk,ke=i==="milestone"?Tk:Lk,be=i==="milestone"?Pk:zk,ce=i==="milestone"?Ik:Ok,ve=i==="milestone"?"Milestone":"Slice",O=i==="milestone"?"milestone_interview":"slice_interview",oe=a.useCallback(Ie=>{F.current?.close();const Ke=ke(Ie,c,{onThinking:re=>{k(xe=>xe+re),ne({sessionId:Ie,status:"generating",needsInput:!1,owningTabId:U,type:O,title:o,projectId:c??null})},onQuestion:re=>{C(!1),te(),m({type:"question",sessionId:Ie,question:re}),k(""),ne({sessionId:Ie,status:"awaiting_input",needsInput:!0,owningTabId:U,type:O,title:o,projectId:c??null})},onSummary:re=>{C(!1),te(),m({type:"summary",sessionId:Ie,summary:re}),y(re),k(""),ne({sessionId:Ie,status:"complete",needsInput:!1,owningTabId:U,type:O,title:o,projectId:c??null})},onError:re=>{const xe=re||"Session failed while contacting the AI.";C(!1),g(null),m({type:"error",sessionId:Ie,errorMessage:xe}),k(""),V.current=Ie,ne({sessionId:Ie,status:"error",needsInput:!1,owningTabId:U,type:O,title:o,projectId:c??null}),N({sessionId:Ie,status:"error"})},onComplete:()=>{C(!1),V.current=null,N({sessionId:Ie,status:"complete"})},onConnectionStateChange:re=>{C(re==="reconnecting")}});F.current=Ke},[N,ne,ke,O,c,U,o]),te=()=>{y(null),f([]),v([]),k("")},pe=a.useCallback(async()=>{g(null),te(),C(!1),m({type:"loading"});try{const{sessionId:Ie}=await W(r,c);V.current=Ie,I(Ie),oe(Ie)}catch(Ie){C(!1),g(Se(Ie)||`Failed to start ${ve.toLowerCase()} interview`),m({type:"initial"}),V.current=null,I(null)}},[oe,c,W,r,ve]),de=a.useCallback(async()=>{g(null),_(!0);try{await ce(r,c),s(),m({type:"applied"})}catch(Ie){g(Se(Ie)||`Failed to skip ${ve.toLowerCase()} interview`),_(!1)}},[s,c,ce,r,ve]);a.useEffect(()=>{e&&d.type==="initial"&&$.current?.focus()},[e,d.type]),a.useEffect(()=>{if(!e||!u||d.type!=="initial")return;let Ie=!1;return di(u).then(Ke=>{if(Ie||!Ke)return;const re=ya(Ke.conversationHistory);if(v(re),I(Ke.id),f(re.map(xe=>xe.response).filter(xe=>!!(xe&&typeof xe=="object"&&!Array.isArray(xe)))),Ke.status==="awaiting_input"&&Ke.currentQuestion)try{const xe=JSON.parse(Ke.currentQuestion);V.current=Ke.id,m({type:"question",sessionId:Ke.id,question:xe})}catch{g("Failed to restore session question.")}else if(Ke.status==="complete"&&Ke.result)try{const xe=JSON.parse(Ke.result);V.current=Ke.id,y(xe),m({type:"summary",sessionId:Ke.id,summary:xe})}catch{g("Failed to restore session result.")}else Ke.status==="generating"?(V.current=Ke.id,Ke.thinkingOutput&&k(Ke.thinkingOutput),m({type:"loading"}),oe(Ke.id)):Ke.status==="error"&&(V.current=Ke.id,g(null),m({type:"error",sessionId:Ke.id,errorMessage:Ke.error??"The session encountered an error."}))}).catch(()=>{Ie||g("Failed to resume session.")}),()=>{Ie=!0}},[oe,e,u,d.type]),a.useEffect(()=>{e||(C(!1),I(null))},[e]),a.useEffect(()=>{if(!(!e||!T)){if(D.current!==T){D.current&&R(D.current,U),P(T,U),D.current=T;return}!T&&D.current&&(R(D.current,U),D.current=null)}},[P,R,e,T,U]),a.useEffect(()=>{if(!e||!T||D.current!==T)return;j(U);const Ie=setInterval(()=>{j(U)},3e4);return()=>{clearInterval(Ie)}},[j,e,T,U]),a.useEffect(()=>()=>{F.current?.close(),F.current=null,D.current&&(R(D.current,U),D.current=null)},[R,U]);const ge=a.useCallback(()=>{F.current?.close(),F.current=null,n()},[n]),ie=a.useCallback(async()=>{F.current?.close(),F.current=null,te(),m({type:"initial"}),g(null),V.current=null,I(null),n()},[n]),Ee=a.useCallback(async Ie=>{if(d.type!=="question")return;const{sessionId:Ke}=d;g(null),f(re=>[...re,Ie]),v(re=>[...re,{question:d.question,response:Ie}]),m({type:"loading"}),k("");try{oe(Ke),await K(Ke,Ie,c,U)}catch(re){F.current?.close(),F.current=null,g(Se(re)||"Failed to submit response"),m({type:"question",sessionId:Ke,question:d.question})}},[oe,c,K,U,d]),Le=a.useCallback(async()=>{if(d.type==="summary"){g(null),_(!0);try{await be(d.sessionId,b||void 0,c),s(),m({type:"applied"})}catch(Ie){g(Se(Ie)||"Failed to apply interview results"),_(!1)}}},[be,b,s,c,d]),qe=()=>d.type==="question"?Math.min(p.length+1,6):6,et=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",Xe=T?Y.get(T):null,it=!!(Xe&&Xe.tabId!==U&&!Xe.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Ie=>Ie.target===Ie.currentTarget&&ie(),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 ",ve,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[et&&t.jsx("button",{className:"modal-send-to-background",onClick:ge,title:"Send to background","aria-label":"Send to background",children:t.jsx(Er,{size:16})}),t.jsx("button",{className:"modal-close",onClick:ie,"aria-label":"Close",children:t.jsx(Kt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[h&&t.jsx("div",{className:"form-error planning-error",children:h}),E&&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 ",ve," 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 pe(),children:[t.jsx(Qn,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void de(),disabled:z,children:[z?t.jsx(rt,{size:16,className:"spin"}):null,"Use Mission Context"]}),t.jsx("button",{className:"btn",onClick:ie,children:"Cancel"})]})]}),d.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(rt,{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:()=>w(!A),type:"button",children:A?"Hide thinking":"Show thinking"}),A&&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(Ts,{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:ie,children:"Cancel"})})]})]})}),d.type==="question"&&t.jsx(M1,{question:d.question,progress:qe(),historyEntries:x,onSubmit:Ee}),d.type==="summary"&&b&&t.jsx(A1,{summary:b,historyEntries:x,onSummaryChange:y,onApply:Le,onCancel:ie,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(vn,{size:48,className:"icon-success"}),t.jsxs("h4",{children:[ve," 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 M1({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(Ts,{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(vn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Kt,{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(Nr,{size:16,className:"icon-ml-4"})]})})]})}function A1({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(Ts,{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(Yt,{size:16}):t.jsx(bn,{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(rt,{size:16,className:"spin"}):null,"Apply"]}),t.jsx("button",{className:"btn",onClick:r,disabled:o,children:"Cancel"})]})]})}const Ba={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)"}},Ju={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)"}},Yu={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)"}},Gr={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)"}},Jr={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)"}},Yr={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)"}},Qu={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)"}},R1=3;function T1(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function Xu({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 Zu(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const wl={title:"",description:"",status:"planning",autopilotEnabled:!1},Nl={title:"",description:"",status:"planning",dependencies:[]},Sl={title:"",description:"",status:"pending"},Cl={title:"",description:"",acceptanceCriteria:"",status:"defined"},P1=3600*1e3;function No(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 I1(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=P1,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 $1(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 D1(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 El(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 Fp=["feature_triaged","feature_completed"],Up=["slice_activated","slice_completed","milestone_completed"],Bp=["mission_started","mission_paused","mission_resumed","mission_completed"],Hp=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function em(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return Bp.includes(e);case"tasks":return Fp.includes(e);case"slices":return Up.includes(e);case"autopilot":return Hp.includes(e);default:return!0}}function L1(e){return e==="error"||e==="warning"?"mission-event__type--error":Bp.includes(e)?"mission-event__type--state":Fp.includes(e)?"mission-event__type--task":Up.includes(e)?"mission-event__type--slice":Hp.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function z1(e){return e.replace(/_/g," ")}function O1(e,n){return n?e==="watching"?`Watching since ${No(n)}`:`Last activation ${No(n)}`:null}function F1({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,A]=a.useState(!1),[w,E]=a.useState(null),[C,z]=a.useState(wl),[_,$]=a.useState(!1),[F,V]=a.useState(new Set),[D,T]=a.useState(new Set),[I,U]=a.useState(null),[Y,ne]=a.useState(Nl),[N,P]=a.useState(!1),[R,j]=a.useState(null),[W,K]=a.useState(Sl),[ke,be]=a.useState(!1),[ce,ve]=a.useState(null),[O,oe]=a.useState(null),[te,pe]=a.useState(Cl),[de,ge]=a.useState(!1),[ie,Ee]=a.useState(null),[Le,qe]=a.useState(null),[et,Xe]=a.useState(""),[Ze,it]=a.useState(!1),[Ie,Ke]=a.useState([]),[re,xe]=a.useState(void 0),se=re??c,[Ae,ze]=a.useState(null),[me,_e]=a.useState(null),[Fe,nt]=a.useState(null);a.useEffect(()=>{h&&se&&it(!0)},[h,se]),a.useEffect(()=>{if(!h||se)return;let B=!1;return ad(r).then(Ce=>{if(B)return;const De=Ce.filter(ft=>ft.type==="mission_interview"&&(ft.status==="awaiting_input"||ft.status==="error"));Ke(De)}).catch(Ce=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",Ce)}),()=>{B=!0}},[h,r,se]),a.useEffect(()=>{if(!h||!d)return;let B=!1;return di(d).then(Ce=>{if(!(B||!Ce))try{const De=JSON.parse(Ce.inputPayload||"{}");De.targetId&&De.targetType&&ze({type:De.targetType,id:De.targetId,title:De.targetTitle||Ce.title,resumeSessionId:d})}catch{ze({type:"milestone",id:"",title:Ce.title,resumeSessionId:d})}}).catch(Ce=>{B||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",Ce),m?.())}),()=>{B=!0}},[h,d,m]);const[we,le]=a.useState(null),[Te,he]=a.useState(new Map),[Me,We]=a.useState(null),[Re,ut]=a.useState({title:"",assertion:"",status:"pending"}),[Q,ue]=a.useState(!1),[ye,at]=a.useState(null),[X,Ye]=a.useState(new Map),[ot,ht]=a.useState(new Set),[yt,vt]=a.useState(new Set),[pt,Et]=a.useState(null),[It,Bt]=a.useState(new Map),[_t,Pt]=a.useState(null),[$t,Ht]=a.useState(null),[Gt,Dt]=a.useState(!0),[Tt,jt]=a.useState(new Set),[Mt,Zt]=a.useState(new Map),[At,H]=a.useState(null),[fe,$e]=a.useState(new Map),[M,ee]=a.useState(null),[Oe,dt]=a.useState(new Map),[Nt,Ct]=a.useState(new Map),[Rt,un]=a.useState("structure"),[mn,Nn]=a.useState([]),Qt=a.useRef([]),An=a.useRef([]),Ne=a.useRef(null),ae=a.useRef(null),Ge=a.useRef("structure"),ct=a.useRef("all"),[Lt,qt]=a.useState(!1),[En,hn]=a.useState(0),[Vt,J]=a.useState("all"),[Pe,Qe]=a.useState(new Set),tt=a.useRef(null),mt=a.useRef(null);An.current=g,Ne.current=f,ae.current=_t,Ge.current=Rt,ct.current=Vt;const St=a.useCallback((B="auto")=>{const Ce=mt.current;if(Ce&&typeof Ce.scrollIntoView=="function"){Ce.scrollIntoView({block:"end",behavior:B});return}const De=tt.current;De&&(De.scrollTop=De.scrollHeight)},[]),zt=a.useCallback(()=>{const B=tt.current;return B?B.scrollHeight-B.scrollTop-B.clientHeight<=100:!0},[]),Sn=a.useCallback(async B=>{if(B.length===0){Ct(new Map);return}const Ce=await Xj(r);Ct(De=>{const ft=new Map(De);for(const[fn,Ft]of Object.entries(Ce))$1(Ft)&&ft.set(fn,Ft);return ft})},[r]),an=a.useCallback(async()=>{try{b(!0);const B=await Kj(r);p(B),Sn(B)}catch(B){i(Se(B)||"Failed to load missions","error")}finally{b(!1)}},[i,r,Sn]),kt=a.useCallback(async B=>{try{S(!0);const Ce=await gp(B,r);if(x(Ce),Ce.milestones.length>0){const De=Ce.milestones[0].id;Pt(De),Dt(!0),V(new Set([De])),dl(De,r).then(ft=>{he(fn=>{const Ft=new Map(fn);return Ft.set(De,ft),Ft})}).catch(()=>{}),ul(De,r).then(ft=>{Bt(fn=>{const Ft=new Map(fn);return Ft.set(De,ft),Ft})}).catch(()=>{}),Ce.milestones[0].slices.length>0&&T(new Set([Ce.milestones[0].slices[0].id]))}else Pt(null),Ht(null)}catch(Ce){i(Se(Ce)||"Failed to load mission details","error")}finally{S(!1)}},[i,r]);a.useEffect(()=>{if(!h||!_t){Ht(null);return}let B=!1;return Ht(null),ou(_t,r).then(Ce=>{if(!B){if(!El(Ce)){Ht(null);return}Ht(Ce),Bt(De=>{const ft=new Map(De);return ft.set(_t,Ce.rollup),ft})}}).catch(()=>{B||Ht(null)}),()=>{B=!0}},[h,_t,r]),a.useEffect(()=>{Dt(!0)},[_t]);const as=a.useCallback(B=>{!B||B!==ae.current||ou(B,r).then(Ce=>{ae.current!==B||!El(Ce)||(Ht(Ce),Bt(De=>{const ft=new Map(De);return ft.set(B,Ce.rollup),ft}))}).catch(()=>{})},[r]),js=a.useCallback(async(B,Ce)=>{const De=Ce?.append??!1,ft=De?Qt.current.length:0;De||(qt(!0),Qe(new Set));try{const fn=await Qj(B,{limit:50,offset:ft,eventType:void 0},r),Ft=fn.events.filter(tn=>em(tn.eventType,Vt));Nn(tn=>{if(!De)return Ft;const He=new Set(tn.map(xt=>xt.id)),Ve=[...tn];for(const xt of Ft)He.has(xt.id)||Ve.push(xt);return Ve}),hn(fn.total),De||requestAnimationFrame(()=>{St("auto")})}catch(fn){i(Se(fn)||"Failed to load mission activity","error")}finally{De||qt(!1)}},[i,Vt,r,St]);a.useEffect(()=>{Qt.current=mn},[mn]),a.useEffect(()=>{h&&(an(),x(null),Pt(null),Ht(null),Nn([]),hn(0),un("structure"),J("all"),Qe(new Set))},[h,an]);const Ps=a.useRef(null);a.useEffect(()=>{h&&u&&Ps.current!==u&&g.length>0&&(Ps.current=u,kt(u))},[h,u,g,kt]),a.useEffect(()=>{h||(Ps.current=null)},[h]),a.useEffect(()=>{!h||!f||Rt!=="activity"||js(f.id)},[Rt,h,js,f,Vt]),a.useEffect(()=>{if(!h||typeof EventSource>"u")return;const B=new URLSearchParams;r&&B.set("projectId",r);const Ce=`/api/events${B.size>0?`?${B.toString()}`:""}`,De=()=>{Sn(An.current)},ft=Gn=>{De();const Cn=Gn;if(Cn.data)try{const Wt=JSON.parse(Cn.data);Wt?.id&&p(Ti=>Ti.map(Cs=>Cs.id===Wt.id?{...Cs,...Wt}:Cs))}catch{}Ne.current&&kt(Ne.current.id)},fn=Gn=>{De(),Ne.current&&kt(Ne.current.id)},Ft=()=>{De(),Ne.current&&kt(Ne.current.id)},tn=Gn=>{De(),Ne.current&&kt(Ne.current.id)},He=Gn=>{const Cn=Gn;if(Cn.data)try{const Wt=JSON.parse(Cn.data);Wt&&Wt.featureId&&(Rn(Wt.featureId),ai(Wt.featureId),Wt.milestoneId&&as(Wt.milestoneId))}catch{}},Ve=Gn=>{const Cn=Gn;if(Cn.data)try{const Wt=JSON.parse(Cn.data);Wt&&Wt.featureId&&(Rn(Wt.featureId),ai(Wt.featureId),Wt.milestoneId&&as(Wt.milestoneId),Ne.current&&kt(Ne.current.id))}catch{}},xt=Gn=>{const Cn=Gn;if(Cn.data)try{const Wt=JSON.parse(Cn.data);Wt&&Wt.milestoneId&&(On(Wt.milestoneId),as(Wt.milestoneId))}catch{}},gn=Gn=>{const Cn=Gn;if(Cn.data)try{const Wt=JSON.parse(Cn.data);Wt&&Wt.milestoneId&&(on(Wt.milestoneId),On(Wt.milestoneId),as(Wt.milestoneId))}catch{}};return Hs(Ce,{events:{"mission:updated":ft,"slice:updated":fn,"feature:updated":Ft,"milestone:updated":tn,"mission:event":Gn=>{De();const Cn=Ne.current;if(!Cn||Ge.current!=="activity")return;const Wt=zt(),Ti=Gn;if(Ti.data)try{const Cs=JSON.parse(Ti.data);if(!D1(Cs)||Cs.missionId!==Cn.id||!em(Cs.eventType,ct.current))return;Nn(oi=>{const al=oi.filter(rl=>rl.id!==Cs.id);return[Cs,...al].slice(0,100)}),hn(oi=>oi+1),Wt&&requestAnimationFrame(()=>{const oi=tt.current;oi&&(oi.scrollTop=0)})}catch{}},"validator-run:started":He,"validator-run:completed":Ve,"milestone:validation:updated":xt,"assertion:created":gn,"assertion:updated":gn,"assertion:deleted":gn,"assertion:linked":gn,"assertion:unlinked":gn,"fix-feature:created":Gn=>{const Cn=Gn;if(Cn.data)try{const Wt=JSON.parse(Cn.data);if(Wt&&Wt.sourceFeatureId){Rn(Wt.sourceFeatureId);const Ti=Wt?.feature?.sliceId,Cs=Ne.current;if(Ti&&Cs){const oi=Cs.milestones.find(al=>al.slices.some(rl=>rl.id===Ti));oi&&as(oi.id)}Ne.current&&kt(Ne.current.id)}}catch{}}}})},[h,zt,kt,Sn,r,as]);const Is=a.useCallback(()=>{A(!0),E(null),z(wl)},[]),si=a.useCallback(B=>{E(B.id),A(!1),z({title:B.title,description:B.description||"",status:B.status,autopilotEnabled:B.autopilotEnabled??!1})},[]),ks=a.useCallback(()=>{E(null),A(!1),z(wl)},[]),$s=a.useCallback(async()=>{if(!C.title.trim()){i("Mission title is required","error");return}try{if($(!0),k)await Gj({title:C.title.trim(),description:C.description.trim()||void 0,autopilotEnabled:C.autopilotEnabled},r),i("Mission created","success");else if(w){const B={title:C.title.trim(),description:C.description.trim()||void 0,status:C.status,autopilotEnabled:C.autopilotEnabled};C.autopilotEnabled&&(B.autoAdvance=!0),await Jj(w,B,r),i("Mission updated","success"),f?.id===w&&await kt(w)}await an(),ks()}catch(B){i(Se(B)||"Failed to save mission","error")}finally{$(!1)}},[C,k,w,i,an,kt,f,ks,r]),Yi=a.useCallback(async B=>{try{await Yj(B,r),i("Mission deleted","success"),f?.id===B&&x(null),await an(),le(null)}catch(Ce){i(Se(Ce)||"Failed to delete mission","error")}},[i,an,f,r]),gi=a.useCallback(()=>{P(!0),U(null),ne(Nl)},[]),ii=a.useCallback(B=>{U(B.id),P(!1),ne({title:B.title,description:B.description||"",status:B.status,dependencies:B.dependencies})},[]),ms=a.useCallback(()=>{U(null),P(!1),ne(Nl)},[]),qs=a.useCallback(async()=>{if(!Y.title.trim()){i("Milestone title is required","error");return}try{$(!0),N&&f?(await Zj(f.id,{title:Y.title.trim(),description:Y.description.trim()||void 0,dependencies:Y.dependencies},r),i("Milestone created","success")):I&&(await ek(I,{title:Y.title.trim(),description:Y.description.trim()||void 0,status:Y.status,dependencies:Y.dependencies},r),i("Milestone updated","success")),await kt(f.id),ms()}catch(B){i(Se(B)||"Failed to save milestone","error")}finally{$(!1)}},[Y,N,I,f,i,kt,ms,C.title,r]),q=a.useCallback(async B=>{try{await tk(B,r),i("Milestone deleted","success"),await kt(f.id),le(null)}catch(Ce){i(Se(Ce)||"Failed to delete milestone","error")}},[i,kt,f,r]),je=a.useCallback(B=>{Pt(B),Dt(!0),V(Ce=>{const De=new Set(Ce);return!De.has(B)?(De.add(B),dl(B,r).then(fn=>{he(Ft=>{const tn=new Map(Ft);return tn.set(B,fn),tn})}).catch(()=>{}),ul(B,r).then(fn=>{Bt(Ft=>{const tn=new Map(Ft);return tn.set(B,fn),tn})}).catch(()=>{})):De.delete(B),De})},[r]),Je=a.useCallback(B=>{ve(B),be(!0),j(null),K(Sl)},[]),bt=a.useCallback(B=>{j(B.id),be(!1),K({title:B.title,description:B.description||"",status:B.status})},[]),gt=a.useCallback(()=>{j(null),be(!1),ve(null),K(Sl)},[]),yn=a.useCallback(async()=>{if(!W.title.trim()){i("Slice title is required","error");return}try{$(!0),ke&&ce?(await nk(ce,{title:W.title.trim(),description:W.description.trim()||void 0},r),i("Slice created","success")):R&&(await sk(R,{title:W.title.trim(),description:W.description.trim()||void 0,status:W.status},r),i("Slice updated","success")),await kt(f.id),gt()}catch(B){i(Se(B)||"Failed to save slice","error")}finally{$(!1)}},[W,ke,R,ce,f,i,kt,gt,r]),en=a.useCallback(async B=>{try{await ik(B,r),i("Slice deleted","success"),await kt(f.id),le(null)}catch(Ce){i(Se(Ce)||"Failed to delete slice","error")}},[i,kt,f,r]),rn=a.useCallback(async B=>{try{await ak(B,r),i("Slice activated","success"),await kt(f.id)}catch(Ce){i(Se(Ce)||"Failed to activate slice","error")}},[i,kt,f,r]),pn=a.useCallback(B=>{T(Ce=>{const De=new Set(Ce);return De.has(B)?De.delete(B):De.add(B),De})},[]),In=a.useCallback(B=>{Ee(B),ge(!0),oe(null),pe(Cl)},[]),qn=a.useCallback(B=>{oe(B.id),ge(!1),pe({title:B.title,description:B.description||"",acceptanceCriteria:B.acceptanceCriteria||"",status:B.status})},[]),Vn=a.useCallback(()=>{oe(null),ge(!1),Ee(null),pe(Cl)},[]),_n=a.useCallback(async()=>{if(!te.title.trim()){i("Feature title is required","error");return}try{$(!0),de&&ie?(await rk(ie,{title:te.title.trim(),description:te.description.trim()||void 0,acceptanceCriteria:te.acceptanceCriteria.trim()||void 0},r),i("Feature created","success")):O&&(await ok(O,{title:te.title.trim(),description:te.description.trim()||void 0,acceptanceCriteria:te.acceptanceCriteria.trim()||void 0,status:te.status},r),i("Feature updated","success")),await kt(f.id),Vn()}catch(B){i(Se(B)||"Failed to save feature","error")}finally{$(!1)}},[te,de,O,ie,f,i,kt,Vn,r]),Wn=a.useCallback(async B=>{try{await lk(B,r),i("Feature deleted","success"),await kt(f.id),le(null)}catch(Ce){i(Se(Ce)||"Failed to delete feature","error")}},[i,kt,f,r]),Ln=a.useCallback(async()=>{if(!Le||!et.trim()){i("Task ID is required","error");return}try{await ck(Le,et.trim(),r),i("Feature linked to task","success"),await kt(f.id),qe(null),Xe("")}catch(B){i(Se(B)||"Failed to link feature to task","error")}},[Le,et,i,kt,f,r]),hs=a.useCallback(async B=>{try{await dk(B,r),i("Feature unlinked from task","success"),await kt(f.id)}catch(Ce){i(Se(Ce)||"Failed to unlink feature","error")}},[i,kt,f,r]),jn=a.useCallback(async B=>{try{$(!0),await uk(B,void 0,void 0,r),i("Feature triaged — task created","success"),await kt(f.id)}catch(Ce){i(Se(Ce)||"Failed to triage feature","error")}finally{$(!1)}},[i,kt,f,r]),zn=a.useCallback(async B=>{nt(B);try{const Ce=await Fk(B,r);_e({featureId:B,enrichedDescription:Ce.description})}catch{await jn(B)}finally{nt(null)}},[jn,r]),rs=a.useCallback(async()=>{me&&(_e(null),await jn(me.featureId))},[jn,me]),ws=a.useCallback(()=>{_e(null)},[]),Zn=a.useCallback(async B=>{try{$(!0);const Ce=await mk(B,r);i(`Triaged ${Ce.count} feature${Ce.count!==1?"s":""}`,"success"),await kt(f.id)}catch(Ce){i(Se(Ce)||"Failed to triage slice features","error")}finally{$(!1)}},[i,kt,f,r]),on=a.useCallback(async B=>{try{const Ce=await dl(B,r);he(De=>{const ft=new Map(De);return ft.set(B,Ce),ft})}catch{}},[r]),On=a.useCallback(async B=>{try{const Ce=await ul(B,r);Bt(De=>{const ft=new Map(De);return ft.set(B,Ce),ft})}catch{}},[r]),Ds=a.useCallback(async B=>{if(!Re.title.trim()||!Re.assertion.trim()){i("Title and assertion text are required","error");return}try{$(!0),await hk(B,{title:Re.title.trim(),assertion:Re.assertion.trim(),status:Re.status},r),i("Assertion created","success"),await on(B),await On(B),ue(!1),ut({title:"",assertion:"",status:"pending"})}catch(Ce){i(Se(Ce)||"Failed to create assertion","error")}finally{$(!1)}},[Re,i,on,On,r]),Zo=a.useCallback(B=>{We(B.id),ut({title:B.title,assertion:B.assertion,status:B.status})},[]),Ei=a.useCallback(()=>{We(null),ue(!1),ut({title:"",assertion:"",status:"pending"})},[]),Lr=a.useCallback(async(B,Ce)=>{if(!Re.title.trim()||!Re.assertion.trim()){i("Title and assertion text are required","error");return}try{$(!0),await pk(B,{title:Re.title.trim(),assertion:Re.assertion.trim(),status:Re.status},r),i("Assertion updated","success"),await on(Ce),await On(Ce),Ei()}catch(De){i(Se(De)||"Failed to update assertion","error")}finally{$(!1)}},[Re,i,on,On,Ei,r]),Ls=a.useCallback(async B=>{try{const Ce=await xk(B,r);Ye(De=>{const ft=new Map(De);return ft.set(B,Ce),ft})}catch{}},[r]),zr=a.useCallback(async B=>{const Ce=ye!==B;at(De=>De===B?null:B),Ce&&await Ls(B)},[ye,Ls]),Or=a.useCallback(B=>{at(B),Ls(B),requestAnimationFrame(()=>{const Ce=document.querySelector(`[data-mission-assertion-id="${B}"]`);Ce instanceof HTMLElement&&typeof Ce.scrollIntoView=="function"&&Ce.scrollIntoView({behavior:"smooth",block:"center"})})},[Ls]),Fr=a.useCallback(async(B,Ce)=>{try{ht(De=>new Set(De).add(Ce)),await fk(B,Ce,r),i("Feature linked to assertion","success"),await Ls(Ce),Et(null)}catch(De){i(Se(De)||"Failed to link feature","error")}finally{ht(De=>{const ft=new Set(De);return ft.delete(Ce),ft})}},[i,Ls,r]),Kn=a.useCallback(async(B,Ce)=>{const De=`${B}-${Ce}`;try{vt(ft=>new Set(ft).add(De)),await gk(B,Ce,r),i("Feature unlinked from assertion","success"),await Ls(Ce)}catch(ft){i(Se(ft)||"Failed to unlink feature","error")}finally{vt(ft=>{const fn=new Set(ft);return fn.delete(De),fn})}},[i,Ls,r]),Ia=a.useCallback(async B=>{try{jt(De=>new Set(De).add(B)),await bk(B,r),i("Validation triggered","success");const Ce=await lu(B,r);Zt(De=>{const ft=new Map(De);return ft.set(B,Ce),ft})}catch(Ce){i(Se(Ce)||"Failed to trigger validation","error")}finally{jt(Ce=>{const De=new Set(Ce);return De.delete(B),De})}},[i,r]),Rn=a.useCallback(async B=>{try{const Ce=await lu(B,r);Zt(De=>{const ft=new Map(De);return ft.set(B,Ce),ft})}catch{}},[r]),ai=a.useCallback(async B=>{try{const Ce=await vk(B,{limit:10},r);$e(De=>{const ft=new Map(De);return ft.set(B,Ce),ft})}catch{}},[r]),_i=a.useCallback(B=>{const Ce=Ne.current;if(Ce){for(const De of Ce.milestones)for(const ft of De.slices)if(ft.features.find(Ft=>Ft.id===B)){V(Ft=>{const tn=new Set(Ft);return tn.add(De.id),tn}),T(Ft=>{const tn=new Set(Ft);return tn.add(ft.id),tn}),H(B),Pt(De.id),Rn(B),ai(B),requestAnimationFrame(()=>{const Ft=document.querySelector(`[data-mission-feature-id="${B}"]`);Ft instanceof HTMLElement&&typeof Ft.scrollIntoView=="function"&&Ft.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[Rn,ai]),$a=a.useCallback(async B=>{try{const Ce=await yk(B,r);dt(De=>{const ft=new Map(De);return ft.set(B,Ce),ft})}catch{}},[r]),Qi=a.useCallback(async B=>{At===B?H(null):(H(B),await Rn(B),await ai(B))},[At,Rn,ai]),el=a.useCallback(async B=>{M===B?ee(null):(ee(B),await $a(B))},[M,$a]),Da=a.useCallback(async B=>{try{await jk(B,r),i("Mission resumed","success"),await kt(B),an()}catch(Ce){i(Se(Ce)||"Failed to resume mission","error")}},[i,kt,an,r]),Z=a.useCallback(async B=>{try{const De=(await kk(B,r)).pausedTaskIds?.length??0;i(`Mission stopped (${De} task${De!==1?"s":""} paused)`,"success"),await kt(B),an()}catch(Ce){i(Se(Ce)||"Failed to stop mission","error")}},[i,kt,an,r]),Be=a.useCallback(async B=>{try{await wk(B,r),i("Mission started — first slice activated","success"),await kt(B),an()}catch(Ce){i(Se(Ce)||"Failed to start mission","error")}},[i,kt,an,r]),lt=a.useCallback(async(B,Ce)=>{try{await Nk(B,{enabled:Ce},r),i(Ce?"Autopilot enabled":"Autopilot disabled","success"),await kt(B),an()}catch(De){i(Se(De)||"Failed to update autopilot","error")}},[i,kt,an,r]),Ot=a.useCallback(B=>{un("structure"),Pt(null),Ht(null),Nn([]),hn(0),J("all"),Qe(new Set),kt(B.id)},[kt]),Vs=a.useCallback(()=>{x(null),Pt(null),Ht(null),un("structure"),Nn([]),hn(0),J("all"),Qe(new Set),an()},[an]),ps=mn.length<En,xi=f?.autopilotState??"inactive",La=xi==="watching"||xi==="activating",Ur=O1(xi,f?.lastAutopilotActivityAt),Xi=a.useMemo(()=>!$t||!_t||!El($t)?null:$t.rollup.milestoneId===_t?$t:null,[_t,$t]),tl=a.useMemo(()=>{const B=new Map;for(const Ce of Xi?.validationTelemetry.validationRounds??[]){const De=B.get(Ce.featureId);(!De||Ce.startedAt>De.startedAt)&&B.set(Ce.featureId,Ce)}return B},[Xi]),nl=a.useCallback(()=>{!f||Lt||!ps||js(f.id,{append:!0})},[Lt,ps,js,f]),sl=a.useCallback(B=>{Qe(Ce=>{const De=new Set(Ce);return De.has(B)?De.delete(B):De.add(B),De})},[]),Mi=a.useCallback(B=>{B.key==="Enter"&&!B.shiftKey&&(B.preventDefault(),$s())},[$s]),Zi=a.useCallback(B=>{B.key==="Enter"&&!B.shiftKey&&(B.preventDefault(),qs())},[qs]),Ai=a.useCallback(B=>{B.key==="Enter"&&!B.shiftKey&&(B.preventDefault(),yn())},[yn]),ea=a.useCallback(B=>{B.key==="Enter"&&!B.shiftKey&&(B.preventDefault(),_n())},[_n]),$d=a.useRef(null);if(a.useEffect(()=>{if(!h)return;const B=Ce=>{Ce.key==="Escape"&&s()};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[h,s]),!h)return null;const il=t.jsxs("div",{ref:$d,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:Vs,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(Po,{size:18})}):null,t.jsx(cs,{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(Kt,{size:18})})]}),t.jsx("div",{className:"mission-manager__body",children:v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(rt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(rt,{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:[La&&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:(Ba[f.status]||Ba.planning).bg,color:(Ba[f.status]||Ba.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:B=>lt(f.id,B.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(Fn,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),t.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(Jr[xi]||Jr.inactive).bg,color:(Jr[xi]||Jr.inactive).text},"data-testid":"autopilot-state-badge",children:[La&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),xi]})]}),Ur&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:Ur})]}),t.jsxs("div",{className:"mission-detail__actions",children:[f.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Z(f.id),title:"Stop mission","aria-label":"Stop mission",children:t.jsx(gs,{size:14})}),f.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Da(f.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(wn,{size:14})}),f.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Be(f.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(wn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>si(f),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(ts,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>le({type:"mission",id:f.id}),title:"Delete mission","aria-label":"Delete mission",children:t.jsx(nn,{size:14})})]})]}),w===f.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:C.title,onChange:B=>z({...C,title:B.target.value}),onKeyDown:Mi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:C.description,onChange:B=>z({...C,description:B.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:C.status,onChange:B=>z({...C,status:B.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:B=>z({...C,autopilotEnabled:B.target.checked})}),t.jsx(Fn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:$s,disabled:_,children:[_?t.jsx(rt,{size:14,className:"spinner"}):t.jsx($n,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ks,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 (",En,")"]})]}),Rt==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[f.milestones.map(B=>{const Ce=Xi?.rollup.milestoneId===B.id?Xi:null,De=Ce?.rollup??It.get(B.id),ft=Ce?.validationTelemetry.validationRounds??[],fn=Ce?.fixFeatures??[],Ft=Qu[De?.state??"not_started"]??Qu.not_started,tn=De&&(De.state==="blocked"||De.state==="failed")?Ce?.validationTelemetry.validationRounds.find(He=>He.blockedReason)?.blockedReason:void 0;return t.jsxs("div",{className:"mission-milestone",children:[t.jsxs("div",{className:"mission-milestone__header",onClick:()=>je(B.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:F.has(B.id)?t.jsx(Yt,{size:16}):t.jsx(bn,{size:16})}),t.jsx(Bi,{size:16,className:"mission-milestone__icon"}),t.jsx("span",{className:"mission-milestone__title",children:B.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Ju[B.status].bg,color:Ju[B.status].text},children:B.status}),t.jsxs("span",{className:"mission-milestone__count",children:[B.slices.length," slices"]}),t.jsx(Xu,{state:T1(B.interviewState)}),De&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Ft.bg,color:Ft.text},title:"Validation state",children:Zu(De.state)}),De.totalAssertions>0&&t.jsx("div",{className:"mission-milestone__coverage-bar",title:`${De.passedAssertions??0} of ${De.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${(De.passedAssertions??0)/De.totalAssertions*100}%`,backgroundColor:(De.passedAssertions??0)===De.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),B.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>ze({type:"milestone",id:B.id,title:B.title}),title:"Plan milestone","aria-label":"Plan milestone",children:t.jsx(Ui,{size:14})}),t.jsxs("div",{className:"mission-milestone__actions",onClick:He=>He.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>Je(B.id),title:"Add slice",children:t.jsx(sn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ii(B),title:"Edit milestone",children:t.jsx(ts,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>le({type:"milestone",id:B.id}),title:"Delete milestone",children:t.jsx(nn,{size:14})})]})]}),F.has(B.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(N||I===B.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:Y.title,onChange:He=>ne({...Y,title:He.target.value}),onKeyDown:Zi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:Y.description,onChange:He=>ne({...Y,description:He.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:qs,disabled:_,children:[_?t.jsx(rt,{size:14,className:"spinner"}):t.jsx($n,{size:14}),I?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ms,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}`:""]})]}),tn&&t.jsxs("div",{className:"mission-blocked-reason",children:[t.jsx("strong",{children:"Blocked reason:"})," ",tn]}),ft.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:()=>Dt(He=>!He),title:Gt?"Hide validation rounds":"Show validation rounds",children:[Gt?t.jsx(Yt,{size:12}):t.jsx(bn,{size:12}),"Validation rounds (",ft.length,")"]}),Gt&&t.jsx("div",{className:"mission-validation-rounds__list",children:ft.map(He=>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--${He.validatorStatus}`,children:He.validatorStatus}),t.jsx("span",{className:"mission-validation-round__feature",children:He.featureTitle}),t.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",He.implementationAttempt," · reviewer #",He.validatorAttempt]})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),He.failedAssertionIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:He.failedAssertionIds.map(Ve=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Or(Ve),title:`Jump to assertion ${Ve}`,children:Ve},`${He.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:"}),He.generatedFixFeatureIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:He.generatedFixFeatureIds.map(Ve=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>_i(Ve),title:`Jump to fix feature ${Ve}`,children:Ve},`${He.roundId}-${Ve}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),He.blockedReason&&t.jsx("div",{className:"mission-validation-round__blocked-reason",children:He.blockedReason})]},He.roundId))})]}),fn.length>0&&t.jsxs("div",{className:"mission-fix-features",children:[t.jsx("div",{className:"mission-fix-features__title",children:"Generated Fix Features"}),t.jsx("div",{className:"mission-fix-features__list",children:fn.map(He=>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:()=>_i(He.id),title:`Jump to feature ${He.id}`,children:He.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Gr[He.status].bg,color:Gr[He.status].text},children:He.status}),He.loopState&&t.jsx("span",{className:`mission-loop-state mission-loop-state--${He.loopState}`,children:He.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:()=>_i(He.sourceFeatureId),title:`Jump to source feature ${He.sourceFeatureId}`,children:He.sourceFeatureId}),t.jsx("span",{children:"Run:"}),t.jsx("span",{className:"mission-fix-feature__run",children:He.runId})]}),He.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:He.failedAssertionIds.map(Ve=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Or(Ve),title:`Jump to assertion ${Ve}`,children:Ve},`${He.id}-${Ve}`))})]})]},He.id))})]})]}),t.jsxs("div",{className:"mission-slices",children:[B.slices.map(He=>t.jsxs("div",{className:"mission-slice",children:[t.jsxs("div",{className:"mission-slice__header",onClick:()=>pn(He.id),children:[t.jsx("button",{className:"mission-slice__expand",children:D.has(He.id)?t.jsx(Yt,{size:16}):t.jsx(bn,{size:16})}),t.jsx(Sc,{size:16,className:"mission-slice__icon"}),t.jsx("span",{className:"mission-slice__title",children:He.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Yu[He.status].bg,color:Yu[He.status].text},children:He.status}),t.jsxs("span",{className:"mission-slice__count",children:[He.features?.length||0," features"]}),t.jsx(Xu,{state:He.planState??"not_started"}),He.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>ze({type:"slice",id:He.id,title:He.title}),title:"Plan slice","aria-label":"Plan slice",children:t.jsx(Ui,{size:14})}),t.jsxs("div",{className:"mission-slice__actions",onClick:Ve=>Ve.stopPropagation(),children:[He.status==="pending"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>rn(He.id),title:"Activate slice",children:t.jsx(wn,{size:14})}),He.status==="active"&&He.features?.some(Ve=>Ve.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Zn(He.id),title:"Triage all features",disabled:_,children:_?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Fn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>In(He.id),title:"Add feature",children:t.jsx(sn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>bt(He),title:"Edit slice",children:t.jsx(ts,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>le({type:"slice",id:He.id}),title:"Delete slice",children:t.jsx(nn,{size:14})})]})]}),D.has(He.id)&&t.jsxs("div",{className:"mission-slice__body",children:[ke&&ce===B.id&&!R&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:W.title,onChange:Ve=>K({...W,title:Ve.target.value}),onKeyDown:Ai,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:W.description,onChange:Ve=>K({...W,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:yn,disabled:_,children:[_?t.jsx(rt,{size:14,className:"spinner"}):t.jsx($n,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:gt,children:"Cancel"})]})]}),R===He.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:W.title,onChange:Ve=>K({...W,title:Ve.target.value}),onKeyDown:Ai,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:W.description,onChange:Ve=>K({...W,description:Ve.target.value}),rows:2}),t.jsxs("select",{value:W.status,onChange:Ve=>K({...W,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:yn,disabled:_,children:[_?t.jsx(rt,{size:14,className:"spinner"}):t.jsx($n,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:gt,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-features",children:[He.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:()=>Qi(Ve.id),title:At===Ve.id?"Collapse details":"Expand to show run history",children:At===Ve.id?t.jsx(Yt,{size:14}):t.jsx(bn,{size:14})}),t.jsx(xc,{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:Gr[Ve.status].bg,color:Gr[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:()=>_i(Ve.generatedFromFeatureId),title:`Generated from feature: ${Ve.generatedFromFeatureId}`,children:"🔗 Fix"}),(Ve.loopState==="validating"||Ve.loopState==="needs_fix")&&(()=>{const xt=Mt.get(Ve.id),gn=tl.get(Ve.id),Ss=xt?.implementationAttemptCount??gn?.implementationAttempt??Ve.implementationAttemptCount??0,Ri=xt?.retryBudgetRemaining??Math.max(0,R1-Ss);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",Ss," · ",Ri," ",Ri===1?"retry":"retries"," left"]})})(),Ve.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>Ia(Ve.id),title:"Validate feature",disabled:Tt.has(Ve.id),children:Tt.has(Ve.id)?t.jsx(rt,{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:()=>zn(Ve.id),title:"Triage — create task",disabled:_||Fe===Ve.id,children:Fe===Ve.id?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Fn,{size:14})}),Ve.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>hs(Ve.id),title:"Unlink task",children:t.jsx(Od,{size:14})}):Ve.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>qe(Ve.id),title:"Link to task",children:t.jsx(ga,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>qn(Ve),title:"Edit feature",children:t.jsx(ts,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>le({type:"feature",id:Ve.id}),title:"Delete feature",children:t.jsx(nn,{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]}),me?.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:me.enrichedDescription}),t.jsxs("div",{className:"mission-triage-preview__actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:rs,disabled:_,children:[_?t.jsx(rt,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:ws,disabled:_,children:"Cancel"})]})]}),O===Ve.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:te.title,onChange:xt=>pe({...te,title:xt.target.value}),onKeyDown:ea,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:te.description,onChange:xt=>pe({...te,description:xt.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:te.acceptanceCriteria,onChange:xt=>pe({...te,acceptanceCriteria:xt.target.value}),rows:2}),t.jsxs("select",{value:te.status,onChange:xt=>pe({...te,status:xt.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:_n,disabled:_,children:[_?t.jsx(rt,{size:14,className:"spinner"}):t.jsx($n,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Vn,children:"Cancel"})]})]}),At===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"})}),(fe.get(Ve.id)??[]).map(xt=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>el(xt.id),children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${xt.status}`,title:xt.status,children:xt.status}),t.jsx("span",{className:"mission-run__time",children:new Date(xt.startedAt).toLocaleString()}),xt.completedAt&&t.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(xt.completedAt).getTime()-new Date(xt.startedAt).getTime())/1e3),"s"]}),xt.triggerType&&t.jsx("span",{className:"mission-run__trigger",children:xt.triggerType}),t.jsx("button",{className:"mission-icon-btn",title:M===xt.id?"Hide details":"Show details",children:M===xt.id?t.jsx(Yt,{size:12}):t.jsx(bn,{size:12})})]}),M===xt.id&&Oe.get(xt.id)&&t.jsxs("div",{className:"mission-run__details",children:[xt.summary&&t.jsx("p",{className:"mission-run__summary",children:xt.summary}),xt.blockedReason&&t.jsxs("p",{className:"mission-run__blocked-reason",children:[t.jsx("strong",{children:"Blocked:"})," ",xt.blockedReason]}),Oe.get(xt.id)?.failures&&Oe.get(xt.id).failures.length>0&&t.jsxs("div",{className:"mission-run__failures",children:[t.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),Oe.get(xt.id).failures.map(gn=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:gn.message}),gn.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",gn.expected]}),gn.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",gn.actual]})]},gn.id))]}),(!Oe.get(xt.id)?.failures||Oe.get(xt.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},xt.id)),(!fe.get(Ve.id)||fe.get(Ve.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},Ve.id)),de&&ie===He.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:te.title,onChange:Ve=>pe({...te,title:Ve.target.value}),onKeyDown:ea,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:te.description,onChange:Ve=>pe({...te,description:Ve.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:te.acceptanceCriteria,onChange:Ve=>pe({...te,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:_n,disabled:_,children:[_?t.jsx(rt,{size:14,className:"spinner"}):t.jsx($n,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Vn,children:"Cancel"})]})]}),!de&&(!He.features||He.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(xc,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},He.id)),B.slices.length===0&&!ke&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Sc,{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"}),De&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Ft.bg,color:Ft.text},children:Zu(De.state)}),De&&De.totalAssertions>0&&t.jsx("div",{className:"mission-assertions__coverage-bar",title:`${De.passedAssertions??0} of ${De.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${(De.passedAssertions??0)/De.totalAssertions*100}%`,backgroundColor:(De.passedAssertions??0)===De.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>{ue(!0),We(null),ut({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx(sn,{size:14})})]}),Q&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:Re.title,onChange:He=>ut({...Re,title:He.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:Re.assertion,onChange:He=>ut({...Re,assertion:He.target.value}),rows:2}),t.jsxs("select",{value:Re.status,onChange:He=>ut({...Re,status:He.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"passed",children:"Passed"}),t.jsx("option",{value:"failed",children:"Failed"}),t.jsx("option",{value:"blocked",children:"Blocked"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:()=>Ds(B.id),disabled:_,children:[_?t.jsx(rt,{size:14,className:"spinner"}):t.jsx($n,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ei,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(Te.get(B.id))?Te.get(B.id):[]).map(He=>t.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":He.id,children:[t.jsx("div",{className:"mission-assertion__header",children:Me===He.id?t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:Re.title,onChange:Ve=>ut({...Re,title:Ve.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:Re.assertion,onChange:Ve=>ut({...Re,assertion:Ve.target.value}),rows:2}),t.jsxs("select",{value:Re.status,onChange:Ve=>ut({...Re,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:()=>Lr(He.id,B.id),disabled:_,children:[_?t.jsx(rt,{size:14,className:"spinner"}):t.jsx($n,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ei,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(Yr[He.status]??Yr.pending).bg,color:(Yr[He.status]??Yr.pending).text},children:He.status}),t.jsx("span",{className:"mission-assertion__title",children:He.title}),(()=>{const xt=X.get(He.id)?.length??0;return xt>0?t.jsxs("span",{className:"mission-assertion__linked-count",title:`${xt} linked feature${xt!==1?"s":""}`,children:["(",xt," linked)"]}):null})(),t.jsx("button",{className:"mission-icon-btn",onClick:()=>zr(He.id),title:"Toggle details",children:ye===He.id?t.jsx(Yt,{size:14}):t.jsx(bn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Zo(He),title:"Edit assertion",children:t.jsx(ts,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>le({type:"assertion",id:He.id}),title:"Delete assertion",children:t.jsx(nn,{size:14})})]})}),ye===He.id&&t.jsxs("div",{className:"mission-assertion__body",children:[t.jsx("p",{className:"mission-assertion__text",children:He.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()=>{ye!==He.id&&await zr(He.id),Et(pt===He.id?null:He.id)},title:"Link a feature",children:[t.jsx(ga,{size:12}),"Link Feature"]})]}),pt===He.id&&t.jsx("div",{className:"mission-assertion__feature-picker",children:t.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const Ve=new Set((X.get(He.id)??[]).map(gn=>gn.id)),xt=[];return f?.milestones.forEach(gn=>gn.slices.forEach(Ss=>xt.push(...Ss.features.filter(Ri=>!Ve.has(Ri.id))))),xt.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):xt.map(gn=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>Fr(gn.id,He.id),disabled:ot.has(He.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:gn.title}),ot.has(He.id)&&t.jsx(rt,{size:12,className:"spinner"})]},gn.id))})()})}),(()=>{const Ve=X.get(He.id)??[];return Ve.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):Ve.map(xt=>{const gn=`${xt.id}-${He.id}`,Ss=yt.has(gn);return t.jsxs("div",{className:"mission-assertion__linked-feature",children:[t.jsx("span",{className:"mission-assertion__linked-feature-title",children:xt.title}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Kn(xt.id,He.id),disabled:Ss,title:"Unlink feature",children:Ss?t.jsx(rt,{size:12,className:"spinner"}):t.jsx(Od,{size:12})})]},xt.id)})})()]})]})]},He.id)),(!Te.get(B.id)||Te.get(B.id)?.length===0)&&!Q&&t.jsx("div",{className:"mission-manager__empty mission-assertions__empty",children:t.jsx("span",{children:"No assertions defined. Add one to define completion criteria."})})]})]})]})]})]},B.id)}),f&&!N&&I===null&&t.jsxs("button",{className:"mission-add-btn",onClick:gi,children:[t.jsx(sn,{size:16}),"Add Milestone"]}),N&&I===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:Y.title,onChange:B=>ne({...Y,title:B.target.value}),onKeyDown:Zi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:Y.description,onChange:B=>ne({...Y,description:B.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:qs,disabled:_,children:[_?t.jsx(rt,{size:14,className:"spinner"}):t.jsx($n,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ms,children:"Cancel"})]})]}),f.milestones.length===0&&!N&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Bi,{size:24}),t.jsx("span",{children:"No milestones yet. Add one to get started."})]})]}):t.jsxs("div",{className:"mission-detail__activity","data-testid":"mission-activity-tab",children:[t.jsxs("div",{className:"mission-detail__activity-controls",children:[t.jsxs("label",{className:"mission-detail__activity-filter",children:[t.jsx("span",{children:"Filter"}),t.jsxs("select",{value:Vt,onChange:B=>J(B.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 ",En]})]}),!Lt&&ps&&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:nl,"data-testid":"mission-activity-load-more",children:"Load more"})}),Lt?t.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[t.jsx(rt,{size:18,className:"spinner"}),t.jsx("span",{children:"Loading mission activity..."})]}):mn.length===0?t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Rs,{size:18}),t.jsx("span",{children:"No events yet."})]}):t.jsxs("div",{ref:tt,className:"mission-events","data-testid":"mission-activity-events",children:[mn.map(B=>{const Ce=!!(B.metadata&&Object.keys(B.metadata).length>0),De=Pe.has(B.id);return t.jsxs("div",{className:"mission-event",children:[t.jsxs("div",{className:"mission-event__header",children:[t.jsx("span",{className:`mission-event__type ${L1(B.eventType)}`,children:z1(B.eventType)}),t.jsx("span",{className:"mission-event__time",children:No(B.timestamp)})]}),t.jsx("p",{className:"mission-event__description",children:B.description}),t.jsx("span",{className:"mission-event__timestamp",children:new Date(B.timestamp).toLocaleString()}),Ce&&t.jsxs("div",{className:"mission-event__metadata",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>sl(B.id),"data-testid":`mission-event-metadata-${B.id}`,children:[De?"Hide":"Show"," metadata"]}),De&&t.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(B.metadata,null,2)})]})]},B.id)}),t.jsx("div",{ref:mt})]})]})]}):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:B=>z({...C,title:B.target.value}),onKeyDown:Mi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:C.description,onChange:B=>z({...C,description:B.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:$s,disabled:_,children:[_?t.jsx(rt,{size:14,className:"spinner"}):t.jsx($n,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ks,children:"Cancel"})]})]}),g.map(B=>{const Ce=B,De=f,ft=De&&De.id===Ce.id,fn=Ba[Ce.status]||{bg:"",text:""},Ft=Ce.summary,tn=Nt.get(Ce.id),He=I1(tn),Ve=!!(Ft&&(Ft.totalMilestones>0||Ft.totalFeatures>0)),xt=tn?.totalTasks??0,gn=tn?.tasksCompleted??0,Ss=tn?.tasksFailed??0,Ri=tn?.estimatedCompletionPercent??Ft?.progressPercent??0,Gn=Ve||xt>0||Ss>0||!!tn?.lastActivityAt,Cn=Ce.status==="active"&&(tn?.currentMilestoneId||tn?.currentSliceId)?"Current milestone/slice in progress":null;return t.jsxs("div",{className:`mission-list__item ${ft?"mission-list__item--selected":""}`,onClick:()=>Ot(B),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(cs,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:Ce.title}),B.autopilotEnabled&&t.jsx("span",{title:"Autopilot enabled",children:t.jsx(Fn,{size:12,className:"mission-list__item-autopilot-icon"})}),t.jsx("span",{className:`mission-health-badge mission-health-badge--${He}`,"data-testid":`mission-health-badge-${Ce.id}`,"aria-label":`Mission health: ${He}`}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:fn.bg,color:fn.text},children:Ce.status})]}),Ce.description&&t.jsx("p",{className:"mission-list__item-description",children:Ce.description}),Cn&&t.jsxs("p",{className:"mission-list__item-active-slice",children:["Active: ",Cn]}),Gn&&t.jsxs("div",{className:"mission-list__item-summary",children:[Ve&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[Ft.completedMilestones,"/",Ft.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[Ft.completedFeatures,"/",Ft.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${Ce.id}`,children:[gn,"/",xt," tasks"]}),Ss>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:Wt=>{Wt.stopPropagation(),Ot(B)},"data-testid":`mission-failed-${Ce.id}`,title:"View mission failures",children:[Ss," failed"]}),t.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${Ce.id}`,children:["Activity ",No(tn?.lastActivityAt)]}),t.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${He}`,children:t.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${Ri}%`}})})]})]}),t.jsxs("div",{className:"mission-list__item-actions",onClick:Wt=>Wt.stopPropagation(),children:[Ce.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Z(Ce.id),title:"Stop mission",children:t.jsx(gs,{size:14})}),Ce.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Da(Ce.id),title:"Resume mission",children:t.jsx(wn,{size:14})}),Ce.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Be(Ce.id),title:"Start mission",children:t.jsx(wn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>si(B),title:"Edit mission",children:t.jsx(ts,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>le({type:"mission",id:Ce.id}),title:"Delete mission",children:t.jsx(nn,{size:14})})]})]},Ce.id)}),w&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:C.title,onChange:B=>z({...C,title:B.target.value}),onKeyDown:Mi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:C.description,onChange:B=>z({...C,description:B.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:C.status,onChange:B=>z({...C,status:B.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:B=>z({...C,autopilotEnabled:B.target.checked})}),t.jsx(Fn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:$s,disabled:_,children:[_?t.jsx(rt,{size:14,className:"spinner"}):t.jsx($n,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ks,children:"Cancel"})]})]}),g.length===0&&!k&&t.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large",children:[t.jsx(cs,{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(ss,{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(B=>t.jsxs("button",{className:"mission-add-btn",onClick:()=>{xe(B.id),it(!0),Ke([])},children:[B.status==="error"?t.jsx(Mn,{size:14}):t.jsx(Qn,{size:14}),B.status==="error"?"Retry":"Resume"]},B.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:Is,children:[t.jsx(sn,{size:16}),"New Mission"]})]})]})]})}),we&&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 ",we.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()=>{we.type==="mission"?await Yi(we.id):we.type==="milestone"?await q(we.id):we.type==="slice"?await en(we.id):we.type==="feature"&&await Wn(we.id)},children:"Delete"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>le(null),children:"Cancel"})]})]})}),Le&&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:et,onChange:B=>Xe(B.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(B=>t.jsxs("button",{className:"mission-task-suggestions__item",onClick:()=>Xe(B.id),children:[B.id,": ",B.title||"Untitled"]},B.id))})]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--primary",onClick:Ln,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{qe(null),Xe("")},children:"Cancel"})]})]})})]}),Ns=t.jsx(S1,{isOpen:Ze,onClose:()=>it(!1),onMissionCreated:()=>{an(),i("Mission created from AI interview","success")},projectId:r,resumeSessionId:se}),ri=Ae?t.jsx(_1,{isOpen:!0,onClose:()=>ze(null),onApplied:()=>{ze(null),f&&kt(f.id)},targetType:Ae.type,targetId:Ae.id,targetTitle:Ae.title,missionContext:f?.title,projectId:r,resumeSessionId:Ae.resumeSessionId}):null;return n?t.jsxs(t.Fragment,{children:[il,Ns,ri]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mission-manager-overlay open",onClick:B=>B.target===B.currentTarget&&s(),"data-testid":"mission-manager-overlay",role:"dialog","aria-modal":"true",children:il}),Ns,ri]})}const Qr=2e3;function tm({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<=Qr,S=a.useCallback(async()=>{if(!(!y||f)){x(!0),b(null);try{const A=m==="agent"?"user-to-agent":"system";await Kk({toId:u.trim(),toType:m,content:g.trim(),type:A,...n?{metadata:{replyTo:{messageId:n.messageId}}}:{}},i),r()}catch(A){const w=Se(A)||"Failed to send message";b(w),l?.(w,"error")}finally{x(!1)}}},[y,f,u,m,g,n,i,r,l]),k=a.useCallback(A=>{d(A),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(Kt,{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:A=>k(A.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(A=>t.jsx("option",{value:A.id,children:A.name||A.id},A.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(kn,{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:A=>p(A.target.value),maxLength:Qr,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>Qr?"over-limit":"",children:[g.length,"/",Qr]})})]}),v&&t.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[t.jsx(ss,{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(rt,{size:14,className:"spin"}),t.jsx("span",{children:"Sending…"})]}):t.jsxs(t.Fragment,{children:[t.jsx(Li,{size:14}),t.jsx("span",{children:"Send"})]})})]})]})}function aa(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 U1(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 B1(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 nm(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function H1(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 q1({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),[A,w]=a.useState(null),[E,C]=a.useState(null),[z,_]=a.useState("inbox"),[$,F]=a.useState(null),[V,D]=a.useState([]),T=a.useMemo(()=>new Map(V.map(ie=>[ie.id,ie.name??""])),[V]),I=a.useCallback((ie,Ee)=>U1(ie,Ee,T),[T]),Y=Pr()==="mobile",ne=!Y,N=a.useCallback(async()=>{g(!0);try{const ie=await Vk({limit:50},e);l(ie),m(ie.unreadCount),s?.(ie.unreadCount)}catch{}finally{g(!1)}},[e,s]),P=a.useCallback(async()=>{g(!0);try{const ie=await Wk({limit:50},e);u(ie)}catch{}finally{g(!1)}},[e]),R=a.useCallback(async ie=>{g(!0);try{const Ee=await Xk(ie,e);F(Ee)}catch{}finally{g(!1)}},[e]),j=a.useCallback(async()=>{try{const ie=await Ma(void 0,e);D(ie)}catch{}},[e]),W=a.useCallback(async()=>{try{const ie=await vp(e);m(ie.unreadCount),s?.(ie.unreadCount)}catch{}},[e,s]);a.useEffect(()=>{i==="inbox"?N():i==="outbox"?P():i==="agents"&&j()},[i,N,P,j]),a.useEffect(()=>{E&&R(E)},[E,R]),a.useEffect(()=>{W()},[W]),a.useEffect(()=>{j()},[j]),a.useEffect(()=>{if(typeof EventSource>"u")return;const ie=e?`?projectId=${encodeURIComponent(e)}`:"",Ee=()=>{W(),i==="inbox"?N():i==="outbox"&&P(),E&&R(E)};return Hs(`/api/events${ie}`,{events:{"message:sent":Ee,"message:received":Ee,"message:read":Ee,"message:deleted":Ee}})},[e,i,E,W,N,P,R]);const K=a.useCallback(async ie=>{if(f(ie),!ie.read)try{const Ee=await Gk(ie.id,e);Ee&&l(qe=>qe&&{...qe,messages:qe.messages.map(et=>et.id===Ee.id?Ee:et),unreadCount:Math.max(0,qe.unreadCount-1)});const Le=Math.max(0,d-1);m(Le),s?.(Le)}catch{}try{const Ee=await Qk(ie.fromId,ie.fromType,e);v(Ee)}catch{v([ie])}},[e,d,s]),ke=a.useCallback(()=>{f(null),v([])},[]),be=a.useCallback(async()=>{try{const ie=await Jk(e);m(0),s?.(0),l(Ee=>Ee&&{...Ee,messages:Ee.messages.map(Le=>({...Le,read:!0})),unreadCount:0}),n?.(`Marked ${ie.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[e,n,s]),ce=a.useCallback(async ie=>{try{await Yk(ie,e),f(null),v([]),i==="inbox"?N():i==="outbox"?P():E&&R(E),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,i,E,N,P,R,n]),ve=a.useCallback(ie=>{k({id:ie.fromId,type:ie.fromType}),w({messageId:ie.id,preview:nm(ie.content,120)}),y(!0)},[]),O=a.useCallback(()=>{y(!1),k(null),w(null),n?.("Message sent","success"),i==="outbox"?P():i==="agents"&&E&&R(E),W()},[i,P,E,R,n,W]),oe=a.useCallback(()=>{k(i==="agents"&&E?{id:E,type:"agent"}:null),w(null),y(!0)},[i,E]),te=a.useCallback(()=>{y(!1),k(null),w(null)},[]),pe=()=>!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:[Y&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:ke,"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:B1(p.type)}),t.jsx("span",{className:"mailbox-message-time",children:aa(p.createdAt)})]}),t.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>ve(p),"data-testid":"mailbox-reply",children:[t.jsx(ji,{size:14}),t.jsx("span",{children:"Reply"})]}),t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>ce(p.id),"data-testid":"mailbox-delete",children:[t.jsx(nn,{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(kn,{size:14}):t.jsx(ta,{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(kn,{size:14}):t.jsx(ta,{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(ie=>{const Ee=ie.metadata?.replyTo?.messageId,Le=Ee?x.find(qe=>qe.id===Ee):void 0;return t.jsxs("div",{className:`mailbox-conversation-msg ${ie.id===p.id?"current":""}`,children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:I(ie.fromId,ie.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:aa(ie.createdAt)})]}),Ee&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":`mailbox-reply-context-${ie.id}`,children:["↪ Replying to ",Le?nm(Le.content,60):`message ${Ee}`]}),t.jsx("div",{className:"mailbox-conversation-msg-body",children:ie.content})]},ie.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})]})]}),de=()=>t.jsxs(t.Fragment,{children:[i==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!o&&t.jsx(_l,{}),o&&o.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[t.jsx(sr,{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:H1(o.messages).map(ie=>t.jsxs("div",{className:`mailbox-conversation-group ${ie.unreadCount>0?"unread":""}`,onClick:()=>K(ie.latestMessage),"data-testid":`mailbox-conversation-${ie.key}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ie.fromType==="agent"?t.jsx(kn,{size:16}):t.jsx(ta,{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(ie.fromId,ie.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:aa(ie.latestMessage.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ie.latestMessage.content.slice(0,80),ie.latestMessage.content.length>80?"…":""]})]}),ie.unreadCount>0&&t.jsx("div",{className:"mailbox-group-unread-badge","data-testid":`mailbox-unread-badge-${ie.key}`,children:ie.unreadCount>9?"9+":ie.unreadCount})]},ie.key))})]}),i==="outbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!c&&t.jsx(_l,{}),c&&c.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[t.jsx(Li,{size:32}),t.jsx("p",{children:"No sent messages"})]}),c?.messages.map(ie=>t.jsxs("div",{className:"mailbox-item",onClick:()=>K(ie),"data-testid":`mailbox-item-${ie.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ie.toType==="agent"?t.jsx(kn,{size:16}):t.jsx(ta,{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(ie.toId,ie.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:aa(ie.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ie.content.slice(0,80),ie.content.length>80?"…":""]})]})]},ie.id))]}),i==="agents"&&t.jsx("div",{className:"mailbox-agents","data-testid":"mailbox-agents",children:V.length===0?t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(kn,{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:E??"",onChange:ie=>{C(ie.target.value||null),_("inbox")},"data-testid":"mailbox-agent-select",children:[t.jsx("option",{value:"",children:"Select an agent…"}),V.map(ie=>t.jsx("option",{value:ie.id,children:ie.name||ie.id},ie.id))]})}),t.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:oe,"data-testid":"mailbox-compose-btn",children:[t.jsx(ji,{size:14}),t.jsx("span",{children:"Compose"})]})]}),E&&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:()=>_("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[t.jsx(sr,{size:12}),t.jsx("span",{children:"Inbox"}),$&&$.unreadCount>0&&t.jsx("span",{className:"mailbox-tab-badge",children:$.unreadCount})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${z==="outbox"?"active":""}`,onClick:()=>_("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[t.jsx(Li,{size:12}),t.jsx("span",{children:"Outbox"})]})]}),t.jsxs("div",{className:"mailbox-agents-content",children:[!E&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(kn,{size:32}),t.jsx("p",{children:"Select an agent to view their mailbox"})]}),E&&h&&!$&&t.jsx(_l,{}),E&&$&&z==="inbox"&&$.inbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(sr,{size:32}),t.jsx("p",{children:"No received messages for this agent"})]}),E&&$&&z==="outbox"&&$.outbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Li,{size:32}),t.jsx("p",{children:"No sent messages for this agent"})]}),E&&$&&z==="inbox"&&$.inbox.map(ie=>t.jsxs("div",{className:`mailbox-item ${ie.read?"":"unread"}`,onClick:()=>K(ie),"data-testid":`mailbox-item-${ie.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ie.fromType==="agent"?t.jsx(kn,{size:16}):t.jsx(ta,{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(ie.fromId,ie.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:aa(ie.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ie.content.slice(0,80),ie.content.length>80?"…":""]})]})]},ie.id)),E&&$&&z==="outbox"&&$.outbox.map(ie=>t.jsxs("div",{className:"mailbox-item",onClick:()=>K(ie),"data-testid":`mailbox-item-${ie.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ie.toType==="agent"?t.jsx(kn,{size:16}):t.jsx(ta,{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(ie.toId,ie.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:aa(ie.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ie.content.slice(0,80),ie.content.length>80?"…":""]})]})]},ie.id))]})]})})]}),ge=()=>b?t.jsx(tm,{recipient:S,replyContext:A,agents:V,projectId:e,onSend:O,onCancel:te,addToast:n}):p?pe():t.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[t.jsx(xa,{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(xa,{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:oe,title:"Compose message","data-testid":"mailbox-header-compose",children:[t.jsx(ji,{size:14}),t.jsx("span",{children:"Compose"})]}),i==="inbox"&&d>0&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:be,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[t.jsx(qg,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{i==="inbox"?N():i==="outbox"?P():E&&R(E)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?t.jsx(rt,{size:14,className:"spin"}):t.jsx(Mn,{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(sr,{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(Li,{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(kn,{size:14}),t.jsx("span",{children:"Agents"})]})]}),t.jsx("div",{className:"mailbox-content","data-testid":"mailbox-content",children:ne?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:de()}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:ge()})]}):t.jsxs(t.Fragment,{children:[pe(),b&&t.jsx(tm,{recipient:S,replyContext:A,agents:V,projectId:e,onSend:O,onCancel:te,addToast:n}),!p&&!b&&de()]})})]})}function _l(){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 ti(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 Si(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 V1(e,n){const s={};return(e[e.length-1]===""?[...e,""]:e).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const W1=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,K1=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,G1={};function sm(e,n){return(G1.jsx?K1:W1).test(e)}const J1=/[ \t\n\f\r]/g;function Y1(e){return typeof e=="object"?e.type==="text"?im(e.value):!1:im(e)}function im(e){return e.replace(J1,"")===""}class Ir{constructor(n,s,i){this.normal=s,this.property=n,i&&(this.space=i)}}Ir.prototype.normal={};Ir.prototype.property={};Ir.prototype.space=void 0;function qp(e,n){const s={},i={};for(const r of e)Object.assign(s,r.property),Object.assign(i,r.normal);return new Ir(s,i,n)}function Dc(e){return e.toLowerCase()}class us{constructor(n,s){this.attribute=s,this.property=n}}us.prototype.attribute="";us.prototype.booleanish=!1;us.prototype.boolean=!1;us.prototype.commaOrSpaceSeparated=!1;us.prototype.commaSeparated=!1;us.prototype.defined=!1;us.prototype.mustUseProperty=!1;us.prototype.number=!1;us.prototype.overloadedBoolean=!1;us.prototype.property="";us.prototype.spaceSeparated=!1;us.prototype.space=void 0;let Q1=0;const Ut=Ji(),Tn=Ji(),Lc=Ji(),st=Ji(),xn=Ji(),pa=Ji(),fs=Ji();function Ji(){return 2**++Q1}const zc=Object.freeze(Object.defineProperty({__proto__:null,boolean:Ut,booleanish:Tn,commaOrSpaceSeparated:fs,commaSeparated:pa,number:st,overloadedBoolean:Lc,spaceSeparated:xn},Symbol.toStringTag,{value:"Module"})),Ml=Object.keys(zc);class gd extends us{constructor(n,s,i,r){let o=-1;if(super(n,s),am(this,"space",r),typeof i=="number")for(;++o<Ml.length;){const l=Ml[o];am(this,Ml[o],(i&zc[l])===zc[l])}}}gd.prototype.defined=!0;function am(e,n,s){s&&(e[n]=s)}function Ta(e){const n={},s={};for(const[i,r]of Object.entries(e.properties)){const o=new gd(i,e.transform(e.attributes||{},i),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(i)&&(o.mustUseProperty=!0),n[i]=o,s[Dc(i)]=i,s[Dc(o.attribute)]=i}return new Ir(n,s,e.space)}const Vp=Ta({properties:{ariaActiveDescendant:null,ariaAtomic:Tn,ariaAutoComplete:null,ariaBusy:Tn,ariaChecked:Tn,ariaColCount:st,ariaColIndex:st,ariaColSpan:st,ariaControls:xn,ariaCurrent:null,ariaDescribedBy:xn,ariaDetails:null,ariaDisabled:Tn,ariaDropEffect:xn,ariaErrorMessage:null,ariaExpanded:Tn,ariaFlowTo:xn,ariaGrabbed:Tn,ariaHasPopup:null,ariaHidden:Tn,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:xn,ariaLevel:st,ariaLive:null,ariaModal:Tn,ariaMultiLine:Tn,ariaMultiSelectable:Tn,ariaOrientation:null,ariaOwns:xn,ariaPlaceholder:null,ariaPosInSet:st,ariaPressed:Tn,ariaReadOnly:Tn,ariaRelevant:null,ariaRequired:Tn,ariaRoleDescription:xn,ariaRowCount:st,ariaRowIndex:st,ariaRowSpan:st,ariaSelected:Tn,ariaSetSize:st,ariaSort:null,ariaValueMax:st,ariaValueMin:st,ariaValueNow:st,ariaValueText:null,role:null},transform(e,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function Wp(e,n){return n in e?e[n]:n}function Kp(e,n){return Wp(e,n.toLowerCase())}const X1=Ta({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:pa,acceptCharset:xn,accessKey:xn,action:null,allow:null,allowFullScreen:Ut,allowPaymentRequest:Ut,allowUserMedia:Ut,alt:null,as:null,async:Ut,autoCapitalize:null,autoComplete:xn,autoFocus:Ut,autoPlay:Ut,blocking:xn,capture:null,charSet:null,checked:Ut,cite:null,className:xn,cols:st,colSpan:null,content:null,contentEditable:Tn,controls:Ut,controlsList:xn,coords:st|pa,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Ut,defer:Ut,dir:null,dirName:null,disabled:Ut,download:Lc,draggable:Tn,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Ut,formTarget:null,headers:xn,height:st,hidden:Lc,high:st,href:null,hrefLang:null,htmlFor:xn,httpEquiv:xn,id:null,imageSizes:null,imageSrcSet:null,inert:Ut,inputMode:null,integrity:null,is:null,isMap:Ut,itemId:null,itemProp:xn,itemRef:xn,itemScope:Ut,itemType:xn,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Ut,low:st,manifest:null,max:null,maxLength:st,media:null,method:null,min:null,minLength:st,multiple:Ut,muted:Ut,name:null,nonce:null,noModule:Ut,noValidate:Ut,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:Ut,optimum:st,pattern:null,ping:xn,placeholder:null,playsInline:Ut,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Ut,referrerPolicy:null,rel:xn,required:Ut,reversed:Ut,rows:st,rowSpan:st,sandbox:xn,scope:null,scoped:Ut,seamless:Ut,selected:Ut,shadowRootClonable:Ut,shadowRootDelegatesFocus:Ut,shadowRootMode:null,shape:null,size:st,sizes:null,slot:null,span:st,spellCheck:Tn,src:null,srcDoc:null,srcLang:null,srcSet:null,start:st,step:null,style:null,tabIndex:st,target:null,title:null,translate:null,type:null,typeMustMatch:Ut,useMap:null,value:Tn,width:st,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:xn,axis:null,background:null,bgColor:null,border:st,borderColor:null,bottomMargin:st,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:Ut,declare:Ut,event:null,face:null,frame:null,frameBorder:null,hSpace:st,leftMargin:st,link:null,longDesc:null,lowSrc:null,marginHeight:st,marginWidth:st,noResize:Ut,noHref:Ut,noShade:Ut,noWrap:Ut,object:null,profile:null,prompt:null,rev:null,rightMargin:st,rules:null,scheme:null,scrolling:Tn,standby:null,summary:null,text:null,topMargin:st,valueType:null,version:null,vAlign:null,vLink:null,vSpace:st,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:Ut,disableRemotePlayback:Ut,prefix:null,property:null,results:st,security:null,unselectable:null},space:"html",transform:Kp}),Z1=Ta({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:fs,accentHeight:st,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:st,amplitude:st,arabicForm:null,ascent:st,attributeName:null,attributeType:null,azimuth:st,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:st,by:null,calcMode:null,capHeight:st,className:xn,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:st,diffuseConstant:st,direction:null,display:null,dur:null,divisor:st,dominantBaseline:null,download:Ut,dx:null,dy:null,edgeMode:null,editable:null,elevation:st,enableBackground:null,end:null,event:null,exponent:st,externalResourcesRequired:null,fill:null,fillOpacity:st,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:pa,g2:pa,glyphName:pa,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:st,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:st,horizOriginX:st,horizOriginY:st,id:null,ideographic:st,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:st,k:st,k1:st,k2:st,k3:st,k4:st,kernelMatrix:fs,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:st,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:st,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:st,overlineThickness:st,paintOrder:null,panose1:null,path:null,pathLength:st,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:xn,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:st,pointsAtY:st,pointsAtZ:st,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:fs,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:fs,rev:fs,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:fs,requiredFeatures:fs,requiredFonts:fs,requiredFormats:fs,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:st,specularExponent:st,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:st,strikethroughThickness:st,string:null,stroke:null,strokeDashArray:fs,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:st,strokeOpacity:st,strokeWidth:null,style:null,surfaceScale:st,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:fs,tabIndex:st,tableValues:null,target:null,targetX:st,targetY:st,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:fs,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:st,underlineThickness:st,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:st,values:null,vAlphabetic:st,vMathematical:st,vectorEffect:null,vHanging:st,vIdeographic:st,version:null,vertAdvY:st,vertOriginX:st,vertOriginY:st,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:st,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Wp}),Gp=Ta({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()}}),Jp=Ta({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Kp}),Yp=Ta({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),e0={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"},t0=/[A-Z]/g,rm=/-[a-z]/g,n0=/^data[-\w.:]+$/i;function s0(e,n){const s=Dc(n);let i=n,r=us;if(s in e.normal)return e.property[e.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&n0.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(rm,a0);i="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!rm.test(o)){let l=o.replace(t0,i0);l.charAt(0)!=="-"&&(l="-"+l),n="data"+l}}r=gd}return new r(i,n)}function i0(e){return"-"+e.toLowerCase()}function a0(e){return e.charAt(1).toUpperCase()}const r0=qp([Vp,X1,Gp,Jp,Yp],"html"),xd=qp([Vp,Z1,Gp,Jp,Yp],"svg");function o0(e){return e.join(" ").trim()}var ra={},Al,om;function l0(){if(om)return Al;om=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(D){var T=D.match(n);T&&(y+=T.length);var I=D.lastIndexOf(u);S=~I?D.length-I:S+D.length}function A(){var D={line:y,column:S};return function(T){return T.position=new w(D),z(),T}}function w(D){this.start=D,this.end={line:y,column:S},this.source=b.source}w.prototype.content=v;function E(D){var T=new Error(b.source+":"+y+":"+S+": "+D);if(T.reason=D,T.filename=b.source,T.line=y,T.column=S,T.source=v,!b.silent)throw T}function C(D){var T=D.exec(v);if(T){var I=T[0];return k(I),v=v.slice(I.length),T}}function z(){C(s)}function _(D){var T;for(D=D||[];T=$();)T!==!1&&D.push(T);return D}function $(){var D=A();if(!(d!=v.charAt(0)||m!=v.charAt(1))){for(var T=2;h!=v.charAt(T)&&(m!=v.charAt(T)||d!=v.charAt(T+1));)++T;if(T+=2,h===v.charAt(T-1))return E("End of comment missing");var I=v.slice(2,T-2);return S+=2,k(I),v=v.slice(T),S+=2,D({type:g,comment:I})}}function F(){var D=A(),T=C(i);if(T){if($(),!C(r))return E("property missing ':'");var I=C(o),U=D({type:p,property:x(T[0].replace(e,h)),value:I?x(I[0].replace(e,h)):h});return C(l),U}}function V(){var D=[];_(D);for(var T;T=F();)T!==!1&&(D.push(T),_(D));return D}return z(),V()}function x(v){return v?v.replace(c,h):h}return Al=f,Al}var lm;function c0(){if(lm)return ra;lm=1;var e=ra&&ra.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(ra,"__esModule",{value:!0}),ra.default=s;const n=e(l0());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 ra}var Ha={},cm;function d0(){if(cm)return Ha;cm=1,Object.defineProperty(Ha,"__esModule",{value:!0}),Ha.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 Ha.camelCase=u,Ha}var qa,dm;function u0(){if(dm)return qa;dm=1;var e=qa&&qa.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=e(c0()),s=d0();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,qa=i,qa}var m0=u0();const h0=Bh(m0),Qp=Xp("end"),bd=Xp("start");function Xp(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 p0(e){const n=bd(e),s=Qp(e);if(n&&s)return{start:n,end:s}}function cr(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?um(e.position):"start"in e||"end"in e?um(e):"line"in e||"column"in e?Oc(e):""}function Oc(e){return mm(e&&e.line)+":"+mm(e&&e.column)}function um(e){return Oc(e&&e.start)+"-"+Oc(e&&e.end)}function mm(e){return e&&typeof e=="number"?e:1}class Xn 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=cr(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}}Xn.prototype.file="";Xn.prototype.name="";Xn.prototype.reason="";Xn.prototype.message="";Xn.prototype.stack="";Xn.prototype.column=void 0;Xn.prototype.line=void 0;Xn.prototype.ancestors=void 0;Xn.prototype.cause=void 0;Xn.prototype.fatal=void 0;Xn.prototype.place=void 0;Xn.prototype.ruleId=void 0;Xn.prototype.source=void 0;const vd={}.hasOwnProperty,f0=new Map,g0=/[A-Z]/g,x0=new Set(["table","tbody","thead","tfoot","tr"]),b0=new Set(["td","th"]),Zp="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function v0(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=E0(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=C0(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"?xd:r0,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=ef(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function ef(e,n,s){if(n.type==="element")return y0(e,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return j0(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return w0(e,n,s);if(n.type==="mdxjsEsm")return k0(e,n);if(n.type==="root")return N0(e,n,s);if(n.type==="text")return S0(e,n)}function y0(e,n,s){const i=e.schema;let r=i;n.tagName.toLowerCase()==="svg"&&i.space==="html"&&(r=xd,e.schema=r),e.ancestors.push(n);const o=nf(e,n.tagName,!1),l=_0(e,n);let c=jd(e,n);return x0.has(n.tagName)&&(c=c.filter(function(u){return typeof u=="string"?!Y1(u):!0})),tf(e,l,o,n),yd(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function j0(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)}jr(e,n.position)}function k0(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);jr(e,n.position)}function w0(e,n,s){const i=e.schema;let r=i;n.name==="svg"&&i.space==="html"&&(r=xd,e.schema=r),e.ancestors.push(n);const o=n.name===null?e.Fragment:nf(e,n.name,!0),l=M0(e,n),c=jd(e,n);return tf(e,l,o,n),yd(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function N0(e,n,s){const i={};return yd(i,jd(e,n)),e.create(n,e.Fragment,i,s)}function S0(e,n){return n.value}function tf(e,n,s,i){typeof s!="string"&&s!==e.Fragment&&e.passNode&&(n.node=i)}function yd(e,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(e.children=s)}}function C0(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 E0(e,n){return s;function s(i,r,o,l){const c=Array.isArray(o.children),u=bd(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 _0(e,n){const s={};let i,r;for(r in n.properties)if(r!=="children"&&vd.call(n.properties,r)){const o=A0(e,r,n.properties[r]);if(o){const[l,c]=o;e.tableCellAlignToStyle&&l==="align"&&typeof c=="string"&&b0.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 M0(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 jr(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 jr(e,n.position);else o=i.value===null?!0:i.value;s[r]=o}return s}function jd(e,n){const s=[];let i=-1;const r=e.passKeys?new Map:f0;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=ef(e,o,l);c!==void 0&&s.push(c)}return s}function A0(e,n,s){const i=s0(e.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=i.commaSeparated?V1(s):o0(s)),i.property==="style"){let r=typeof s=="object"?s:R0(e,String(s));return e.stylePropertyNameCase==="css"&&(r=T0(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&i.space?e0[i.property]||i.property:i.attribute,s]}}function R0(e,n){try{return h0(n,{reactCompat:!0})}catch(s){if(e.ignoreInvalidStyle)return{};const i=s,r=new Xn("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=Zp+"#cannot-parse-style-attribute",r}}function nf(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=sm(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=sm(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(i.type==="Literal"){const r=i.value;return vd.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(i);jr(e)}function jr(e,n){const s=new Xn("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=Zp+"#cannot-handle-mdx-estrees-without-createevaluater",s}function T0(e){const n={};let s;for(s in e)vd.call(e,s)&&(n[P0(s)]=e[s]);return n}function P0(e){let n=e.replace(g0,I0);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function I0(e){return"-"+e.toLowerCase()}const Rl={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"]},$0={};function kd(e,n){const s=$0,i=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return sf(e,i,r)}function sf(e,n,s){if(D0(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 hm(e.children,n,s)}return Array.isArray(e)?hm(e,n,s):""}function hm(e,n,s){const i=[];let r=-1;for(;++r<e.length;)i[r]=sf(e[r],n,s);return i.join("")}function D0(e){return!!(e&&typeof e=="object")}const pm=document.createElement("i");function wd(e){const n="&"+e+";";pm.innerHTML=n;const s=pm.textContent;return s.charCodeAt(s.length-1)===59&&e!=="semi"||s===n?!1:s}function vs(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 Ms(e,n){return e.length>0?(vs(e,e.length,0,n),e):n}const fm={}.hasOwnProperty;function af(e){const n={};let s=-1;for(;++s<e.length;)L0(n,e[s]);return n}function L0(e,n){let s;for(s in n){const r=(fm.call(e,s)?e[s]:void 0)||(e[s]={}),o=n[s];let l;if(o)for(l in o){fm.call(r,l)||(r[l]=[]);const c=o[l];z0(r[l],Array.isArray(c)?c:c?[c]:[])}}}function z0(e,n){let s=-1;const i=[];for(;++s<n.length;)(n[s].add==="after"?e:i).push(n[s]);vs(e,0,0,i)}function rf(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 Us(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const ns=Ci(/[A-Za-z]/),Yn=Ci(/[\dA-Za-z]/),O0=Ci(/[#-'*+\--9=?A-Z^-~]/);function So(e){return e!==null&&(e<32||e===127)}const Fc=Ci(/\d/),F0=Ci(/[\dA-Fa-f]/),U0=Ci(/[!-/:-@[-`{-~]/);function wt(e){return e!==null&&e<-2}function dn(e){return e!==null&&(e<0||e===32)}function Jt(e){return e===-2||e===-1||e===32}const Go=Ci(/\p{P}|\p{S}/u),Vi=Ci(/\s/);function Ci(e){return n;function n(s){return s!==null&&s>-1&&e.test(String.fromCharCode(s))}}function Pa(e){const n=[];let s=-1,i=0,r=0;for(;++s<e.length;){const o=e.charCodeAt(s);let l="";if(o===37&&Yn(e.charCodeAt(s+1))&&Yn(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 Xt(e,n,s,i){const r=i?i-1:Number.POSITIVE_INFINITY;let o=0;return l;function l(u){return Jt(u)?(e.enter(s),c(u)):n(u)}function c(u){return Jt(u)&&o++<r?(e.consume(u),c):(e.exit(s),n(u))}}const B0={tokenize:H0};function H0(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"),Xt(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 wt(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),l)}}const q0={tokenize:V0},gm={tokenize:W0};function V0(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 A=k,w;for(;A--;)if(n.events[A][0]==="exit"&&n.events[A][1].type==="chunkFlow"){w=n.events[A][1].end;break}b(i);let E=k;for(;E<n.events.length;)n.events[E][1].end={...w},E++;return vs(n.events,A+1,0,n.events.slice(k)),n.events.length=E,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(gm,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(gm,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 wt(S)?(e.consume(S),v(e.exit("chunkFlow")),i=0,n.interrupt=void 0,c):(e.consume(S),x)}function v(S,k){const A=n.sliceStream(S);if(k&&A.push(null),S.previous=o,o&&(o.next=S),o=S,r.defineSkip(S.start),r.write(A),n.parser.lazy[S.start.line]){let w=r.events.length;for(;w--;)if(r.events[w][1].start.offset<l&&(!r.events[w][1].end||r.events[w][1].end.offset>l))return;const E=n.events.length;let C=E,z,_;for(;C--;)if(n.events[C][0]==="exit"&&n.events[C][1].type==="chunkFlow"){if(z){_=n.events[C][1].end;break}z=!0}for(b(i),w=E;w<n.events.length;)n.events[w][1].end={..._},w++;vs(n.events,C+1,0,n.events.slice(E)),n.events.length=w}}function b(S){let k=s.length;for(;k-- >S;){const A=s[k];n.containerState=A[1],A[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 W0(e,n,s){return Xt(e,e.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function ja(e){if(e===null||dn(e)||Vi(e))return 1;if(Go(e))return 2}function Jo(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 Uc={name:"attention",resolveAll:K0,tokenize:G0};function K0(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};xm(h,-u),xm(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=Ms(d,[["enter",e[i][1],n],["exit",e[i][1],n]])),d=Ms(d,[["enter",r,n],["enter",l,n],["exit",l,n],["enter",o,n]]),d=Ms(d,Jo(n.parser.constructs.insideSpan.null,e.slice(i+1,s),n)),d=Ms(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=Ms(d,[["enter",e[s][1],n],["exit",e[s][1],n]])):m=0,vs(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 G0(e,n){const s=this.parser.constructs.attentionMarkers.null,i=this.previous,r=ja(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=ja(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 xm(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const J0={name:"autolink",tokenize:Y0};function Y0(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 ns(p)?(e.consume(p),l):p===64?s(p):d(p)}function l(p){return p===43||p===45||p===46||Yn(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||Yn(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||So(p)?s(p):(e.consume(p),u)}function d(p){return p===64?(e.consume(p),m):O0(p)?(e.consume(p),d):s(p)}function m(p){return Yn(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||Yn(p))&&i++<63){const f=p===45?g:h;return e.consume(p),f}return s(p)}}const $r={partial:!0,tokenize:Q0};function Q0(e,n,s){return i;function i(o){return Jt(o)?Xt(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||wt(o)?n(o):s(o)}}const of={continuation:{tokenize:Z0},exit:eS,name:"blockQuote",tokenize:X0};function X0(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 Jt(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(l))}}function Z0(e,n,s){const i=this;return r;function r(l){return Jt(l)?Xt(e,o,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(of,n,s)(l)}}function eS(e){e.exit("blockQuote")}const lf={name:"characterEscape",tokenize:tS};function tS(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 U0(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):s(o)}}const cf={name:"characterReference",tokenize:nS};function nS(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=Yn,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=F0,m):(e.enter("characterReferenceValue"),o=7,l=Fc,m(h))}function m(h){if(h===59&&r){const g=e.exit("characterReferenceValue");return l===Yn&&!wd(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 bm={partial:!0,tokenize:iS},vm={concrete:!0,name:"codeFenced",tokenize:sS};function sS(e,n,s){const i=this,r={partial:!0,tokenize:A};let o=0,l=0,c;return u;function u(w){return d(w)}function d(w){const E=i.events[i.events.length-1];return o=E&&E[1].type==="linePrefix"?E[2].sliceSerialize(E[1],!0).length:0,c=w,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),m(w)}function m(w){return w===c?(l++,e.consume(w),m):l<3?s(w):(e.exit("codeFencedFenceSequence"),Jt(w)?Xt(e,h,"whitespace")(w):h(w))}function h(w){return w===null||wt(w)?(e.exit("codeFencedFence"),i.interrupt?n(w):e.check(bm,x,k)(w)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),g(w))}function g(w){return w===null||wt(w)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(w)):Jt(w)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),Xt(e,p,"whitespace")(w)):w===96&&w===c?s(w):(e.consume(w),g)}function p(w){return w===null||wt(w)?h(w):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),f(w))}function f(w){return w===null||wt(w)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),h(w)):w===96&&w===c?s(w):(e.consume(w),f)}function x(w){return e.attempt(r,k,v)(w)}function v(w){return e.enter("lineEnding"),e.consume(w),e.exit("lineEnding"),b}function b(w){return o>0&&Jt(w)?Xt(e,y,"linePrefix",o+1)(w):y(w)}function y(w){return w===null||wt(w)?e.check(bm,x,k)(w):(e.enter("codeFlowValue"),S(w))}function S(w){return w===null||wt(w)?(e.exit("codeFlowValue"),y(w)):(e.consume(w),S)}function k(w){return e.exit("codeFenced"),n(w)}function A(w,E,C){let z=0;return _;function _(T){return w.enter("lineEnding"),w.consume(T),w.exit("lineEnding"),$}function $(T){return w.enter("codeFencedFence"),Jt(T)?Xt(w,F,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(T):F(T)}function F(T){return T===c?(w.enter("codeFencedFenceSequence"),V(T)):C(T)}function V(T){return T===c?(z++,w.consume(T),V):z>=l?(w.exit("codeFencedFenceSequence"),Jt(T)?Xt(w,D,"whitespace")(T):D(T)):C(T)}function D(T){return T===null||wt(T)?(w.exit("codeFencedFence"),E(T)):C(T)}}}function iS(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 Tl={name:"codeIndented",tokenize:rS},aS={partial:!0,tokenize:oS};function rS(e,n,s){const i=this;return r;function r(d){return e.enter("codeIndented"),Xt(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):wt(d)?e.attempt(aS,l,u)(d):(e.enter("codeFlowValue"),c(d))}function c(d){return d===null||wt(d)?(e.exit("codeFlowValue"),l(d)):(e.consume(d),c)}function u(d){return e.exit("codeIndented"),n(d)}}function oS(e,n,s){const i=this;return r;function r(l){return i.parser.lazy[i.now().line]?s(l):wt(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r):Xt(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):wt(l)?r(l):s(l)}}const lS={name:"codeText",previous:dS,resolve:cS,tokenize:uS};function cS(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 dS(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function uS(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)):wt(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||wt(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 mS{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&&Va(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),Va(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),Va(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);Va(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);Va(this.left,s.reverse())}}}function Va(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 df(e){const n={};let s=-1,i,r,o,l,c,u,d;const m=new mS(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,hS(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 vs(e,0,Number.POSITIVE_INFINITY,m.slice(0)),!d}function hS(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 pS={resolve:gS,tokenize:xS},fS={partial:!0,tokenize:bS};function gS(e){return df(e),e}function xS(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):wt(c)?e.check(fS,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 bS(e,n,s){const i=this;return r;function r(l){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),Xt(e,o,"linePrefix")}function o(l){if(l===null||wt(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 uf(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||So(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||wt(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||dn(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||So(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 mf(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):wt(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),m):(e.enter("chunkString",{contentType:"string"}),h(p))}function h(p){return p===null||p===91||p===93||wt(p)||c++>999?(e.exit("chunkString"),m(p)):(e.consume(p),u||(u=!Jt(p)),p===92?g:h)}function g(p){return p===91||p===92||p===93?(e.consume(p),c++,h):h(p)}}function hf(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):wt(g)?(e.enter("lineEnding"),e.consume(g),e.exit("lineEnding"),Xt(e,d,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),m(g))}function m(g){return g===l||g===null||wt(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 dr(e,n){let s;return i;function i(r){return wt(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s=!0,i):Jt(r)?Xt(e,i,s?"linePrefix":"lineSuffix")(r):n(r)}}const vS={name:"definition",tokenize:jS},yS={partial:!0,tokenize:kS};function jS(e,n,s){const i=this;let r;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return mf.call(i,e,c,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function c(p){return r=Us(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 dn(p)?dr(e,d)(p):d(p)}function d(p){return uf(e,m,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function m(p){return e.attempt(yS,h,h)(p)}function h(p){return Jt(p)?Xt(e,g,"whitespace")(p):g(p)}function g(p){return p===null||wt(p)?(e.exit("definition"),i.parser.defined.push(r),n(p)):s(p)}}function kS(e,n,s){return i;function i(c){return dn(c)?dr(e,r)(c):s(c)}function r(c){return hf(e,o,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return Jt(c)?Xt(e,l,"whitespace")(c):l(c)}function l(c){return c===null||wt(c)?n(c):s(c)}}const wS={name:"hardBreakEscape",tokenize:NS};function NS(e,n,s){return i;function i(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return wt(o)?(e.exit("hardBreakEscape"),n(o)):s(o)}}const SS={name:"headingAtx",resolve:CS,tokenize:ES};function CS(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"},vs(e,i,s-i+1,[["enter",r,n],["enter",o,n],["exit",o,n],["exit",r,n]])),e}function ES(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||dn(m)?(e.exit("atxHeadingSequence"),c(m)):s(m)}function c(m){return m===35?(e.enter("atxHeadingSequence"),u(m)):m===null||wt(m)?(e.exit("atxHeading"),n(m)):Jt(m)?Xt(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||dn(m)?(e.exit("atxHeadingText"),c(m)):(e.consume(m),d)}}const _S=["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"],ym=["pre","script","style","textarea"],MS={concrete:!0,name:"htmlFlow",resolveTo:TS,tokenize:PS},AS={partial:!0,tokenize:$S},RS={partial:!0,tokenize:IS};function TS(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 PS(e,n,s){const i=this;let r,o,l,c,u;return d;function d(j){return m(j)}function m(j){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(j),h}function h(j){return j===33?(e.consume(j),g):j===47?(e.consume(j),o=!0,x):j===63?(e.consume(j),r=3,i.interrupt?n:N):ns(j)?(e.consume(j),l=String.fromCharCode(j),v):s(j)}function g(j){return j===45?(e.consume(j),r=2,p):j===91?(e.consume(j),r=5,c=0,f):ns(j)?(e.consume(j),r=4,i.interrupt?n:N):s(j)}function p(j){return j===45?(e.consume(j),i.interrupt?n:N):s(j)}function f(j){const W="CDATA[";return j===W.charCodeAt(c++)?(e.consume(j),c===W.length?i.interrupt?n:F:f):s(j)}function x(j){return ns(j)?(e.consume(j),l=String.fromCharCode(j),v):s(j)}function v(j){if(j===null||j===47||j===62||dn(j)){const W=j===47,K=l.toLowerCase();return!W&&!o&&ym.includes(K)?(r=1,i.interrupt?n(j):F(j)):_S.includes(l.toLowerCase())?(r=6,W?(e.consume(j),b):i.interrupt?n(j):F(j)):(r=7,i.interrupt&&!i.parser.lazy[i.now().line]?s(j):o?y(j):S(j))}return j===45||Yn(j)?(e.consume(j),l+=String.fromCharCode(j),v):s(j)}function b(j){return j===62?(e.consume(j),i.interrupt?n:F):s(j)}function y(j){return Jt(j)?(e.consume(j),y):_(j)}function S(j){return j===47?(e.consume(j),_):j===58||j===95||ns(j)?(e.consume(j),k):Jt(j)?(e.consume(j),S):_(j)}function k(j){return j===45||j===46||j===58||j===95||Yn(j)?(e.consume(j),k):A(j)}function A(j){return j===61?(e.consume(j),w):Jt(j)?(e.consume(j),A):S(j)}function w(j){return j===null||j===60||j===61||j===62||j===96?s(j):j===34||j===39?(e.consume(j),u=j,E):Jt(j)?(e.consume(j),w):C(j)}function E(j){return j===u?(e.consume(j),u=null,z):j===null||wt(j)?s(j):(e.consume(j),E)}function C(j){return j===null||j===34||j===39||j===47||j===60||j===61||j===62||j===96||dn(j)?A(j):(e.consume(j),C)}function z(j){return j===47||j===62||Jt(j)?S(j):s(j)}function _(j){return j===62?(e.consume(j),$):s(j)}function $(j){return j===null||wt(j)?F(j):Jt(j)?(e.consume(j),$):s(j)}function F(j){return j===45&&r===2?(e.consume(j),I):j===60&&r===1?(e.consume(j),U):j===62&&r===4?(e.consume(j),P):j===63&&r===3?(e.consume(j),N):j===93&&r===5?(e.consume(j),ne):wt(j)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(AS,R,V)(j)):j===null||wt(j)?(e.exit("htmlFlowData"),V(j)):(e.consume(j),F)}function V(j){return e.check(RS,D,R)(j)}function D(j){return e.enter("lineEnding"),e.consume(j),e.exit("lineEnding"),T}function T(j){return j===null||wt(j)?V(j):(e.enter("htmlFlowData"),F(j))}function I(j){return j===45?(e.consume(j),N):F(j)}function U(j){return j===47?(e.consume(j),l="",Y):F(j)}function Y(j){if(j===62){const W=l.toLowerCase();return ym.includes(W)?(e.consume(j),P):F(j)}return ns(j)&&l.length<8?(e.consume(j),l+=String.fromCharCode(j),Y):F(j)}function ne(j){return j===93?(e.consume(j),N):F(j)}function N(j){return j===62?(e.consume(j),P):j===45&&r===2?(e.consume(j),N):F(j)}function P(j){return j===null||wt(j)?(e.exit("htmlFlowData"),R(j)):(e.consume(j),P)}function R(j){return e.exit("htmlFlow"),n(j)}}function IS(e,n,s){const i=this;return r;function r(l){return wt(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),o):s(l)}function o(l){return i.parser.lazy[i.now().line]?s(l):n(l)}}function $S(e,n,s){return i;function i(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt($r,n,s)}}const DS={name:"htmlText",tokenize:LS};function LS(e,n,s){const i=this;let r,o,l;return c;function c(N){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(N),u}function u(N){return N===33?(e.consume(N),d):N===47?(e.consume(N),A):N===63?(e.consume(N),S):ns(N)?(e.consume(N),C):s(N)}function d(N){return N===45?(e.consume(N),m):N===91?(e.consume(N),o=0,f):ns(N)?(e.consume(N),y):s(N)}function m(N){return N===45?(e.consume(N),p):s(N)}function h(N){return N===null?s(N):N===45?(e.consume(N),g):wt(N)?(l=h,U(N)):(e.consume(N),h)}function g(N){return N===45?(e.consume(N),p):h(N)}function p(N){return N===62?I(N):N===45?g(N):h(N)}function f(N){const P="CDATA[";return N===P.charCodeAt(o++)?(e.consume(N),o===P.length?x:f):s(N)}function x(N){return N===null?s(N):N===93?(e.consume(N),v):wt(N)?(l=x,U(N)):(e.consume(N),x)}function v(N){return N===93?(e.consume(N),b):x(N)}function b(N){return N===62?I(N):N===93?(e.consume(N),b):x(N)}function y(N){return N===null||N===62?I(N):wt(N)?(l=y,U(N)):(e.consume(N),y)}function S(N){return N===null?s(N):N===63?(e.consume(N),k):wt(N)?(l=S,U(N)):(e.consume(N),S)}function k(N){return N===62?I(N):S(N)}function A(N){return ns(N)?(e.consume(N),w):s(N)}function w(N){return N===45||Yn(N)?(e.consume(N),w):E(N)}function E(N){return wt(N)?(l=E,U(N)):Jt(N)?(e.consume(N),E):I(N)}function C(N){return N===45||Yn(N)?(e.consume(N),C):N===47||N===62||dn(N)?z(N):s(N)}function z(N){return N===47?(e.consume(N),I):N===58||N===95||ns(N)?(e.consume(N),_):wt(N)?(l=z,U(N)):Jt(N)?(e.consume(N),z):I(N)}function _(N){return N===45||N===46||N===58||N===95||Yn(N)?(e.consume(N),_):$(N)}function $(N){return N===61?(e.consume(N),F):wt(N)?(l=$,U(N)):Jt(N)?(e.consume(N),$):z(N)}function F(N){return N===null||N===60||N===61||N===62||N===96?s(N):N===34||N===39?(e.consume(N),r=N,V):wt(N)?(l=F,U(N)):Jt(N)?(e.consume(N),F):(e.consume(N),D)}function V(N){return N===r?(e.consume(N),r=void 0,T):N===null?s(N):wt(N)?(l=V,U(N)):(e.consume(N),V)}function D(N){return N===null||N===34||N===39||N===60||N===61||N===96?s(N):N===47||N===62||dn(N)?z(N):(e.consume(N),D)}function T(N){return N===47||N===62||dn(N)?z(N):s(N)}function I(N){return N===62?(e.consume(N),e.exit("htmlTextData"),e.exit("htmlText"),n):s(N)}function U(N){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(N),e.exit("lineEnding"),Y}function Y(N){return Jt(N)?Xt(e,ne,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(N):ne(N)}function ne(N){return e.enter("htmlTextData"),l(N)}}const Nd={name:"labelEnd",resolveAll:US,resolveTo:BS,tokenize:HS},zS={tokenize:qS},OS={tokenize:VS},FS={tokenize:WS};function US(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&&vs(e,0,e.length,s),e}function BS(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=Ms(c,e.slice(o+1,o+i+3)),c=Ms(c,[["enter",m,n]]),c=Ms(c,Jo(n.parser.constructs.insideSpan.null,e.slice(o+i+4,l-3),n)),c=Ms(c,[["exit",m,n],e[l-2],e[l-1],["exit",d,n]]),c=Ms(c,e.slice(l+1)),c=Ms(c,[["exit",u,n]]),vs(e,o,e.length,c),e}function HS(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(Us(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(zS,m,l?m:h)(g):g===91?e.attempt(OS,m,l?d:h)(g):l?m(g):h(g)}function d(g){return e.attempt(FS,m,h)(g)}function m(g){return n(g)}function h(g){return o._balanced=!0,s(g)}}function qS(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 dn(h)?dr(e,o)(h):o(h)}function o(h){return h===41?m(h):uf(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function l(h){return dn(h)?dr(e,u)(h):m(h)}function c(h){return s(h)}function u(h){return h===34||h===39||h===40?hf(e,d,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):m(h)}function d(h){return dn(h)?dr(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 VS(e,n,s){const i=this;return r;function r(c){return mf.call(i,e,o,l,"reference","referenceMarker","referenceString")(c)}function o(c){return i.parser.defined.includes(Us(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)))?n(c):s(c)}function l(c){return s(c)}}function WS(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 KS={name:"labelStartImage",resolveAll:Nd.resolveAll,tokenize:GS};function GS(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 JS={name:"labelStartLink",resolveAll:Nd.resolveAll,tokenize:YS};function YS(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 Pl={name:"lineEnding",tokenize:QS};function QS(e,n){return s;function s(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),Xt(e,n,"linePrefix")}}const mo={name:"thematicBreak",tokenize:XS};function XS(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||wt(d))?(e.exit("thematicBreak"),n(d)):s(d)}function u(d){return d===r?(e.consume(d),i++,u):(e.exit("thematicBreakSequence"),Jt(d)?Xt(e,c,"whitespace")(d):c(d))}}const os={continuation:{tokenize:nC},exit:iC,name:"list",tokenize:tC},ZS={partial:!0,tokenize:aC},eC={partial:!0,tokenize:sC};function tC(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:Fc(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(mo,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 Fc(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(ZS,g,h))}function m(p){return i.containerState.initialBlankLine=!0,o++,g(p)}function h(p){return Jt(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 nC(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,Xt(e,n,"listItemIndent",i.containerState.size+1)(c)}function o(c){return i.containerState.furtherBlankLines||!Jt(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(eC,n,l)(c))}function l(c){return i.containerState._closeFlow=!0,i.interrupt=void 0,Xt(e,e.attempt(os,n,s),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function sC(e,n,s){const i=this;return Xt(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 iC(e){e.exit(this.containerState.type)}function aC(e,n,s){const i=this;return Xt(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!Jt(o)&&l&&l[1].type==="listItemPrefixWhitespace"?n(o):s(o)}}const jm={name:"setextUnderline",resolveTo:rC,tokenize:oC};function rC(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 oC(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"),Jt(d)?Xt(e,u,"lineSuffix")(d):u(d))}function u(d){return d===null||wt(d)?(e.exit("setextHeadingLine"),n(d)):s(d)}}const lC={tokenize:cC};function cC(e){const n=this,s=e.attempt($r,i,e.attempt(this.parser.constructs.flowInitial,r,Xt(e,e.attempt(this.parser.constructs.flow,r,e.attempt(pS,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 dC={resolveAll:ff()},uC=pf("string"),mC=pf("text");function pf(e){return{resolveAll:ff(e==="text"?hC: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 ff(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 hC(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 pC={42:os,43:os,45:os,48:os,49:os,50:os,51:os,52:os,53:os,54:os,55:os,56:os,57:os,62:of},fC={91:vS},gC={[-2]:Tl,[-1]:Tl,32:Tl},xC={35:SS,42:mo,45:[jm,mo],60:MS,61:jm,95:mo,96:vm,126:vm},bC={38:cf,92:lf},vC={[-5]:Pl,[-4]:Pl,[-3]:Pl,33:KS,38:cf,42:Uc,60:[J0,DS],91:JS,92:[wS,lf],93:Nd,95:Uc,96:lS},yC={null:[Uc,dC]},jC={null:[42,95]},kC={null:[]},wC=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:jC,contentInitial:fC,disable:kC,document:pC,flow:xC,flowInitial:gC,insideSpan:yC,string:bC,text:vC},Symbol.toStringTag,{value:"Module"}));function NC(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:E(A),check:E(w),consume:y,enter:S,exit:k,interrupt:E(w,{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($){return l=Ms(l,$),v(),l[l.length-1]!==null?[]:(C(n,0),d.events=Jo(o,d.events,d),d.events)}function g($,F){return CC(p($),F)}function p($){return SC(l,$)}function f(){const{_bufferIndex:$,_index:F,line:V,column:D,offset:T}=i;return{_bufferIndex:$,_index:F,line:V,column:D,offset:T}}function x($){r[$.line]=$.column,_()}function v(){let $;for(;i._index<l.length;){const F=l[i._index];if(typeof F=="string")for($=i._index,i._bufferIndex<0&&(i._bufferIndex=0);i._index===$&&i._bufferIndex<F.length;)b(F.charCodeAt(i._bufferIndex));else b(F)}}function b($){m=m($)}function y($){wt($)?(i.line++,i.column=1,i.offset+=$===-3?2:1,_()):$!==-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=$}function S($,F){const V=F||{};return V.type=$,V.start=f(),d.events.push(["enter",V,d]),c.push(V),V}function k($){const F=c.pop();return F.end=f(),d.events.push(["exit",F,d]),F}function A($,F){C($,F.from)}function w($,F){F.restore()}function E($,F){return V;function V(D,T,I){let U,Y,ne,N;return Array.isArray(D)?R(D):"tokenize"in D?R([D]):P(D);function P(ke){return be;function be(ce){const ve=ce!==null&&ke[ce],O=ce!==null&&ke.null,oe=[...Array.isArray(ve)?ve:ve?[ve]:[],...Array.isArray(O)?O:O?[O]:[]];return R(oe)(ce)}}function R(ke){return U=ke,Y=0,ke.length===0?I:j(ke[Y])}function j(ke){return be;function be(ce){return N=z(),ne=ke,ke.partial||(d.currentConstruct=ke),ke.name&&d.parser.constructs.disable.null.includes(ke.name)?K():ke.tokenize.call(F?Object.assign(Object.create(d),F):d,u,W,K)(ce)}}function W(ke){return $(ne,N),T}function K(ke){return N.restore(),++Y<U.length?j(U[Y]):I}}}function C($,F){$.resolveAll&&!o.includes($)&&o.push($),$.resolve&&vs(d.events,F,d.events.length-F,$.resolve(d.events.slice(F),d)),$.resolveTo&&(d.events=$.resolveTo(d.events,d))}function z(){const $=f(),F=d.previous,V=d.currentConstruct,D=d.events.length,T=Array.from(c);return{from:D,restore:I};function I(){i=$,d.previous=F,d.currentConstruct=V,d.events.length=D,c=T,_()}}function _(){i.line in r&&i.column<2&&(i.column=r[i.line],i.offset+=r[i.line]-1)}}function SC(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 CC(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 EC(e){const i={constructs:af([wC,...(e||{}).extensions||[]]),content:r(B0),defined:[],document:r(q0),flow:r(lC),lazy:{},string:r(uC),text:r(mC)};return i;function r(o){return l;function l(c){return NC(i,o,c)}}}function _C(e){for(;!df(e););return e}const km=/[\0\t\n\r]/g;function MC(){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(km.lastIndex=h,d=km.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 AC=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function RC(e){return e.replace(AC,TC)}function TC(e,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),o=r===120||r===88;return rf(s.slice(o?2:1),o?16:10)}return wd(s)||e}const gf={}.hasOwnProperty;function PC(e,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),IC(s)(_C(EC(s).document().write(MC()(e,n,!0))))}function IC(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(qe),autolinkProtocol:z,autolinkEmail:z,atxHeading:o(ge),blockQuote:o(O),characterEscape:z,characterReference:z,codeFenced:o(oe),codeFencedFenceInfo:l,codeFencedFenceMeta:l,codeIndented:o(oe,l),codeText:o(te,l),codeTextData:z,data:z,codeFlowValue:z,definition:o(pe),definitionDestinationString:l,definitionLabelString:l,definitionTitleString:l,emphasis:o(de),hardBreakEscape:o(ie),hardBreakTrailing:o(ie),htmlFlow:o(Ee,l),htmlFlowData:z,htmlText:o(Ee,l),htmlTextData:z,image:o(Le),label:l,link:o(qe),listItem:o(Xe),listItemValue:g,listOrdered:o(et,h),listUnordered:o(et),paragraph:o(Ze),reference:j,referenceString:l,resourceDestinationString:l,resourceTitleString:l,setextHeading:o(ge),strong:o(it),thematicBreak:o(Ke)},exit:{atxHeading:u(),atxHeadingSequence:A,autolink:u(),autolinkEmail:ve,autolinkProtocol:ce,blockQuote:u(),characterEscapeValue:_,characterReferenceMarkerHexadecimal:K,characterReferenceMarkerNumeric:K,characterReferenceValue:ke,characterReference:be,codeFenced:u(v),codeFencedFence:x,codeFencedFenceInfo:p,codeFencedFenceMeta:f,codeFlowValue:_,codeIndented:u(b),codeText:u(T),codeTextData:_,data:_,definition:u(),definitionDestinationString:k,definitionLabelString:y,definitionTitleString:S,emphasis:u(),hardBreakEscape:u(F),hardBreakTrailing:u(F),htmlFlow:u(V),htmlFlowData:_,htmlText:u(D),htmlTextData:_,image:u(U),label:ne,labelText:Y,lineEnding:$,link:u(I),listItem:u(),listOrdered:u(),listUnordered:u(),paragraph:u(),referenceString:W,resourceDestinationString:N,resourceTitleString:P,resource:R,setextHeading:u(C),setextHeadingLineSequence:E,setextHeadingText:w,strong:u(),thematicBreak:u()}};xf(n,(e||{}).mdastExtensions||[]);const s={};return i;function i(re){let xe={type:"root",children:[]};const se={stack:[xe],tokenStack:[],config:n,enter:c,exit:d,buffer:l,resume:m,data:s},Ae=[];let ze=-1;for(;++ze<re.length;)if(re[ze][1].type==="listOrdered"||re[ze][1].type==="listUnordered")if(re[ze][0]==="enter")Ae.push(ze);else{const me=Ae.pop();ze=r(re,me,ze)}for(ze=-1;++ze<re.length;){const me=n[re[ze][0]];gf.call(me,re[ze][1].type)&&me[re[ze][1].type].call(Object.assign({sliceSerialize:re[ze][2].sliceSerialize},se),re[ze][1])}if(se.tokenStack.length>0){const me=se.tokenStack[se.tokenStack.length-1];(me[1]||wm).call(se,void 0,me[0])}for(xe.position={start:vi(re.length>0?re[0][1].start:{line:1,column:1,offset:0}),end:vi(re.length>0?re[re.length-2][1].end:{line:1,column:1,offset:0})},ze=-1;++ze<n.transforms.length;)xe=n.transforms[ze](xe)||xe;return xe}function r(re,xe,se){let Ae=xe-1,ze=-1,me=!1,_e,Fe,nt,we;for(;++Ae<=se;){const le=re[Ae];switch(le[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{le[0]==="enter"?ze++:ze--,we=void 0;break}case"lineEndingBlank":{le[0]==="enter"&&(_e&&!we&&!ze&&!nt&&(nt=Ae),we=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:we=void 0}if(!ze&&le[0]==="enter"&&le[1].type==="listItemPrefix"||ze===-1&&le[0]==="exit"&&(le[1].type==="listUnordered"||le[1].type==="listOrdered")){if(_e){let Te=Ae;for(Fe=void 0;Te--;){const he=re[Te];if(he[1].type==="lineEnding"||he[1].type==="lineEndingBlank"){if(he[0]==="exit")continue;Fe&&(re[Fe][1].type="lineEndingBlank",me=!0),he[1].type="lineEnding",Fe=Te}else if(!(he[1].type==="linePrefix"||he[1].type==="blockQuotePrefix"||he[1].type==="blockQuotePrefixWhitespace"||he[1].type==="blockQuoteMarker"||he[1].type==="listItemIndent"))break}nt&&(!Fe||nt<Fe)&&(_e._spread=!0),_e.end=Object.assign({},Fe?re[Fe][1].start:le[1].end),re.splice(Fe||Ae,0,["exit",_e,le[2]]),Ae++,se++}if(le[1].type==="listItemPrefix"){const Te={type:"listItem",_spread:!1,start:Object.assign({},le[1].start),end:void 0};_e=Te,re.splice(Ae,0,["enter",Te,le[2]]),Ae++,se++,nt=void 0,we=!0}}}return re[xe][1]._spread=me,se}function o(re,xe){return se;function se(Ae){c.call(this,re(Ae),Ae),xe&&xe.call(this,Ae)}}function l(){this.stack.push({type:"fragment",children:[]})}function c(re,xe,se){this.stack[this.stack.length-1].children.push(re),this.stack.push(re),this.tokenStack.push([xe,se||void 0]),re.position={start:vi(xe.start),end:void 0}}function u(re){return xe;function xe(se){re&&re.call(this,se),d.call(this,se)}}function d(re,xe){const se=this.stack.pop(),Ae=this.tokenStack.pop();if(Ae)Ae[0].type!==re.type&&(xe?xe.call(this,re,Ae[0]):(Ae[1]||wm).call(this,re,Ae[0]));else throw new Error("Cannot close `"+re.type+"` ("+cr({start:re.start,end:re.end})+"): it’s not open");se.position.end=vi(re.end)}function m(){return kd(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function g(re){if(this.data.expectingFirstListItemValue){const xe=this.stack[this.stack.length-2];xe.start=Number.parseInt(this.sliceSerialize(re),10),this.data.expectingFirstListItemValue=void 0}}function p(){const re=this.resume(),xe=this.stack[this.stack.length-1];xe.lang=re}function f(){const re=this.resume(),xe=this.stack[this.stack.length-1];xe.meta=re}function x(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function v(){const re=this.resume(),xe=this.stack[this.stack.length-1];xe.value=re.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function b(){const re=this.resume(),xe=this.stack[this.stack.length-1];xe.value=re.replace(/(\r?\n|\r)$/g,"")}function y(re){const xe=this.resume(),se=this.stack[this.stack.length-1];se.label=xe,se.identifier=Us(this.sliceSerialize(re)).toLowerCase()}function S(){const re=this.resume(),xe=this.stack[this.stack.length-1];xe.title=re}function k(){const re=this.resume(),xe=this.stack[this.stack.length-1];xe.url=re}function A(re){const xe=this.stack[this.stack.length-1];if(!xe.depth){const se=this.sliceSerialize(re).length;xe.depth=se}}function w(){this.data.setextHeadingSlurpLineEnding=!0}function E(re){const xe=this.stack[this.stack.length-1];xe.depth=this.sliceSerialize(re).codePointAt(0)===61?1:2}function C(){this.data.setextHeadingSlurpLineEnding=void 0}function z(re){const se=this.stack[this.stack.length-1].children;let Ae=se[se.length-1];(!Ae||Ae.type!=="text")&&(Ae=Ie(),Ae.position={start:vi(re.start),end:void 0},se.push(Ae)),this.stack.push(Ae)}function _(re){const xe=this.stack.pop();xe.value+=this.sliceSerialize(re),xe.position.end=vi(re.end)}function $(re){const xe=this.stack[this.stack.length-1];if(this.data.atHardBreak){const se=xe.children[xe.children.length-1];se.position.end=vi(re.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(xe.type)&&(z.call(this,re),_.call(this,re))}function F(){this.data.atHardBreak=!0}function V(){const re=this.resume(),xe=this.stack[this.stack.length-1];xe.value=re}function D(){const re=this.resume(),xe=this.stack[this.stack.length-1];xe.value=re}function T(){const re=this.resume(),xe=this.stack[this.stack.length-1];xe.value=re}function I(){const re=this.stack[this.stack.length-1];if(this.data.inReference){const xe=this.data.referenceType||"shortcut";re.type+="Reference",re.referenceType=xe,delete re.url,delete re.title}else delete re.identifier,delete re.label;this.data.referenceType=void 0}function U(){const re=this.stack[this.stack.length-1];if(this.data.inReference){const xe=this.data.referenceType||"shortcut";re.type+="Reference",re.referenceType=xe,delete re.url,delete re.title}else delete re.identifier,delete re.label;this.data.referenceType=void 0}function Y(re){const xe=this.sliceSerialize(re),se=this.stack[this.stack.length-2];se.label=RC(xe),se.identifier=Us(xe).toLowerCase()}function ne(){const re=this.stack[this.stack.length-1],xe=this.resume(),se=this.stack[this.stack.length-1];if(this.data.inReference=!0,se.type==="link"){const Ae=re.children;se.children=Ae}else se.alt=xe}function N(){const re=this.resume(),xe=this.stack[this.stack.length-1];xe.url=re}function P(){const re=this.resume(),xe=this.stack[this.stack.length-1];xe.title=re}function R(){this.data.inReference=void 0}function j(){this.data.referenceType="collapsed"}function W(re){const xe=this.resume(),se=this.stack[this.stack.length-1];se.label=xe,se.identifier=Us(this.sliceSerialize(re)).toLowerCase(),this.data.referenceType="full"}function K(re){this.data.characterReferenceType=re.type}function ke(re){const xe=this.sliceSerialize(re),se=this.data.characterReferenceType;let Ae;se?(Ae=rf(xe,se==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Ae=wd(xe);const ze=this.stack[this.stack.length-1];ze.value+=Ae}function be(re){const xe=this.stack.pop();xe.position.end=vi(re.end)}function ce(re){_.call(this,re);const xe=this.stack[this.stack.length-1];xe.url=this.sliceSerialize(re)}function ve(re){_.call(this,re);const xe=this.stack[this.stack.length-1];xe.url="mailto:"+this.sliceSerialize(re)}function O(){return{type:"blockquote",children:[]}}function oe(){return{type:"code",lang:null,meta:null,value:""}}function te(){return{type:"inlineCode",value:""}}function pe(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function de(){return{type:"emphasis",children:[]}}function ge(){return{type:"heading",depth:0,children:[]}}function ie(){return{type:"break"}}function Ee(){return{type:"html",value:""}}function Le(){return{type:"image",title:null,url:"",alt:null}}function qe(){return{type:"link",title:null,url:"",children:[]}}function et(re){return{type:"list",ordered:re.type==="listOrdered",start:null,spread:re._spread,children:[]}}function Xe(re){return{type:"listItem",spread:re._spread,checked:null,children:[]}}function Ze(){return{type:"paragraph",children:[]}}function it(){return{type:"strong",children:[]}}function Ie(){return{type:"text",value:""}}function Ke(){return{type:"thematicBreak"}}}function vi(e){return{line:e.line,column:e.column,offset:e.offset}}function xf(e,n){let s=-1;for(;++s<n.length;){const i=n[s];Array.isArray(i)?xf(e,i):$C(e,i)}}function $C(e,n){let s;for(s in n)if(gf.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 wm(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+cr({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+cr({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+cr({start:n.start,end:n.end})+") is still open")}function DC(e){const n=this;n.parser=s;function s(i){return PC(i,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function LC(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 zC(e,n){const s={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,s),[e.applyData(n,s),{type:"text",value:`
|
|
622
|
-
`}]}function OC(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 FC(e,n){const s={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function UC(e,n){const s={type:"element",tagName:"em",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function BC(e,n){const s=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=String(n.identifier).toUpperCase(),r=Pa(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 HC(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 qC(e,n){if(e.options.allowDangerousHtml){const s={type:"raw",value:n.value};return e.patch(n,s),e.applyData(n,s)}}function bf(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 VC(e,n){const s=String(n.identifier).toUpperCase(),i=e.definitionById.get(s);if(!i)return bf(e,n);const r={src:Pa(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 WC(e,n){const s={src:Pa(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 KC(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 GC(e,n){const s=String(n.identifier).toUpperCase(),i=e.definitionById.get(s);if(!i)return bf(e,n);const r={href:Pa(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 JC(e,n){const s={href:Pa(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 YC(e,n,s){const i=e.all(n),r=s?QC(s):vf(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 QC(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=vf(s[i])}return n}function vf(e){const n=e.spread;return n??e.children.length>1}function XC(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 ZC(e,n){const s={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function e2(e,n){const s={type:"root",children:e.wrap(e.all(n))};return e.patch(n,s),e.applyData(n,s)}function t2(e,n){const s={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function n2(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=bd(n.children[1]),u=Qp(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 s2(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 i2(e,n){const s={type:"element",tagName:"td",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}const Nm=9,Sm=32;function a2(e){const n=String(e),s=/\r?\n|\r/g;let i=s.exec(n),r=0;const o=[];for(;i;)o.push(Cm(n.slice(r,i.index),r>0,!0),i[0]),r=i.index+i[0].length,i=s.exec(n);return o.push(Cm(n.slice(r),r>0,!1)),o.join("")}function Cm(e,n,s){let i=0,r=e.length;if(n){let o=e.codePointAt(i);for(;o===Nm||o===Sm;)i++,o=e.codePointAt(i)}if(s){let o=e.codePointAt(r-1);for(;o===Nm||o===Sm;)r--,o=e.codePointAt(r-1)}return r>i?e.slice(i,r):""}function r2(e,n){const s={type:"text",value:a2(String(n.value))};return e.patch(n,s),e.applyData(n,s)}function o2(e,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,s),e.applyData(n,s)}const l2={blockquote:LC,break:zC,code:OC,delete:FC,emphasis:UC,footnoteReference:BC,heading:HC,html:qC,imageReference:VC,image:WC,inlineCode:KC,linkReference:GC,link:JC,listItem:YC,list:XC,paragraph:ZC,root:e2,strong:t2,table:n2,tableCell:i2,tableRow:s2,text:r2,thematicBreak:o2,toml:Xr,yaml:Xr,definition:Xr,footnoteDefinition:Xr};function Xr(){}const yf=-1,Yo=0,ur=1,Co=2,Sd=3,Cd=4,Ed=5,_d=6,jf=7,kf=8,Em=typeof self=="object"?self:globalThis,c2=(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 Yo:case yf:return s(l,r);case ur:{const c=s([],r);for(const u of l)c.push(i(u));return c}case Co:{const c=s({},r);for(const[u,d]of l)c[i(u)]=i(d);return c}case Sd:return s(new Date(l),r);case Cd:{const{source:c,flags:u}=l;return s(new RegExp(c,u),r)}case Ed:{const c=s(new Map,r);for(const[u,d]of l)c.set(i(u),i(d));return c}case _d:{const c=s(new Set,r);for(const u of l)c.add(i(u));return c}case jf:{const{name:c,message:u}=l;return s(new Em[c](u),r)}case kf: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 Em[o](l),r)};return i},_m=e=>c2(new Map,e)(0),oa="",{toString:d2}={},{keys:u2}=Object,Wa=e=>{const n=typeof e;if(n!=="object"||!e)return[Yo,n];const s=d2.call(e).slice(8,-1);switch(s){case"Array":return[ur,oa];case"Object":return[Co,oa];case"Date":return[Sd,oa];case"RegExp":return[Cd,oa];case"Map":return[Ed,oa];case"Set":return[_d,oa];case"DataView":return[ur,s]}return s.includes("Array")?[ur,s]:s.includes("Error")?[jf,s]:[Co,s]},Zr=([e,n])=>e===Yo&&(n==="function"||n==="symbol"),m2=(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]=Wa(l);switch(c){case Yo:{let m=l;switch(u){case"bigint":c=kf,m=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+u);m=null;break;case"undefined":return r([yf],l)}return r([c,m],l)}case ur:{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 Co:{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 u2(l))(e||!Zr(Wa(l[g])))&&m.push([o(g),o(l[g])]);return h}case Sd:return r([c,l.toISOString()],l);case Cd:{const{source:m,flags:h}=l;return r([c,{source:m,flags:h}],l)}case Ed:{const m=[],h=r([c,m],l);for(const[g,p]of l)(e||!(Zr(Wa(g))||Zr(Wa(p))))&&m.push([o(g),o(p)]);return h}case _d:{const m=[],h=r([c,m],l);for(const g of l)(e||!Zr(Wa(g)))&&m.push(o(g));return h}}const{message:d}=l;return r([c,{name:u,message:d}],l)};return o},Mm=(e,{json:n,lossy:s}={})=>{const i=[];return m2(!(n||s),!!n,new Map,i)(e),i},Eo=typeof structuredClone=="function"?(e,n)=>n&&("json"in n||"lossy"in n)?_m(Mm(e,n)):structuredClone(e):(e,n)=>_m(Mm(e,n));function h2(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 p2(e,n){return"Back to reference "+(e+1)+(n>1?"-"+n:"")}function f2(e){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=e.options.footnoteBackContent||h2,i=e.options.footnoteBackLabel||p2,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=Pa(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:{...Eo(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 Qo=(function(e){if(e==null)return v2;if(typeof e=="function")return Xo(e);if(typeof e=="object")return Array.isArray(e)?g2(e):x2(e);if(typeof e=="string")return b2(e);throw new Error("Expected function, string, or object as test")});function g2(e){const n=[];let s=-1;for(;++s<e.length;)n[s]=Qo(e[s]);return Xo(i);function i(...r){let o=-1;for(;++o<n.length;)if(n[o].apply(this,r))return!0;return!1}}function x2(e){const n=e;return Xo(s);function s(i){const r=i;let o;for(o in e)if(r[o]!==n[o])return!1;return!0}}function b2(e){return Xo(n);function n(s){return s&&s.type===e}}function Xo(e){return n;function n(s,i,r){return!!(y2(s)&&e.call(this,s,typeof i=="number"?i:void 0,r||void 0))}}function v2(){return!0}function y2(e){return e!==null&&typeof e=="object"&&"type"in e}const wf=[],j2=!0,Bc=!1,k2="skip";function Nf(e,n,s,i){let r;typeof n=="function"&&typeof s!="function"?(i=s,s=n):r=n;const o=Qo(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=wf,f,x,v;if((!n||o(u,d,m[m.length-1]||void 0))&&(p=w2(s(u,m)),p[0]===Bc))return p;if("children"in u&&u.children){const b=u;if(b.children&&p[0]!==k2)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]===Bc)return f;x=typeof f[1]=="number"?f[1]:x+l}}return p}}}function w2(e){return Array.isArray(e)?e:typeof e=="number"?[j2,e]:e==null?wf:[e]}function Md(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),Nf(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 Hc={}.hasOwnProperty,N2={};function S2(e,n){const s=n||N2,i=new Map,r=new Map,o=new Map,l={...l2,...s.handlers},c={all:d,applyData:E2,definitionById:i,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:l,one:u,options:s,patch:C2,wrap:M2};return Md(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(Hc.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=Eo(v);return b.children=c.all(m),b}return Eo(m)}return(c.options.unknownHandler||_2)(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=Am(f.value)),!Array.isArray(f)&&f.type==="element")){const x=f.children[0];x&&x.type==="text"&&(x.value=Am(x.value))}Array.isArray(f)?h.push(...f):h.push(f)}}}return h}}function C2(e,n){e.position&&(n.position=p0(e))}function E2(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,Eo(o)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function _2(e,n){const s=n.data||{},i="value"in n&&!(Hc.call(s,"hProperties")||Hc.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 M2(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 Am(e){let n=0,s=e.charCodeAt(n);for(;s===9||s===32;)n++,s=e.charCodeAt(n);return e.slice(n)}function Rm(e,n){const s=S2(e,n),i=s.one(e,void 0),r=f2(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 A2(e,n){return e&&"run"in e?async function(s,i){const r=Rm(s,{file:i,...n});await e.run(r,i)}:function(s,i){return Rm(s,{file:i,...e||n})}}function Tm(e){if(e)throw e}var Il,Pm;function R2(){if(Pm)return Il;Pm=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 Il=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},Il}var T2=R2();const $l=Bh(T2);function qc(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 P2(){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?I2(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 I2(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 Js={basename:$2,dirname:D2,extname:L2,join:z2,sep:"/"};function $2(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');Dr(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 D2(e){if(Dr(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 L2(e){Dr(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 z2(...e){let n=-1,s;for(;++n<e.length;)Dr(e[n]),e[n]&&(s=s===void 0?e[n]:s+"/"+e[n]);return s===void 0?".":O2(s)}function O2(e){Dr(e);const n=e.codePointAt(0)===47;let s=F2(e,!n);return s.length===0&&!n&&(s="."),s.length>0&&e.codePointAt(e.length-1)===47&&(s+="/"),n?"/"+s:s}function F2(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 Dr(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const U2={cwd:B2};function B2(){return"/"}function Vc(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function H2(e){if(typeof e=="string")e=new URL(e);else if(!Vc(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 q2(e)}function q2(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 Dl=["history","path","basename","stem","extname","dirname"];class Sf{constructor(n){let s;n?Vc(n)?s={path:n}:typeof n=="string"||V2(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":U2.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let i=-1;for(;++i<Dl.length;){const o=Dl[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)Dl.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?Js.basename(this.path):void 0}set basename(n){zl(n,"basename"),Ll(n,"basename"),this.path=Js.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?Js.dirname(this.path):void 0}set dirname(n){Im(this.basename,"dirname"),this.path=Js.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?Js.extname(this.path):void 0}set extname(n){if(Ll(n,"extname"),Im(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=Js.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){Vc(n)&&(n=H2(n)),zl(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?Js.basename(this.path,this.extname):void 0}set stem(n){zl(n,"stem"),Ll(n,"stem"),this.path=Js.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 Xn(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 Ll(e,n){if(e&&e.includes(Js.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+Js.sep+"`")}function zl(e,n){if(!e)throw new Error("`"+n+"` cannot be empty")}function Im(e,n){if(!e)throw new Error("Setting `"+n+"` requires `path` to be set too")}function V2(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const W2=(function(e){const i=this.constructor.prototype,r=i[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,i),o}),K2={}.hasOwnProperty;class Ad extends W2{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=P2()}copy(){const n=new Ad;let s=-1;for(;++s<this.attachers.length;){const i=this.attachers[s];n.use(...i)}return n.data($l(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(Ul("data",this.frozen),this.namespace[n]=s,this):K2.call(this.namespace,n)&&this.namespace[n]||void 0:n?(Ul("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=eo(n),i=this.parser||this.Parser;return Ol("parse",i),i(String(s),s)}process(n,s){const i=this;return this.freeze(),Ol("process",this.parser||this.Parser),Fl("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(o,l){const c=eo(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);Y2(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(),Ol("processSync",this.parser||this.Parser),Fl("processSync",this.compiler||this.Compiler),this.process(n,r),Dm("processSync","process",s),i;function r(o,l){s=!0,Tm(o),i=l}}run(n,s,i){$m(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=eo(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),Dm("runSync","run",i),r;function o(l,c){Tm(l),r=c,i=!0}}stringify(n,s){this.freeze();const i=eo(s),r=this.compiler||this.Compiler;return Fl("stringify",r),$m(n),r(n,i)}use(n,...s){const i=this.attachers,r=this.namespace;if(Ul("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=$l(!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];qc(x)&&qc(p)&&(p=$l(!0,x,p)),i[g]=[d,p,...f]}}}}const G2=new Ad().freeze();function Ol(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Fl(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Ul(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 $m(e){if(!qc(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Dm(e,n,s){if(!s)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function eo(e){return J2(e)?e:new Sf(e)}function J2(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function Y2(e){return typeof e=="string"||Q2(e)}function Q2(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const X2="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Lm=[],zm={allowDangerousHtml:!0},Z2=/^(https?|ircs?|mailto|xmpp)$/i,eE=[{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 hi(e){const n=tE(e),s=nE(e);return sE(n.runSync(n.parse(s),s),e)}function tE(e){const n=e.rehypePlugins||Lm,s=e.remarkPlugins||Lm,i=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...zm}:zm;return G2().use(DC).use(s).use(A2,i).use(n)}function nE(e){const n=e.children||"",s=new Sf;return typeof n=="string"&&(s.value=n),s}function sE(e,n){const s=n.allowedElements,i=n.allowElement,r=n.components,o=n.disallowedElements,l=n.skipHtml,c=n.unwrapDisallowed,u=n.urlTransform||iE;for(const m of eE)Object.hasOwn(n,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+X2+m.id,void 0);return Md(e,d),v0(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 Rl)if(Object.hasOwn(Rl,p)&&Object.hasOwn(m.properties,p)){const f=m.properties[p],x=Rl[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 iE(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||Z2.test(e.slice(0,n))?e:""}function Om(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 aE(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function rE(e,n,s){const r=Qo((s||{}).ignore||[]),o=oE(n);let l=-1;for(;++l<o.length;)Nf(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,A={index:S.index,input:S.input,stack:[...m,d]};let w=p(...S,A);if(typeof w=="string"&&(w=w.length>0?{type:"text",value:w}:void 0),w===!1?g.lastIndex=k+1:(f!==k&&y.push({type:"text",value:d.value.slice(f,k)}),Array.isArray(w)?y.push(...w):w&&y.push(w),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 oE(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([lE(r[0]),cE(r[1])])}return n}function lE(e){return typeof e=="string"?new RegExp(aE(e),"g"):e}function cE(e){return typeof e=="function"?e:function(){return e}}const Bl="phrasing",Hl=["autolink","link","image","label"];function dE(){return{transforms:[xE],enter:{literalAutolink:mE,literalAutolinkEmail:ql,literalAutolinkHttp:ql,literalAutolinkWww:ql},exit:{literalAutolink:gE,literalAutolinkEmail:fE,literalAutolinkHttp:hE,literalAutolinkWww:pE}}}function uE(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Bl,notInConstruct:Hl},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Bl,notInConstruct:Hl},{character:":",before:"[ps]",after:"\\/",inConstruct:Bl,notInConstruct:Hl}]}}function mE(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function ql(e){this.config.enter.autolinkProtocol.call(this,e)}function hE(e){this.config.exit.autolinkProtocol.call(this,e)}function pE(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 fE(e){this.config.exit.autolinkEmail.call(this,e)}function gE(e){this.exit(e)}function xE(e){rE(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,bE],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,vE]],{ignore:["link","linkReference"]})}function bE(e,n,s,i,r){let o="";if(!Cf(r)||(/^w/i.test(n)&&(s=n+s,n="",o="http://"),!yE(s)))return!1;const l=jE(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 vE(e,n,s,i){return!Cf(i,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function yE(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 jE(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=Om(e,"(");let o=Om(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 Cf(e,n){const s=e.input.charCodeAt(e.index-1);return(e.index===0||Vi(s)||Go(s))&&(!n||s!==47)}Ef.peek=AE;function kE(){this.buffer()}function wE(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function NE(){this.buffer()}function SE(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function CE(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=Us(this.sliceSerialize(e)).toLowerCase(),s.label=n}function EE(e){this.exit(e)}function _E(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=Us(this.sliceSerialize(e)).toLowerCase(),s.label=n}function ME(e){this.exit(e)}function AE(){return"["}function Ef(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 RE(){return{enter:{gfmFootnoteCallString:kE,gfmFootnoteCall:wE,gfmFootnoteDefinitionLabelString:NE,gfmFootnoteDefinition:SE},exit:{gfmFootnoteCallString:CE,gfmFootnoteCall:EE,gfmFootnoteDefinitionLabelString:_E,gfmFootnoteDefinition:ME}}}function TE(e){let n=!1;return e&&e.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:Ef},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?_f:PE))),d(),u}}function PE(e,n,s){return n===0?e:_f(e,n,s)}function _f(e,n,s){return(s?"":" ")+e}const IE=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Mf.peek=OE;function $E(){return{canContainEols:["delete"],enter:{strikethrough:LE},exit:{strikethrough:zE}}}function DE(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:IE}],handlers:{delete:Mf}}}function LE(e){this.enter({type:"delete",children:[]},e)}function zE(e){this.exit(e)}function Mf(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 OE(){return"~"}function FE(e){return e.length}function UE(e,n){const s=n||{},i=(s.align||[]).concat(),r=s.stringLength||FE,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=BE(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]=Fm(i[h]);else{const x=Fm(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 A=u[h]-(v[h]||0),w=o[h];w===114?S=" ".repeat(A):w===99?A%2?(S=" ".repeat(A/2+.5),k=" ".repeat(A/2-.5)):(S=" ".repeat(A/2),k=S):k=" ".repeat(A)}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 BE(e){return e==null?"":String(e)}function Fm(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 HE(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()),qE);return r(),l}function qE(e,n,s){return">"+(s?"":" ")+e}function VE(e,n){return Um(e,n.inConstruct,!0)&&!Um(e,n.notInConstruct,!1)}function Um(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 Bm(e,n,s,i){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
|
|
634
|
-
`&&VE(s.stack,s.unsafe[r]))return/[ \t]/.test(i.before)?"":" ";return`\\
|
|
635
|
-
`}function WE(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 KE(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 GE(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 JE(e,n,s,i){const r=GE(s),o=e.value||"",l=r==="`"?"GraveAccent":"Tilde";if(KE(e,s)){const h=s.enter("codeIndented"),g=s.indentLines(o,YE);return h(),g}const c=s.createTracker(i),u=r.repeat(Math.max(WE(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 YE(e,n,s){return(s?"":" ")+e}function Rd(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 QE(e,n,s,i){const r=Rd(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 XE(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 kr(e){return"&#x"+e.toString(16).toUpperCase()+";"}function _o(e,n,s){const i=ja(e),r=ja(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}}Af.peek=ZE;function Af(e,n,s,i){const r=XE(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=_o(i.before.charCodeAt(i.before.length-1),d,r);m.inside&&(u=kr(d)+u.slice(1));const h=u.charCodeAt(u.length-1),g=_o(i.after.charCodeAt(0),h,r);g.inside&&(u=u.slice(0,-1)+kr(h));const p=l.move(r);return o(),s.attentionEncodeSurroundingInfo={after:g.outside,before:m.outside},c+u+p}function ZE(e,n,s){return s.options.emphasis||"*"}function e_(e,n){let s=!1;return Md(e,function(i){if("value"in i&&/\r?\n|\r/.test(i.value)||i.type==="break")return s=!0,Bc}),!!((!e.depth||e.depth<3)&&kd(e)&&(n.options.setext||s))}function t_(e,n,s,i){const r=Math.max(Math.min(6,e.depth||1),1),o=s.createTracker(i);if(e_(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=kr(d.charCodeAt(0))+d.slice(1)),d=d?l+" "+d:l,s.options.closeAtx&&(d+=" "+l),u(),c(),d}Rf.peek=n_;function Rf(e){return e.value||""}function n_(){return"<"}Tf.peek=s_;function Tf(e,n,s,i){const r=Rd(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 s_(){return"!"}Pf.peek=i_;function Pf(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 i_(){return"!"}If.peek=a_;function If(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 a_(){return"`"}function $f(e,n){const s=kd(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))}Df.peek=r_;function Df(e,n,s,i){const r=Rd(s),o=r==='"'?"Quote":"Apostrophe",l=s.createTracker(i);let c,u;if($f(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 r_(e,n,s){return $f(e,s)?"<":"["}Lf.peek=o_;function Lf(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 o_(){return"["}function Td(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 l_(e){const n=Td(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 c_(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 zf(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 d_(e,n,s,i){const r=s.enter("list"),o=s.bulletCurrent;let l=e.ordered?c_(s):Td(s);const c=e.ordered?l==="."?")":".":l_(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),zf(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 u_(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 m_(e,n,s,i){const r=u_(s);let o=s.bulletCurrent||Td(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 h_(e,n,s,i){const r=s.enter("paragraph"),o=s.enter("phrasing"),l=s.containerPhrasing(e,i);return o(),r(),l}const p_=Qo(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function f_(e,n,s,i){return(e.children.some(function(l){return p_(l)})?s.containerPhrasing:s.containerFlow).call(s,e,i)}function g_(e){const n=e.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}Of.peek=x_;function Of(e,n,s,i){const r=g_(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=_o(i.before.charCodeAt(i.before.length-1),d,r);m.inside&&(u=kr(d)+u.slice(1));const h=u.charCodeAt(u.length-1),g=_o(i.after.charCodeAt(0),h,r);g.inside&&(u=u.slice(0,-1)+kr(h));const p=l.move(r+r);return o(),s.attentionEncodeSurroundingInfo={after:g.outside,before:m.outside},c+u+p}function x_(e,n,s){return s.options.strong||"*"}function b_(e,n,s,i){return s.safe(e.value,i)}function v_(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 y_(e,n,s){const i=(zf(s)+(s.options.ruleSpaces?" ":"")).repeat(v_(s));return s.options.ruleSpaces?i.slice(0,-1):i}const Ff={blockquote:HE,break:Bm,code:JE,definition:QE,emphasis:Af,hardBreak:Bm,heading:t_,html:Rf,image:Tf,imageReference:Pf,inlineCode:If,link:Df,linkReference:Lf,list:d_,listItem:m_,paragraph:h_,root:f_,strong:Of,text:b_,thematicBreak:y_};function j_(){return{enter:{table:k_,tableData:Hm,tableHeader:Hm,tableRow:N_},exit:{codeText:S_,table:w_,tableData:Vl,tableHeader:Vl,tableRow:Vl}}}function k_(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 w_(e){this.exit(e),this.data.inTable=void 0}function N_(e){this.enter({type:"tableRow",children:[]},e)}function Vl(e){this.exit(e)}function Hm(e){this.enter({type:"tableCell",children:[]},e)}function S_(e){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,C_));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(e)}function C_(e,n){return n==="|"?n:e}function E_(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 UE(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=Ff.inlineCode(p,f,x);return x.stack.includes("tableCell")&&(v=v.replace(/\|/g,"\\$&")),v}}function __(){return{exit:{taskListCheckValueChecked:qm,taskListCheckValueUnchecked:qm,paragraph:A_}}}function M_(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:R_}}}function qm(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function A_(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 R_(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=Ff.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 T_(){return[dE(),RE(),$E(),j_(),__()]}function P_(e){return{extensions:[uE(),TE(e),DE(),E_(e),M_()]}}const I_={tokenize:F_,partial:!0},Uf={tokenize:U_,partial:!0},Bf={tokenize:B_,partial:!0},Hf={tokenize:H_,partial:!0},$_={tokenize:q_,partial:!0},qf={name:"wwwAutolink",tokenize:z_,previous:Wf},Vf={name:"protocolAutolink",tokenize:O_,previous:Kf},fi={name:"emailAutolink",tokenize:L_,previous:Gf},ni={};function D_(){return{text:ni}}let $i=48;for(;$i<123;)ni[$i]=fi,$i++,$i===58?$i=65:$i===91&&($i=97);ni[43]=fi;ni[45]=fi;ni[46]=fi;ni[95]=fi;ni[72]=[fi,Vf];ni[104]=[fi,Vf];ni[87]=[fi,qf];ni[119]=[fi,qf];function L_(e,n,s){const i=this;let r,o;return l;function l(h){return!Wc(h)||!Gf.call(i,i.previous)||Pd(i.events)?s(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(h))}function c(h){return Wc(h)?(e.consume(h),c):h===64?(e.consume(h),u):s(h)}function u(h){return h===46?e.check($_,m,d)(h):h===45||h===95||Yn(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&&ns(i.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),n(h)):s(h)}}function z_(e,n,s){const i=this;return r;function r(l){return l!==87&&l!==119||!Wf.call(i,i.previous)||Pd(i.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(I_,e.attempt(Uf,e.attempt(Bf,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function O_(e,n,s){const i=this;let r="",o=!1;return l;function l(h){return(h===72||h===104)&&Kf.call(i,i.previous)&&!Pd(i.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),e.consume(h),c):s(h)}function c(h){if(ns(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||So(h)||dn(h)||Vi(h)||Go(h)?s(h):e.attempt(Uf,e.attempt(Bf,m),s)(h)}function m(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(h)}}function F_(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 U_(e,n,s){let i,r,o;return l;function l(d){return d===46||d===95?e.check(Hf,u,c)(d):d===null||dn(d)||Vi(d)||d!==45&&Go(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 B_(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(Hf,n,o)(l):l===null||dn(l)||Vi(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&i++,e.consume(l),r}}function H_(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||dn(c)||Vi(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||dn(c)||Vi(c)?n(c):i(c)}function o(c){return ns(c)?l(c):s(c)}function l(c){return c===59?(e.consume(c),i):ns(c)?(e.consume(c),l):s(c)}}function q_(e,n,s){return i;function i(o){return e.consume(o),r}function r(o){return Yn(o)?s(o):n(o)}}function Wf(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||dn(e)}function Kf(e){return!ns(e)}function Gf(e){return!(e===47||Wc(e))}function Wc(e){return e===43||e===45||e===46||e===95||Yn(e)}function Pd(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 V_={tokenize:Z_,partial:!0};function W_(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:Y_,continuation:{tokenize:Q_},exit:X_}},text:{91:{name:"gfmFootnoteCall",tokenize:J_},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:K_,resolveTo:G_}}}}function K_(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=Us(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 G_(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 J_(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||dn(h))return s(h);if(h===93){e.exit("chunkString");const g=e.exit("gfmFootnoteCallString");return r.includes(Us(i.sliceSerialize(g)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),n):s(h)}return dn(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 Y_(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||dn(f))return s(f);if(f===93){e.exit("chunkString");const x=e.exit("gfmFootnoteDefinitionLabelString");return o=Us(i.sliceSerialize(x)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),g}return dn(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),Xt(e,p,"gfmFootnoteDefinitionWhitespace")):s(f)}function p(f){return n(f)}}function Q_(e,n,s){return e.check($r,n,e.attempt(V_,n,s))}function X_(e){e.exit("gfmFootnoteDefinition")}function Z_(e,n,s){const i=this;return Xt(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 eM(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&&vs(g,g.length,0,Jo(p,l.slice(d+1,u),c)),vs(g,g.length,0,[["exit",h,c],["enter",l[u][1],c],["exit",l[u][1],c],["exit",m,c]]),vs(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=ja(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=ja(f);return v._open=!b||b===2&&!!x,v._close=!x||x===2&&!!b,c(f)}}}class tM{constructor(){this.map=[]}add(n,s,i){nM(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 nM(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 sM(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 iM(){return{flow:{null:{name:"table",tokenize:aM,resolveAll:rM}}}}function aM(e,n,s){const i=this;let r=0,o=0,l;return c;function c(_){let $=i.events.length-1;for(;$>-1;){const D=i.events[$][1].type;if(D==="lineEnding"||D==="linePrefix")$--;else break}const F=$>-1?i.events[$][1].type:null,V=F==="tableHead"||F==="tableRow"?w:u;return V===w&&i.parser.lazy[i.now().line]?s(_):V(_)}function u(_){return e.enter("tableHead"),e.enter("tableRow"),d(_)}function d(_){return _===124||(l=!0,o+=1),m(_)}function m(_){return _===null?s(_):wt(_)?o>1?(o=0,i.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(_),e.exit("lineEnding"),p):s(_):Jt(_)?Xt(e,m,"whitespace")(_):(o+=1,l&&(l=!1,r+=1),_===124?(e.enter("tableCellDivider"),e.consume(_),e.exit("tableCellDivider"),l=!0,m):(e.enter("data"),h(_)))}function h(_){return _===null||_===124||dn(_)?(e.exit("data"),m(_)):(e.consume(_),_===92?g:h)}function g(_){return _===92||_===124?(e.consume(_),h):h(_)}function p(_){return i.interrupt=!1,i.parser.lazy[i.now().line]?s(_):(e.enter("tableDelimiterRow"),l=!1,Jt(_)?Xt(e,f,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(_):f(_))}function f(_){return _===45||_===58?v(_):_===124?(l=!0,e.enter("tableCellDivider"),e.consume(_),e.exit("tableCellDivider"),x):A(_)}function x(_){return Jt(_)?Xt(e,v,"whitespace")(_):v(_)}function v(_){return _===58?(o+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(_),e.exit("tableDelimiterMarker"),b):_===45?(o+=1,b(_)):_===null||wt(_)?k(_):A(_)}function b(_){return _===45?(e.enter("tableDelimiterFiller"),y(_)):A(_)}function y(_){return _===45?(e.consume(_),y):_===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(_),e.exit("tableDelimiterMarker"),S):(e.exit("tableDelimiterFiller"),S(_))}function S(_){return Jt(_)?Xt(e,k,"whitespace")(_):k(_)}function k(_){return _===124?f(_):_===null||wt(_)?!l||r!==o?A(_):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(_)):A(_)}function A(_){return s(_)}function w(_){return e.enter("tableRow"),E(_)}function E(_){return _===124?(e.enter("tableCellDivider"),e.consume(_),e.exit("tableCellDivider"),E):_===null||wt(_)?(e.exit("tableRow"),n(_)):Jt(_)?Xt(e,E,"whitespace")(_):(e.enter("data"),C(_))}function C(_){return _===null||_===124||dn(_)?(e.exit("data"),E(_)):(e.consume(_),_===92?z:C)}function z(_){return _===92||_===124?(e.consume(_),C):C(_)}}function rM(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 tM;for(;++s<e.length;){const p=e[s],f=p[1];p[0]==="enter"?f.type==="tableHead"?(c=!1,u!==0&&(Vm(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=to(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=to(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=to(g,n,o,r,s,h)):l[1]!==0&&(h=to(g,n,l,r,s,h)),r=0):r&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")&&(l[3]=s)}for(u!==0&&Vm(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=sM(n.events,s))}return e}function to(e,n,s,i,r,o){const l=i===1?"tableHeader":i===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},ua(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const u=ua(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=ua(n.events,s[2]),m=ua(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({},ua(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function Vm(e,n,s,i,r){const o=[],l=ua(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 ua(e,n){const s=e[n],i=s[0]==="enter"?"start":"end";return s[1][i]}const oM={name:"tasklistCheck",tokenize:cM};function lM(){return{text:{91:oM}}}function cM(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 dn(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 wt(u)?n(u):Jt(u)?e.check({tokenize:dM},n,s)(u):s(u)}}function dM(e,n,s){return Xt(e,i,"whitespace");function i(r){return r===null?s(r):n(r)}}function uM(e){return af([D_(),W_(),eM(e),iM(),lM()])}const mM={};function pi(e){const n=this,s=e||mM,i=n.data(),r=i.micromarkExtensions||(i.micromarkExtensions=[]),o=i.fromMarkdownExtensions||(i.fromMarkdownExtensions=[]),l=i.toMarkdownExtensions||(i.toMarkdownExtensions=[]);r.push(uM(s)),o.push(T_()),l.push(P_(s))}const Wm=500,Km=100;function Wl(e){return e.length>Wm?e.slice(-Wm):e}function Jf(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 E=x.current,C=++S.current;f.current=!1;const z=e,_=s;async function $(){if(!z)return;l(!0),g(!1);try{const V=await Vd(z,_,{limit:Km});if(f.current||x.current!==E||S.current!==C)return;r(Wl(V.entries)),u(V.hasMore),m(V.total)}catch{if(f.current||x.current!==E||S.current!==C)return;r([]),u(!1),m(null)}finally{!f.current&&x.current===E&&S.current===C&&l(!1)}const F=_?`?projectId=${encodeURIComponent(_)}`:"";p.current=Hs(`/api/tasks/${z}/logs/stream${F}`,{events:{"agent:log":V=>{if(!(f.current||x.current!==E))try{const D=JSON.parse(V.data);r(T=>Wl([...T,D])),m(T=>T!==null?T+1:null)}catch{}}}})}return $(),()=>{f.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const A=a.useCallback(async()=>{if(!e||h)return;const E=x.current,C=i.length,z=e;g(!0);try{const _=await Vd(z,s,{limit:Km,offset:C});if(f.current||x.current!==E)return;r($=>{const F=[..._.entries,...$];return Wl(F)}),u(_.hasMore),m(_.total)}catch{}finally{g(!1)}},[e,s,i.length,h]),w=a.useCallback(()=>r([]),[]);return{entries:i,loading:o,clear:w,loadMore:A,hasMore:c,total:d,loadingMore:h}}function hM(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 Gm={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})},Yf=50,pM={triage:"Plan"};function Jm(e){return e.scrollHeight-(e.scrollTop+e.clientHeight)<=Yf}function Kc(e){return[e.taskId,e.timestamp,e.agent??"",e.type,e.text,e.detail??""].join("|")}function fM(e){const n=new Map;return e.map(s=>{const i=Kc(s),r=n.get(i)??0;return n.set(i,r+1),`${i}|${r}`})}function gM(e){return e==="tool"||e==="tool_result"||e==="tool_error"}function xM(e,n){return e.agent?gM(e.type)?!0:!n||n.agent!==e.agent||n.type!==e.type:!1}function bM(e,n){const s=[];for(let i=0;i<e.length;i+=1){const r=e[i],o=n[i]??`${Kc(r)}|fallback`,l=i>0?e[i-1]:void 0,c=xM(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]??`${Kc(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 vM({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,A]=a.useState(!0),w=a.useMemo(()=>fM(e),[e]),E=a.useMemo(()=>bM(e,w),[e,w]);a.useLayoutEffect(()=>{const T=d.current;if(!T)return;const I=e.length,U=m.current,Y=h.current||T.scrollHeight,ne=w[0]??null,N=w[w.length-1]??null,P=g.current!==ne,R=p.current!==N;if(I>U)if(U===0)T.scrollTop=T.scrollHeight;else{const j=Y-(T.scrollTop+T.clientHeight)<=Yf,W=R&&!P,K=P&&!R;if(W&&j&&(T.scrollTop=T.scrollHeight),K){const ke=T.scrollHeight-Y;ke>0&&(T.scrollTop+=ke)}}m.current=I,h.current=T.scrollHeight,g.current=ne,p.current=N,A(Jm(T))},[e,w]);const C=a.useCallback(()=>{const T=d.current;T&&A(Jm(T))},[]),z=a.useCallback(()=>{const T=d.current;T&&(T.scrollTop=T.scrollHeight,A(!0))},[]),_=a.useCallback(T=>{T.key==="Escape"&&v&&b(!1)},[v]);a.useEffect(()=>{if(v)return document.addEventListener("keydown",_),()=>{document.removeEventListener("keydown",_)}},[v,_]);const $=s?.provider&&s?.modelId,F=i?.provider&&i?.modelId,V=r?.provider&&r?.modelId,D=a.useMemo(()=>{const T=[];return $&&T.push({role:"Executor",provider:s.provider,modelId:s.modelId}),F&&T.push({role:"Reviewer",provider:i.provider,modelId:i.modelId}),V&&T.push({role:"Planning",provider:r.provider,modelId:r.modelId}),T},[$,s,F,i,V,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:[D.map(T=>t.jsx(Dn,{provider:T.provider,size:"sm"},`${T.role}-${T.provider}-${T.modelId??"default"}`)),t.jsx("button",{className:"agent-log-model-expand-btn",onClick:()=>S(T=>!T),"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(Yt,{size:14}):t.jsx(bn,{size:14})})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>x(T=>!T),"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(T=>!T),"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(Er,{size:14}):t.jsx(zo,{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:"}),$?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Dn,{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(Dn,{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:"}),V?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Dn,{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(rt,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})}),E.map(T=>{const I=T.kind==="single"?T.entry:T.entries[0],U=T.showBadge?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:hM(I.timestamp)}):null,Y=T.showBadge?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",pM[I.agent]??I.agent,"]"]}),U]}):null;if(T.kind==="single"){const{entry:N}=T;if(N.type==="tool")return t.jsxs("div",{className:"agent-log-tool",children:[Y,"⚡ ",N.text,N.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",N.detail]})]},T.key);if(N.type==="tool_result")return t.jsxs("div",{className:"agent-log-tool-result",children:[Y,"✓ ",N.text,N.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",N.detail]})]},T.key);if(N.type==="tool_error")return t.jsxs("div",{className:"agent-log-tool-error",children:[Y,"✗ ",N.text,N.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",N.detail]})]},T.key)}const ne=T.kind==="single"?I.text:T.entries.map(N=>N.text).join("");return T.kind==="thinking"?t.jsxs("div",{className:"agent-log-thinking",children:[Y,f?t.jsx("div",{className:"markdown-body",children:t.jsx(hi,{remarkPlugins:[pi],components:Gm,children:ne})}):ne]},T.key):t.jsxs("div",{className:"agent-log-text",children:[Y,f?t.jsx("div",{className:"markdown-body",children:t.jsx(hi,{remarkPlugins:[pi],components:Gm,children:ne})}):ne]},T.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(Yt,{size:12}),t.jsx("span",{children:"Live"})]})]})]})}function ka(e){return e??void 0}function no(e){return{provider:ka(e.modelProvider),modelId:ka(e.modelId)}}function so(e){return{provider:ka(e.validatorModelProvider),modelId:ka(e.validatorModelId)}}function io(e){return{provider:ka(e.planningModelProvider),modelId:ka(e.planningModelId)}}function yM(e,n){return wp(e,n)}function jM(e,n){return Np(e,n)}function kM(e,n){return Sp(e,n)}function Kl(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 Gl(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function Jl(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function wM(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 NM({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(()=>no(e)),[v,b]=a.useState(()=>no(e)),[y,S]=a.useState(()=>so(e)),[k,A]=a.useState(()=>so(e)),[w,E]=a.useState(()=>io(e)),[C,z]=a.useState(()=>io(e)),[_,$]=a.useState(()=>e.thinkingLevel??null),[F,V]=a.useState(()=>e.thinkingLevel??null),[D,T]=a.useState(null),I=a.useRef(e.id);a.useEffect(()=>{h(!0),p(null),ds().then(de=>{o(de.models),c(de.favoriteProviders),d(de.favoriteModels)}).catch(de=>{p(de.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const U=a.useCallback(async de=>{const ge=l,Ee=ge.includes(de)?ge.filter(Le=>Le!==de):[de,...ge];c(Ee);try{await cn({favoriteProviders:Ee,favoriteModels:u})}catch{c(ge),n("Failed to update favorites","error")}},[l,u,n]),Y=a.useCallback(async de=>{const ge=u,Ee=ge.includes(de)?ge.filter(Le=>Le!==de):[de,...ge];d(Ee);try{await cn({favoriteProviders:l,favoriteModels:Ee})}catch{d(ge),n("Failed to update model favorites","error")}},[u,l,n]);a.useEffect(()=>{I.current=e.id;const de=no(e),ge=so(e),ie=io(e);x(de),b(de),S(ge),A(ge),E(ie),z(ie);const Ee=e.thinkingLevel??null;$(Ee),V(Ee),T(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const ne=a.useMemo(()=>Gl(f),[f]),N=a.useMemo(()=>Gl(y),[y]),P=a.useMemo(()=>Gl(w),[w]),R=a.useMemo(()=>yM(e,i),[e,i]),j=a.useMemo(()=>jM(e,i),[e,i]),W=a.useMemo(()=>kM(e,i),[e,i]),K=D!==null,ke=a.useCallback(async(de,ge)=>{const ie=e.id,Ee=v,Le=k,qe=C;T(de);try{const et=s?de==="executor"?{modelProvider:ge.provider??null,modelId:ge.modelId??null}:de==="validator"?{validatorModelProvider:ge.provider??null,validatorModelId:ge.modelId??null}:{planningModelProvider:ge.provider??null,planningModelId:ge.modelId??null}:{modelProvider:(de==="executor"?ge:v).provider??null,modelId:(de==="executor"?ge:v).modelId??null,validatorModelProvider:(de==="validator"?ge:k).provider??null,validatorModelId:(de==="validator"?ge:k).modelId??null,planningModelProvider:(de==="planning"?ge:C).provider??null,planningModelId:(de==="planning"?ge:C).modelId??null},Xe=await Qs(ie,et);if(I.current!==ie)return;const Ze=no(Xe),it=so(Xe),Ie=io(Xe);b(Ze),x(Ze),A(it),S(it),z(Ie),E(Ie),s?.(Xe),n(wM(de,{executor:Ze,validator:it,planning:Ie}[de]),"success")}catch(et){if(I.current!==ie)return;de==="executor"?x(Ee):de==="validator"?S(Le):E(qe),n(Se(et)||"Failed to save model settings","error")}finally{I.current===ie&&T(null)}},[e.id,v,k,C,n,s]),be=a.useCallback(de=>{const ge=Kl(de);x(ge),!Jl(ge,v)&&ke("executor",ge)},[v,ke]),ce=a.useCallback(de=>{const ge=Kl(de);S(ge),!Jl(ge,k)&&ke("validator",ge)},[k,ke]),ve=a.useCallback(de=>{const ge=Kl(de);E(ge),!Jl(ge,C)&&ke("planning",ge)},[C,ke]),O=a.useCallback(async de=>{const ge=e.id,ie=F,Ee=de===""?null:de;$(Ee),T("thinking");try{const Le=await Qs(ge,{thinkingLevel:Ee});if(I.current!==ge)return;const qe=Le.thinkingLevel??null;V(qe),$(qe),s?.(Le);const et=i?.defaultThinkingLevel??"off";n(qe===null?`Thinking level set to default (${et})`:`Thinking level set to ${qe}`,"success")}catch(Le){if(I.current!==ge)return;$(ie),n(Se(Le)||"Failed to save thinking level","error")}finally{I.current===ge&&T(null)}},[e.id,F,i,n,s]),oe=!v.provider&&!v.modelId,te=!k.provider&&!k.modelId,pe=!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),ds().then(de=>{o(de.models),c(de.favoriteProviders),d(de.favoriteModels)}).catch(de=>p(de.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:oe?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",R.provider&&R.modelId?` (${R.provider}/${R.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[v.provider&&t.jsx(Dn,{provider:v.provider,size:"sm"}),v.provider,"/",v.modelId]})}),t.jsx(Bn,{id:"executorModel",label:"Executor Model",value:ne,onChange:be,models:r,disabled:K,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:U,favoriteModels:u,onToggleModelFavorite:Y}),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:te?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",j.provider&&j.modelId?` (${j.provider}/${j.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[k.provider&&t.jsx(Dn,{provider:k.provider,size:"sm"}),k.provider,"/",k.modelId]})}),t.jsx(Bn,{id:"validatorModel",label:"Reviewer Model",value:N,onChange:ce,models:r,disabled:K,placeholder:"Select reviewer model…",favoriteProviders:l,onToggleFavorite:U,favoriteModels:u,onToggleModelFavorite:Y}),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:pe?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:[C.provider&&t.jsx(Dn,{provider:C.provider,size:"sm"}),C.provider,"/",C.modelId]})}),t.jsx(Bn,{id:"planningModel",label:"Planning Model",value:P,onChange:ve,models:r,disabled:K,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:U,favoriteModels:u,onToggleModelFavorite:Y}),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:_??"",onChange:de=>O(de.target.value),disabled:K,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:oe&&te&&pe&&F===null?"Using project or global default models.":"Model settings are up to date."})]})]})}const SM={open:t.jsx(Io,{size:16}),closed:t.jsx(Sr,{size:16}),merged:t.jsx(Jh,{size:16})};function CM({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),A=a.useCallback(async()=>{if(h.trim()){v(!0);try{const z=await vy(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(Se(z)||"Failed to create PR","error")}finally{v(!1)}}},[e,h,p,n,l,u]),w=a.useCallback(async()=>{if(s){y(!0);try{const z=await yy(e,n);k(z),c(z.prInfo),u("PR status refreshed","success")}catch(z){u(Se(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(xs,{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(xs,{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(xs,{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:A,disabled:!h.trim()||x,children:x?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(xs,{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(sn,{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 E=SM[s.status]??t.jsx(Io,{size:16}),C=S?.blockingReasons??[];return t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(xs,{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:E}),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:w,disabled:b,title:"Refresh PR status",children:t.jsx(Mn,{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(ji,{size:14}),s.commentCount]}),t.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[t.jsx(bx,{size:14}),"View on GitHub"]})]})]})]})}const Ym=2e3;function EM(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function _M(e){return e==="agent"||e==="system"}function MM({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((E,C)=>new Date(C.createdAt).getTime()-new Date(E.createdAt).getTime()),[e.comments]),v=o.length>Ym;async function b(){const E=o.trim();if(E){g(!0);try{const C=await Xv(e.id,E,r);l(""),n?.(C),s("Comment added","success")}catch(C){s(Se(C)||"Failed to add comment","error")}finally{g(!1)}}}async function y(E){const C=d.trim();if(C){g(!0);try{const z=await Kv(e.id,E,C,r);u(null),m(""),n?.(z),s("Comment updated","success")}catch(z){s(Se(z)||"Failed to update comment","error")}finally{g(!1)}}}async function S(E){f(E);try{const C=await Gv(e.id,E,r);n?.(C),s("Comment deleted","success")}catch(C){s(Se(C)||"Failed to delete comment","error")}finally{f(null)}}function k(E){E.key==="Enter"&&(E.ctrlKey||E.metaKey)&&(E.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(E=>{const C=E.author===i,z=c===E.id,_=_M(E.author);return t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header comments-header-row",children:[t.jsxs("div",{className:"comments-author-row",children:[_?t.jsx("span",{className:"ai-guidance-badge","data-testid":"ai-guidance-badge",children:"AI Guidance"}):t.jsx("strong",{children:E.author}),t.jsx("span",{className:"detail-log-timestamp",children:EM(E)})]}),C&&!z?t.jsxs("div",{className:"comments-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{u(E.id),m(E.text)},children:"Edit"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void S(E.id),disabled:p===E.id,children:p===E.id?"Deleting…":"Delete"})]}):null]}),z?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:d,onChange:$=>m($.target.value),rows:3,className:"comments-textarea"}),t.jsxs("div",{className:"comments-edit-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{u(null),m("")},disabled:h,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void y(E.id),disabled:h||!d.trim(),children:"Save"})]})]}):t.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:E.text})]},E.id)})}),t.jsxs("div",{className:"comments-compose-form",children:[t.jsx("textarea",{value:o,onChange:E=>l(E.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," / ",Ym]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void b(),disabled:h||!o.trim()||v,children:h?"Posting…":"Add Comment"})]})]})]})}function AM(e){return e?e.slice(0,7):"Unknown"}function RM({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:AM(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 Qf(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(po.Fragment,{children:`${s}
|
|
649
|
-
`},i)})}function TM(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function PM({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);ti(g,e,"fusion:changes-diff-modal-size");const p=Si(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(Os,{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(Po,{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(bn,{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(xo,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx(Mn,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(Kt,{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(Cr,{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:TM(y.status)}),t.jsx("span",{className:"changes-diff-file-path",title:y.path,children:t.jsx("bdo",{dir:"ltr",children:y.path})}),t.jsxs("span",{className:"changes-diff-file-stat",children:["+",y.additions," -",y.deletions]})]},y.path))})]}),t.jsx("div",{className:"changes-diff-content",children:v?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"changes-diff-file-header-bar",children:[t.jsx("span",{className:"changes-diff-file-header-name",children:v.path}),t.jsxs("span",{className:"changes-diff-file-header-stats",children:["+",v.additions," -",v.deletions]})]}),v.patch?t.jsx("div",{className:"changes-diff-viewer",children:t.jsx("pre",{className:`changes-diff-patch ${m?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:Qf(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(Os,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function Xf(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function Yl(e,n,s){return t.jsxs("div",{className:"detail-section task-changes-tab",children:[n&&s&&t.jsxs("div",{className:"commit-diff-meta",children:[s.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Cr,{size:14}),t.jsx("code",{children:s.commitSha.slice(0,7)})]}),s.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(s.mergedAt).toLocaleString()]})]}),t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Os,{size:24}),t.jsxs("p",{children:[e.length," file",e.length===1?"":"s"," modified during execution."]}),t.jsx("span",{className:"task-changes-state-hint",children:n?"The recorded merge commit has no diff (likely collapsed into a squash on main). Showing file paths only — patches unavailable.":"The live worktree diff is empty. Showing the last file paths captured during execution — patches unavailable."})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:e.map(i=>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:Xf("unknown")}),t.jsx("span",{className:"changes-file-path",title:i,children:t.jsx("bdo",{dir:"ltr",children:i})})]})},i))})]})}function IM({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,A]=a.useState(!1),w=i==="done",E=w&&!!r?.commitSha,C=i==="in-progress"||i==="in-review"||E,z=a.useCallback(async()=>{if(!C){h(!1);return}try{h(!0),p(null);const D=await fp(e,void 0,s),T=D.files.map(I=>({path:I.path,status:I.status,additions:I.additions,deletions:I.deletions,patch:I.patch}));c(T),d(D.stats),T.length>0&&(x(new Set([T[0].path])),b(0))}catch(D){p(Se(D)||"Failed to load diff")}finally{h(!1)}},[e,s,C]);a.useEffect(()=>{z()},[z]);const _=D=>{x(T=>{const I=new Set(T);if(I.has(D))I.delete(D);else{I.add(D);const U=l.findIndex(Y=>Y.path===D);U!==-1&&b(U)}return I})},$=D=>{if(D<0||D>=l.length)return;const T=l[D].path;x(new Set([T])),b(D)},F=v!==null&&v>0,V=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(ss,{size:16}),t.jsxs("span",{children:["Error loading changes: ",g]})]})});if(!w&&!n)return o&&o.length>0?Yl(o,!1):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Os,{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(w&&!E){if(o&&o.length>0)return Yl(o,!0,r);const D=r?.filesChanged,T=r?.insertions,I=r?.deletions,U=D!=null||T!=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(Os,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:U?`Merge summary: ${D??0} file${(D??0)===1?"":"s"} changed, +${T??0} additions, -${I??0} deletions.`:"No merge commit was recorded for this task."})]})})}return l.length===0?o&&o.length>0?Yl(o,w,r):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Os,{size:24}),t.jsx("p",{children:"No files modified."}),t.jsx("span",{className:"task-changes-state-hint",children:w?"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:[w&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Cr,{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(Os,{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&&$(v-1),disabled:!F,title:"Previous file","aria-label":"Previous file",children:t.jsx(Po,{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:()=>V&&$(v+1),disabled:!V,title:"Next file","aria-label":"Next file",children:t.jsx(bn,{size:14})})]}),t.jsx("button",{className:`btn btn-sm ${y?"btn-primary":""}`,onClick:()=>S(D=>!D),title:y?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(xo,{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:()=>A(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:t.jsx(zo,{size:14})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map(D=>{const T=f.has(D.path);return t.jsxs("div",{className:`changes-file-item ${T?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>_(D.path),children:[t.jsx("span",{className:"changes-file-toggle",children:T?t.jsx(Yt,{size:14}):t.jsx(bn,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${D.status}`,title:D.status,children:Xf(D.status)}),t.jsx("span",{className:"changes-file-path",title:D.path,children:t.jsx("bdo",{dir:"ltr",children:D.path})}),t.jsxs("span",{className:"changes-file-stat",title:`+${D.additions} -${D.deletions}`,children:["+",D.additions," -",D.deletions]})]}),T&&D.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:Qf(D.patch)})})})]},D.path)})}),t.jsx(PM,{isOpen:k,taskId:e,files:l,stats:u,mergeDetails:r,column:i,onClose:()=>A(!1),onRefresh:z})]})}function Qm(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function $M(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function OD(e,n){const s=$M(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 DM(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}const Xm=["image/png","image/jpeg","image/gif","image/webp"];function LM(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 Zf({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:A,presetMode:w,onPresetModeChange:E,selectedPresetId:C,onSelectedPresetIdChange:z,selectedWorkflowSteps:_,onWorkflowStepsChange:$,onDefaultOnApplied:F,pendingImages:V,onImagesChange:D,tasks:T,projectId:I,disabled:U=!1,addToast:Y,isActive:ne=!0,onAutoSaveDescription:N,onPlanningMode:P,onSubtaskBreakdown:R,onClose:j,renderBelowPrimary:W,renderBelowModelConfiguration:K,hideDependencies:ke,autoExpandMoreOptionsOnSelection:be=!0,reviewLevel:ce,onReviewLevelChange:ve,executionMode:O,onExecutionModeChange:oe}){const te=(ke?!1:o.length>0)||V.length>0||_.length>0||w!=="default"||(g??bs)!==bs||f!==""||v!==""||(y||"")!==""||(k||"")!==""||ce!==void 0||O==="fast"||(c||"")!=="",[pe,de]=a.useState(!1),[ge,ie]=a.useState(be?te:!1),[Ee,Le]=a.useState(""),[qe,et]=a.useState([]),[Xe,Ze]=a.useState([]),[it,Ie]=a.useState([]),[Ke,re]=a.useState(!1),[xe,se]=a.useState(null),[Ae,ze]=a.useState([]),[me,_e]=a.useState("idle"),[Fe,nt]=a.useState(!1),[we,le]=a.useState(!1),[Te,he]=a.useState(!1),Me=a.useRef(null),We=a.useRef(null),Re=a.useRef(null),ut=a.useRef(null),Q=a.useRef(null),ue=a.useRef(null),ye=a.useRef(null),at=a.useRef(!1),X=a.useRef(te),Ye=a.useRef(n.trim()),ot=a.useRef(n.trim());a.useEffect(()=>{ne&&(re(!0),ds().then(M=>{et(M.models),Ze(M.favoriteProviders),Ie(M.favoriteModels)}).catch(()=>{}).finally(()=>re(!1)),Fo(I).then(M=>se(M)).catch(()=>se(null)),Uo(I).then(M=>ze(M.filter(ee=>ee.enabled))).catch(()=>ze([])))},[ne,I]);const ht=xe?.modelPresets||[],yt=ht.find(M=>M.id===C),vt=(ke?!1:o.length>0)||V.length>0||_.length>0||w!=="default"||(g??bs)!==bs||f!==""||v!==""||(y||"")!==""||(k||"")!==""||ce!==void 0||O==="fast"||(c||"")!=="";a.useEffect(()=>{if(e!=="create"||!ne||!xe?.autoSelectModelPreset)return;const M=(xe.defaultPresetBySize,void 0);if(M){const ee=Qm(M);z(M.id),E("preset"),x(ee.executorValue),b(ee.validatorValue)}},[ne,xe,ht,e]);const pt=a.useRef(!1);a.useEffect(()=>{if(e!=="create"||!ne||pt.current||Ae.length===0)return;const M=Ae.filter(Oe=>Oe.defaultOn);if(M.length===0)return;pt.current=!0;const ee=M.map(Oe=>Oe.id);$(ee),F?.(ee)},[e,ne,Ae]),a.useEffect(()=>{ne||(pt.current=!1)},[ne]),a.useEffect(()=>{if(!be){X.current=vt;return}vt&&!X.current&&ie(!0),X.current=vt},[vt,be]),a.useEffect(()=>{ge||(de(!1),Le(""))},[ge]),a.useEffect(()=>{e!=="edit"||!ne||ut.current&&(ut.current.focus(),ut.current.select())},[e,ne]),a.useEffect(()=>{if(!pe)return;const M=ee=>{We.current&&!We.current.contains(ee.target)&&de(!1)};return document.addEventListener("mousedown",M),()=>document.removeEventListener("mousedown",M)},[pe]),a.useEffect(()=>{(e!=="edit"||U)&&he(!1)},[e,U]),a.useEffect(()=>{if(e!=="edit"){_e("idle");return}const M=n.trim();Ye.current=M,ot.current=M,_e("idle")},[e]),a.useEffect(()=>{if(e!=="edit"||!N||!ne)return;const M=n.trim(),ee=Ye.current;if(M===ee||M===ot.current){ue.current&&(clearTimeout(ue.current),ue.current=null),at.current||_e("idle");return}return ue.current&&clearTimeout(ue.current),ue.current=setTimeout(async()=>{if(!at.current){at.current=!0,_e("saving");try{await N(M),ot.current=M,_e("saved"),ye.current&&clearTimeout(ye.current),ye.current=setTimeout(()=>{_e("idle"),ye.current=null},2e3)}catch{_e("idle")}finally{at.current=!1,ue.current=null}}},1500),()=>{ue.current&&(clearTimeout(ue.current),ue.current=null)}},[e,n,N,ne]),a.useEffect(()=>()=>{ue.current&&clearTimeout(ue.current),ye.current&&clearTimeout(ye.current)},[]),a.useEffect(()=>{if(!Fe)return;const M=ee=>{Me.current&&!Me.current.contains(ee.target)&&nt(!1)};return document.addEventListener("mousedown",M),()=>document.removeEventListener("mousedown",M)},[Fe]);const Et=a.useCallback(M=>{const ee=M.clipboardData?.items;if(ee)for(let Oe=0;Oe<ee.length;Oe++){const dt=ee[Oe];if(dt.type.startsWith("image/")){const Nt=dt.getAsFile();if(Nt&&Xm.includes(Nt.type)){M.preventDefault(),D([...V,{file:Nt,previewUrl:URL.createObjectURL(Nt)}]);return}}}},[V,D]),It=a.useCallback(M=>{M.preventDefault();const ee=M.dataTransfer.files;for(let Oe=0;Oe<ee.length;Oe++){const dt=ee[Oe];if(Xm.includes(dt.type)){D([...V,{file:dt,previewUrl:URL.createObjectURL(dt)}]);return}}},[V,D]),Bt=a.useCallback(M=>{const ee=V[M];ee&&URL.revokeObjectURL(ee.previewUrl),D(V.filter((Oe,dt)=>dt!==M))},[V,D]),_t=a.useCallback(M=>{l(o.includes(M)?o.filter(ee=>ee!==M):[...o,M])},[o,l]),Pt=(M,ee)=>M.length>ee?M.slice(0,ee)+"…":M,$t=a.useCallback(M=>{s(M.target.value);const ee=M.target;ee.style.height="auto",ee.style.height=ee.scrollHeight+"px"},[s]),Ht=a.useCallback(()=>{he(M=>!M)},[]),Gt=a.useCallback(M=>{!Te||M.key!=="Escape"||(M.preventDefault(),M.stopPropagation(),he(!1))},[Te]),Dt=a.useCallback(async M=>{const ee=n.trim();if(!(!ee||we)){le(!0);try{const Oe=await dp(ee,M,I);s(Oe),nt(!1),Y("Description refined with AI","success"),Re.current&&(Re.current.style.height="auto",Re.current.style.height=Re.current.scrollHeight+"px")}catch(Oe){const dt=up(Oe);Y(dt,"error")}finally{le(!1)}}},[n,we,Y,s,I]),Tt=a.useCallback(async M=>{const ee=Xe,dt=ee.includes(M)?ee.filter(Nt=>Nt!==M):[M,...ee];Ze(dt);try{await cn({favoriteProviders:dt,favoriteModels:it})}catch{Ze(ee)}},[Xe,it]),jt=a.useCallback(async M=>{const ee=it,dt=ee.includes(M)?ee.filter(Nt=>Nt!==M):[M,...ee];Ie(dt);try{await cn({favoriteProviders:Xe,favoriteModels:dt})}catch{Ie(ee)}},[it,Xe]),Mt=a.useCallback(M=>{if(M<=0)return;const ee=[..._];[ee[M-1],ee[M]]=[ee[M],ee[M-1]],$(ee)},[_,$]),Zt=a.useCallback(M=>{if(M>=_.length-1)return;const ee=[..._];[ee[M],ee[M+1]]=[ee[M+1],ee[M]],$(ee)},[_,$]),At=a.useCallback(M=>{$(_.filter(ee=>ee!==M))},[_,$]),H=new Map;for(const M of Ae)H.set(M.id,{name:M.name,description:M.description});const fe=T.filter(M=>!o.includes(M.id)).sort((M,ee)=>{const Oe=ee.createdAt.localeCompare(M.createdAt);if(Oe!==0)return Oe;const dt=parseInt(M.id.slice(M.id.lastIndexOf("-")+1),10)||0;return(parseInt(ee.id.slice(ee.id.lastIndexOf("-")+1),10)||0)-dt}),$e=Ee?fe.filter(M=>M.id.toLowerCase().includes(Ee.toLowerCase())||M.title&&M.title.toLowerCase().includes(Ee.toLowerCase())||M.description&&M.description.toLowerCase().includes(Ee.toLowerCase())):fe;return t.jsxs("div",{className:"task-form",onDrop:It,onDragOver:M=>M.preventDefault(),onPaste:Et,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:ut,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:i||"",onChange:M=>r(M.target.value),disabled:U})]}),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${me==="idle"?"":" is-visible"}`,"aria-live":"polite",children:me==="saving"?"Saving...":me==="saved"?"Saved":""})]}),t.jsxs("div",{className:`description-with-refine${Te?" description--fullscreen":""}`,ref:Me,onKeyDown:Gt,children:[Te&&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:Ht,"aria-label":"Collapse description",title:"Collapse description",children:t.jsx(Er,{size:14})})]}),t.jsx("textarea",{ref:Re,autoFocus:e==="create",id:"task-form-description",value:n,onChange:$t,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:U||we}),(()=>{const M=!!n.trim()&&!U;return t.jsxs(t.Fragment,{children:[!Te&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${M?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:Ht,"aria-label":"Expand description",title:"Expand description",children:t.jsx(zo,{size:14})}),M&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${we?"refine-button--loading":""}`,onClick:()=>nt(ee=>!ee),disabled:we,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(Qn,{size:12,style:{verticalAlign:"middle"}}),we?"Refining...":"Refine"]})]})})(),Fe&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:M=>M.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>Dt("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:()=>Dt("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:()=>Dt("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:()=>Dt("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"&&(P||R)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[P&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const M=n.trim();if(!M){Y("Enter a description first","error");return}j?.(),P(M)},disabled:U||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),R&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const M=n.trim();if(!M){Y("Enter a description first","error");return}j?.(),R(M)},disabled:U||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),W,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>ie(M=>!M),"aria-expanded":ge,"aria-controls":"task-form-more-options",disabled:U,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),ge?t.jsx(ui,{size:14}):t.jsx(Yt,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${ge?"":" collapsed"}`,"aria-hidden":!ge,hidden:!ge,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Attachments"}),V.length>0&&t.jsx("div",{className:"inline-create-previews",children:V.map((M,ee)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:M.previewUrl,alt:M.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>Bt(ee),disabled:U,title:"Remove image",children:"×"})]},M.previewUrl))}),t.jsx("input",{ref:Q,type:"file",accept:"image/*",onChange:M=>{const ee=M.target.files?.[0];ee&&(D([...V,{file:ee,previewUrl:URL.createObjectURL(ee)}]),M.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>Q.current?.click(),disabled:U,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:M=>u(M.target.value||void 0),disabled:U||m,children:[t.jsx("option",{value:"",children:"Use project default / local"}),(d??[]).map(M=>t.jsxs("option",{value:M.id,children:[M.name," (",DM(M.status),")"]},M.id))]}),(()=>{const M=(d??[]).find(ee=>ee.id===c);return M?t.jsx("div",{className:"task-form-node-status",children:t.jsx(qi,{status:M.status,showLabel:!0})}):null})(),t.jsx("small",{children:h??"Task override takes priority over project default node routing."})]}),!ke&&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:We,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>de(M=>!M),disabled:U,children:o.length>0?`${o.length} selected`:"Add dependencies"}),pe&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Ee,onChange:M=>Le(M.target.value),onClick:M=>M.stopPropagation()}),$e.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):$e.map(M=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(M.id)?" selected":""}`,onClick:()=>_t(M.id),onMouseDown:ee=>ee.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:M.id}),t.jsx("span",{className:"dep-dropdown-title",children:Pt(M.title||M.description||M.id,30)})]},M.id))]})]}),o.length>0&&t.jsx("div",{className:"selected-deps",children:o.map(M=>t.jsxs("span",{className:"dep-chip",children:[M,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>_t(M),disabled:U,children:"×"})]},M))})]})}),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??bs,onChange:M=>p(M.target.value),disabled:U,children:cd.map(M=>t.jsx("option",{value:M,children:M[0].toUpperCase()+M.slice(1)},M))})]}),oe&&O!==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:O,onChange:M=>oe(M.target.value),disabled:U,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),Ke?t.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):qe.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:w==="preset"?C:w,onChange:M=>{const ee=M.target.value;if(ee==="default"){E("default"),z(""),x(""),b("");return}if(ee==="custom"){E("custom"),z("");return}const Oe=ht.find(Nt=>Nt.id===ee),dt=Qm(Oe);E("preset"),z(ee),x(dt.executorValue),b(dt.validatorValue)},disabled:U,children:[t.jsx("option",{value:"default",children:"Use default"}),ht.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,ht.map(M=>t.jsx("option",{value:M.id,children:M.name},M.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),w==="preset"&&yt?t.jsxs("small",{children:["Using preset: ",yt.name]}):null,w==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>E("custom"),disabled:U,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(Bn,{id:"executor-model",label:"Executor Model",value:f,onChange:M=>{E("custom"),z(""),x(M)},models:qe,disabled:U||w==="preset",favoriteProviders:Xe,onToggleFavorite:Tt,favoriteModels:it,onToggleModelFavorite:jt})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Reviewer"}),t.jsx(Bn,{id:"validator-model",label:"Reviewer Model",value:v,onChange:M=>{E("custom"),z(""),b(M)},models:qe,disabled:U||w==="preset",favoriteProviders:Xe,onToggleFavorite:Tt,favoriteModels:it,onToggleModelFavorite:jt})]}),S&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),t.jsx(Bn,{id:"planning-model",label:"Planning Model",value:y||"",onChange:M=>{E("custom"),z(""),S(M)},models:qe,disabled:U||w==="preset",favoriteProviders:Xe,onToggleFavorite:Tt,favoriteModels:it,onToggleModelFavorite:jt})]}),A&&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:M=>A(M.target.value),disabled:U||w==="preset",children:[t.jsxs("option",{value:"",children:["Default (",xe?.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"})]})]}),ve&&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:ce??"",onChange:M=>ve(M.target.value===""?void 0:parseInt(M.target.value,10)),disabled:U,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"})]})]})]})]}),K,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:Ae.length>0&&Ae.map(M=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${M.id}`,children:[t.jsx("input",{type:"checkbox",checked:_.includes(M.id),onChange:ee=>{$(ee.target.checked?[..._,M.id]:_.filter(Oe=>Oe!==M.id))},disabled:U}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[M.name,LM(M.phase||"pre-merge",M.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:M.description})]})]},M.id))})]}),_.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:"}),_.map((M,ee)=>{const Oe=H.get(M);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${M}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:ee+1}),t.jsx("span",{className:"workflow-step-order-name",children:Oe?.name||M}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Mt(ee),disabled:U||ee===0,"data-testid":`workflow-step-move-up-${M}`,title:"Move up",children:t.jsx(ui,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Zt(ee),disabled:U||ee===_.length-1,"data-testid":`workflow-step-move-down-${M}`,title:"Move down",children:t.jsx(Yt,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>At(M),disabled:U,"data-testid":`workflow-step-remove-${M}`,title:"Remove",children:t.jsx(Kt,{size:14})})]})]},M)})]})]})]})]})}const Zm={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 zM(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function OM(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 FM(e){return e?new Date(e).toLocaleString():null}function UM(e){const n=e.split(`
|
|
650
|
-
`);return n.length<=1?e:`${n.length} lines`}function ao(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 BM({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 HM({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(j=>j.status==="pending"),{entries:S}=Jf(e,!!l&&y,o);a.useEffect(()=>{let j=!1;return Uo(o).then(W=>{j||x(W.filter(K=>K.enabled))}).catch(()=>{j||x([])}),()=>{j=!0}},[o]);const k=i??[],A=a.useMemo(()=>f.map(j=>({id:j.id,name:j.name,description:j.description,phase:j.phase||"pre-merge"})),[f]),w=a.useMemo(()=>new Map(A.map(j=>[j.id,j])),[A]),E=j=>{d(W=>({...W,[j]:!W[j]}))},C=j=>{h(W=>{const K=W[j]??"markdown";return{...W,[j]:K==="markdown"?"plain":"markdown"}})},z=j=>{p(j)},_=()=>{p(null)};a.useEffect(()=>{if(!g)return;const j=W=>{W.key==="Escape"&&_()};return document.addEventListener("keydown",j),()=>{document.removeEventListener("keydown",j)}},[g]);const $=a.useCallback((j,W)=>{if(c){if(W){if(k.includes(j)){c(k);return}c([...k,j]);return}c(k.filter(K=>K!==j))}},[c,k]),F=a.useCallback(j=>{if(!c||j<=0)return;const W=[...k];[W[j-1],W[j]]=[W[j],W[j-1]],c(W)},[c,k]),V=a.useCallback(j=>{if(!c||j>=k.length-1)return;const W=[...k];[W[j],W[j+1]]=[W[j+1],W[j]],c(W)},[c,k]),D=a.useCallback(j=>{c&&c(k.filter(W=>W!==j))},[c,k]),T=n.length>0,I=k.length>0;a.useEffect(()=>{r||b(!1)},[r]);const U=a.useMemo(()=>k.map(j=>{const W=w.get(j);return{id:j,name:W?.name||j,description:W?.description||"Step definition not found.",phase:W?.phase||"pre-merge"}}),[k,w]),Y=()=>!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:A.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:k.includes(j.id),onChange:W=>$(j.id,W.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[j.name,ao(j.phase,j.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:j.description})]})]},j.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((j,W)=>{const K=w.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:W+1}),t.jsx("span",{className:"workflow-step-order-name",children:K?.name||j}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>F(W),disabled:W===0,"data-testid":`workflow-step-move-up-${j}`,title:"Move up",children:t.jsx(ui,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>V(W),disabled:W===k.length-1,"data-testid":`workflow-step-move-down-${j}`,title:"Move down",children:t.jsx(Yt,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>D(j),"data-testid":`workflow-step-remove-${j}`,title:"Remove",children:t.jsx(Kt,{size:14})})]})]},j)})]})]}),ne=()=>{if(s)return t.jsxs("div",{className:"workflow-results-loading","data-testid":"workflow-results-loading",children:[t.jsx("div",{className:"workflow-results-spinner"}),t.jsx("span",{children:"Loading workflow results…"})]});if(!T)return t.jsxs("div",{className:"workflow-results-empty","data-testid":"workflow-results-empty",children:[t.jsx("p",{children:"No workflow steps configured for this task."}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."})]});const j=n.filter(ce=>ce.status==="passed").length,W=n.filter(ce=>ce.status==="failed").length,K=n.filter(ce=>ce.status==="skipped").length,ke=n.filter(ce=>ce.status==="pending").length,be=[`${n.length} step${n.length!==1?"s":""}`];return j>0&&be.push(`${j} passed`),W>0&&be.push(`${W} failed`),K>0&&be.push(`${K} skipped`),ke>0&&be.push(`${ke} running`),t.jsxs("div",{className:"workflow-results-list","data-testid":"workflow-results-list",children:[t.jsx("div",{className:"workflow-results-summary-bar","data-testid":"workflow-results-summary",children:be.join(" · ")}),n.map((ce,ve)=>{const O=ce.phase||"pre-merge",oe=u[ce.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${ce.status}`,"data-testid":`workflow-result-item-${ce.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[ce.workflowStepName,ao(O,ce.workflowStepId,"workflow-result-phase")]}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${ce.status}`,"data-testid":`workflow-result-badge-${ce.workflowStepId}`,children:zM(ce.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[ce.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",FM(ce.startedAt)]}),ce.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:OM(ce.startedAt,ce.completedAt)})]}),ce.status==="pending"&&ce.startedAt?t.jsx(BM,{entries:S,startedAt:ce.startedAt,stepId:ce.workflowStepId}):ce.output?t.jsxs("div",{className:"workflow-result-output-section",children:[t.jsxs("div",{className:"workflow-result-output-header",children:[t.jsx("span",{className:"workflow-result-output-label",children:"Output:"}),t.jsx("button",{className:"workflow-result-toggle",onClick:()=>E(ce.workflowStepId),"data-testid":`workflow-result-toggle-${ce.workflowStepId}`,children:oe?"Hide output":"Show output"}),!oe&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${ce.workflowStepId}`,children:UM(ce.output)}),oe&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>C(ce.workflowStepId),"data-testid":`workflow-result-mode-toggle-${ce.workflowStepId}`,title:(m[ce.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(m[ce.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-result-expand-toggle",onClick:()=>z(ce.workflowStepId),"data-testid":`workflow-result-expand-${ce.workflowStepId}`,title:"Expand output",children:t.jsx(zo,{size:12})})]})]}),oe&&t.jsx("div",{className:`workflow-result-output${(m[ce.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${ce.workflowStepId}`,children:(m[ce.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(hi,{remarkPlugins:[pi],components:Zm,children:ce.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:ce.output})})]}):null]},`${ce.workflowStepId}-${ve}`)})]})},N=r?t.jsx("button",{type:"button",className:"modal-edit-btn workflow-results-edit-toggle",onClick:()=>b(j=>!j),"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($n,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(ts,{size:14}),"Edit"]})}):null,P=!s&&!T&&I,R=r&&T;return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[P?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:[U.length," step",U.length===1?"":"s"]})]}),N]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:U.map(j=>t.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${j.id}`,children:[t.jsxs("div",{className:"workflow-configured-name",children:[j.name,ao(j.phase,j.id,"workflow-configured-phase")]}),t.jsx("p",{className:"workflow-configured-description",children:j.description})]},j.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."}),Y()]}):t.jsxs(t.Fragment,{children:[R&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:"Workflow Steps"}),N]}),ne(),Y()]}),g&&(()=>{const j=n.find(ke=>ke.workflowStepId===g);if(!j)return null;const W=m[j.workflowStepId]??"markdown",K=j.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:ke=>{ke.target===ke.currentTarget&&_()},"data-testid":"workflow-output-modal",children:t.jsxs("div",{className:"workflow-output-modal",role:"dialog","aria-modal":"true",children:[t.jsxs("div",{className:"workflow-output-modal-header",children:[t.jsxs("div",{className:"workflow-output-modal-title",children:[t.jsx("span",{className:"workflow-output-modal-name",children:j.workflowStepName}),ao(K,j.workflowStepId,"workflow-output-modal-phase")]}),t.jsxs("div",{className:"workflow-output-modal-controls",children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>C(j.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:W==="markdown"?"Switch to plain text":"Switch to markdown",children:W==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-output-modal-close",onClick:_,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:t.jsx(Kt,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${W==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:W==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(hi,{remarkPlugins:[pi],components:Zm,children:j.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:j.output})})})]})})})()]})}function qM(e){return e==="block"?"Block execution":e==="fallback-local"?"Fall back to local":"Not configured"}const VM=new Set(["planning","researching","executing","finalizing","merging"]);function WM(e){return e!==void 0&&e!=="online"}function KM({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),yo().then(_=>{o(_)}).catch(_=>{d(Se(_)||"Failed to load nodes")}).finally(()=>{c(!1)})},[]);const x=a.useMemo(()=>new Map(r.map(_=>[_.id,_])),[r]),v=a.useMemo(()=>[...r].sort((_,$)=>_.name.localeCompare($.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,A=k?`${k.name} (${k.type})`:y?`${y} (node unavailable or unknown)`:"Local (no routing configured)",w=e.column==="in-progress"||VM.has(e.status),E=w||g||l,C=a.useCallback(async _=>{if(_===m)return;const $=e.id,F=m;h(_),p(!0);try{const V=await Qs($,{nodeId:_||null});if(f.current!==$)return;h(V.nodeId??""),i?.(V),s(_?"Node override updated":"Node override cleared","success")}catch(V){if(f.current!==$)return;h(F),s(Se(V)||"Failed to update node override","error")}finally{f.current===$&&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:[k?t.jsx(qi,{status:k.status,compact:!0}):null,A,WM(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:qM(b?.unavailableNodePolicy)})]})]}),w&&y?t.jsx("div",{className:"routing-tab__info-banner",children:"Routing is locked while this task is active. Node override cannot be changed until the task is no longer active."}):null]}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Node Override"}),w?t.jsx("div",{className:"routing-tab__warning-banner",children:"Node override cannot be changed while the task is active."}):null,t.jsx("label",{className:"routing-tab__selector-label",htmlFor:`routing-node-${e.id}`,children:"Select execution node"}),t.jsxs("select",{id:`routing-node-${e.id}`,className:"select routing-tab__selector",value:m,disabled:E,onChange:_=>{C(_.target.value)},children:[t.jsx("option",{value:"",children:"Use project default"}),v.map(_=>t.jsxs("option",{value:_.id,title:`Status: ${_.status}`,children:[_.name," (",_.type,") — ",_.status]},_.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:w||g,onClick:z,children:"Clear override"})]}):null]})]})}const GM=/^[a-zA-Z0-9_-]{1,64}$/,JM=200;function eh(e){return e?new Date(e).toLocaleString():""}function YM(e,n=JM){return e.length<=n?e:e.substring(0,n)+"…"}function QM({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([]),[A,w]=a.useState(!1),[E,C]=a.useState(!1),[z,_]=a.useState(""),[$,F]=a.useState(""),[V,D]=a.useState(!1),[T,I]=a.useState(null),[U,Y]=a.useState(null),[ne,N]=a.useState(!1),P=a.useCallback(async()=>{try{const O=await Jv(e,i);l(O)}catch(O){n(Se(O)||"Failed to load documents","error")}finally{u(!1)}},[e,i,n]);a.useEffect(()=>{P()},[P]);async function R(O){d===O.key?(m(null),g(""),f(null),v(""),y(null),k([]),N(!1)):(m(O.key),g(O.content),f(null),v(""),y(null),k([]),N(!1))}async function j(O){if(b===O)y(null),k([]);else{y(O),w(!0);try{const oe=await Yv(e,O,i);k(oe)}catch(oe){n(Se(oe)||"Failed to load revisions","error")}finally{w(!1)}}}function W(){d&&(f(d),v(h))}function K(){f(null),v("")}async function ke(){if(!(!p||!x.trim())){D(!0);try{await Wd(e,p,x,{},i),f(null),v(""),await P();const O=o.find(oe=>oe.key===p);O&&g(O.content),n("Document saved","success")}catch(O){n(Se(O)||"Failed to save document","error")}finally{D(!1)}}}async function be(){const O=z.trim(),oe=$.trim();if(!O){n("Document key is required","error");return}if(!GM.test(O)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!oe){n("Content is required","error");return}D(!0);try{await Wd(e,O,oe,{},i),C(!1),_(""),F(""),await P(),n("Document created","success")}catch(te){n(Se(te)||"Failed to create document","error")}finally{D(!1)}}async function ce(O){I(O);try{await Qv(e,O,i),Y(null),I(null),d===O&&(m(null),g("")),b===O&&(y(null),k([])),await P(),n("Document deleted","success")}catch(oe){n(Se(oe)||"Failed to delete document","error")}finally{I(null)}}function ve(O){g(O.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"}),E&&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:O=>_(O.target.value),placeholder:"e.g., plan, notes, research",disabled:V}),t.jsx("span",{className:"form-hint",children:"Alphanumeric, hyphens, underscores (1-64 chars)"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-content",children:"Content"}),t.jsx("textarea",{id:"doc-content",value:$,onChange:O=>F(O.target.value),rows:6,placeholder:"Enter document content…",disabled:V})]}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{C(!1),_(""),F("")},disabled:V,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void be(),disabled:V||!z.trim()||!$.trim(),children:V?"Creating…":"Create"})]})]}),o.length===0&&!E?t.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):t.jsx("div",{className:"task-documents-list",children:o.map(O=>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(Ui,{size:14}),t.jsx("span",{className:"task-document-key",children:O.key}),t.jsxs("span",{className:"task-document-revision-badge",children:["v",O.revision]})]}),t.jsxs("div",{className:"task-document-meta",children:[t.jsx("span",{className:"task-document-author",children:O.author}),t.jsx("span",{className:"task-document-timestamp",children:eh(O.updatedAt||O.createdAt)})]})]}),d===O.key&&p!==O.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:()=>N(oe=>!oe),"aria-label":ne?"Switch to plain text":"Switch to markdown","aria-pressed":ne,title:ne?"Switch to plain text":"Switch to markdown",children:ne?"Markdown":"Plain"})}),t.jsx("div",{className:"task-document-content",children:ne?t.jsx("div",{className:"task-document-content-markdown",children:t.jsx("div",{className:"markdown-body",children:t.jsx(hi,{remarkPlugins:[pi],children:h})})}):t.jsx("pre",{className:"task-document-content-text",children:h})}),b===O.key&&t.jsxs("div",{className:"task-document-revisions",children:[t.jsx("h5",{children:"Revision History"}),A?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(oe=>oe.revision<O.revision).sort((oe,te)=>te.revision-oe.revision).map(oe=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>ve(oe),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",oe.revision]}),t.jsx("span",{className:"revision-author",children:oe.author}),t.jsx("span",{className:"revision-timestamp",children:eh(oe.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:YM(oe.content,100)})]},oe.id))})]})]}),p===O.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:x,onChange:oe=>v(oe.target.value),rows:10,disabled:V}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:K,disabled:V,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void ke(),disabled:V||!x.trim(),children:V?"Saving…":"Save"})]})]}),t.jsxs("div",{className:"task-document-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>void R(O),children:d===O.key?t.jsxs(t.Fragment,{children:[t.jsx(ui,{size:14})," Collapse"]}):t.jsxs(t.Fragment,{children:[t.jsx(Yt,{size:14})," Expand"]})}),d===O.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void j(O.key),children:[t.jsx(mr,{size:14})," History"]}),r&&p!==O.key&&t.jsx("button",{className:"btn btn-sm",onClick:W,children:"Edit"}),r&&(U===O.key?t.jsxs("div",{className:"confirm-delete-actions",children:[t.jsx("span",{children:"Delete?"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void ce(O.key),disabled:T===O.key,children:T===O.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Y(null),disabled:T===O.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>Y(O.key),children:t.jsx(nn,{size:14})}))]})]})]},O.key))}),r&&!E&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>C(!0),children:[t.jsx(sn,{size:14})," New Document"]})]})}function ro(e){return e.toLocaleString()}function Ql(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function Ka(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 XM(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 ZM({tokenUsage:e,loading:n,task:s}){const i=Rp(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=XM(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:Ka(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:Ka(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:Ka(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} (${Ka(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} (${Ka(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 ${Ql(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:ro(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:ro(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:ro(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:ro(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:Ql(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:Ql(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}const eA=new Set(["planning","researching","executing","finalizing","merging"]);function tA(e,n){return wp(e,n)}function nA(e,n){return Np(e,n)}function sA(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 iA(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const i=sA(n);return i||Sp(e,s)}function aA(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 rA(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 oA(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function lA(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 th(e,n){return e.length>n?e.slice(0,n)+"…":e}function nh(e=[],n=[]){return e.length===n.length&&e.every((s,i)=>s===n[i])}function Xl(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function Zl(e){return e.trim()}function cA(e){const n=e.trim();return n.length>0?n:void 0}function Ga(e){return typeof e=="string"&&cd.includes(e)?e:bs}function Ja(e){return e==="fast"?"fast":"standard"}const ec=200,dA=new Set(["triage","todo"]);function uA({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 Z=!1;return S(!0),b(null),fr(e.id,n).then(Be=>{Z||(b(Be),S(!1))}).catch(()=>{Z||S(!1)}),()=>{Z=!0}},[e.id,n]);const k=v?{...v,...e,prompt:v.prompt,log:v.log}:{...e,prompt:""},A=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[w,E]=a.useState("activity"),[C,z]=a.useState(!1),[_,$]=a.useState(e.attachments||[]),[F,V]=a.useState(!1),[D,T]=a.useState(e.dependencies||[]),[I,U]=a.useState(!1),[Y,ne]=a.useState(""),[N,P]=a.useState(null),[R,j]=a.useState([]),[W,K]=a.useState(!1),[ke,be]=a.useState(!1),[ce,ve]=a.useState(!1),[O,oe]=a.useState(!1),[te,pe]=a.useState(!1),[de,ge]=a.useState(k.prompt||""),[ie,Ee]=a.useState(""),[Le,qe]=a.useState(!1),[et,Xe]=a.useState(""),[Ze,it]=a.useState(!1),[Ie,Ke]=a.useState(!1),[re,xe]=a.useState(e.title||""),[se,Ae]=a.useState(e.description||""),[ze,me]=a.useState(e.dependencies||[]),[_e,Fe]=a.useState(""),[nt,we]=a.useState(""),[le,Te]=a.useState(""),[he,Me]=a.useState(""),[We,Re]=a.useState("default"),[ut,Q]=a.useState(void 0),[ue,ye]=a.useState(bs),[at,X]=a.useState(e.nodeId),[Ye,ot]=a.useState(Ja(e.executionMode)),[ht,yt]=a.useState(""),[vt,pt]=a.useState(e.enabledWorkflowSteps||[]),[Et,It]=a.useState(e.sourceIssue?.provider??""),[Bt,_t]=a.useState(e.sourceIssue?.repository??""),[Pt,$t]=a.useState(e.sourceIssue?.externalIssueId??""),[Ht,Gt]=a.useState(e.sourceIssue?.url??""),[Dt,Tt]=a.useState([]),[jt,Mt]=a.useState(!1),Zt=a.useRef(!1),[At,H]=a.useState(!1),[fe,$e]=a.useState(!1),[M,ee]=a.useState(!1),Oe=a.useRef(null),dt=a.useRef(null),Nt=a.useRef(null),Ct=a.useRef(null);ti(Ct,!0,"fusion:task-detail-modal-size");const{getSlotsForId:Rt}=yp(n),un=Rt("task-detail-tab");a.useEffect(()=>(Zt.current=!0,()=>{Zt.current=!1}),[]);const[mn,Nn]=a.useState(void 0),[Qt,An]=a.useState([]),[Ne,ae]=a.useState(!1),[Ge,ct]=a.useState(e.enabledWorkflowSteps||[]),Lt=e.column==="in-progress"||eA.has(e.status);a.useEffect(()=>{xe(e.title||""),Ae(e.description||""),It(e.sourceIssue?.provider??""),_t(e.sourceIssue?.repository??""),$t(e.sourceIssue?.externalIssueId??""),Gt(e.sourceIssue?.url??""),ot(Ja(e.executionMode)),ee(!1),Ke(!1)},[e.id,e.title,e.description,e.sourceIssue,e.executionMode]),a.useEffect(()=>{ct(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),a.useEffect(()=>{let Z=!1;return Fo(n).then(Be=>{Z||Nn(Be)}).catch(()=>{}),()=>{Z=!0}},[n]),a.useEffect(()=>{if(f!=="workflow")return;let Z=!1;return ae(!0),yj(e.id,n).then(Be=>{Z||An(Be)}).catch(Be=>{Z||h(`Failed to load workflow results: ${Se(Be)}`,"error")}).finally(()=>{Z||ae(!1)}),()=>{Z=!0}},[f,e.id,n,h]),a.useEffect(()=>{if(f!=="workflow")return;const Z=n?`?projectId=${encodeURIComponent(n)}`:"",Be=lt=>{try{const Ot=JSON.parse(lt.data);Ot.id===e.id&&Array.isArray(Ot.workflowStepResults)&&An(Ot.workflowStepResults)}catch{}};return Hs(`/api/events${Z}`,{events:{"task:updated":Be}})},[f,e.id,n]),a.useEffect(()=>{I||ne("")},[I]),a.useEffect(()=>{if(!e.assignedAgentId){P(null);return}const Z=R.find(lt=>lt.id===e.assignedAgentId);if(Z){P(Z);return}let Be=!1;return hp(e.assignedAgentId,n).then(lt=>{Be||P(lt)}).catch(()=>{Be||P(null)}),()=>{Be=!0}},[e.assignedAgentId,n,R]),a.useEffect(()=>{K(!1)},[e.id]),a.useEffect(()=>{if(!(At||fe))return;const Be=lt=>{const Ot=lt.target,Vs=Oe.current?.contains(Ot),ps=Nt.current?.contains(Ot);!Vs&&At&&H(!1),!ps&&fe&&$e(!1)};return document.addEventListener("mousedown",Be),()=>document.removeEventListener("mousedown",Be)},[At,fe]),a.useEffect(()=>{if(!(At||fe))return;const Be=lt=>{lt.key==="Escape"&&(lt.stopPropagation(),At&&H(!1),fe&&$e(!1))};return document.addEventListener("keydown",Be),()=>document.removeEventListener("keydown",Be)},[At,fe]),a.useEffect(()=>{pe(!1),ge(k.prompt||""),Ee("")},[e.id,k.prompt]);const qt=dA.has(e.column)&&!jt,En=a.useCallback(()=>{if(!qt)return;Ke(!0),xe(e.title||""),Ae(e.description||""),me(e.dependencies||[]);const Z=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",Be=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",lt=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";Fe(Z),we(Be),Te(lt),Me(e.thinkingLevel??""),X(e.nodeId),Re(Z||Be||lt?"custom":"default"),yt(""),pt(e.enabledWorkflowSteps||[]),ot(Ja(e.executionMode)),It(e.sourceIssue?.provider??""),_t(e.sourceIssue?.repository??""),$t(e.sourceIssue?.externalIssueId??""),Gt(e.sourceIssue?.url??""),Tt([]),Q(e.reviewLevel),ye(Ga(e.priority))},[qt,e]),hn=a.useCallback(()=>{Ke(!1),xe(e.title||""),Ae(e.description||""),me(e.dependencies||[]),X(e.nodeId),It(e.sourceIssue?.provider??""),_t(e.sourceIssue?.repository??""),$t(e.sourceIssue?.externalIssueId??""),Gt(e.sourceIssue?.url??""),ye(Ga(e.priority)),ot(Ja(e.executionMode)),Dt.forEach(Z=>URL.revokeObjectURL(Z.previewUrl)),Tt([])},[e.title,e.description,e.dependencies,e.nodeId,e.priority,e.executionMode,Dt]),Vt=a.useCallback(async()=>{Mt(!0);try{const Z={},Be=re.trim(),lt=se.trim();Be&&Be!==(e.title??"")&&(Z.title=Be),lt&<!==(e.description??"")&&(Z.description=lt),nh(ze,e.dependencies??[])||(Z.dependencies=ze),nh(vt,e.enabledWorkflowSteps??[])||(Z.enabledWorkflowSteps=vt);const Ot=Xl(_e),Vs=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";_e!==Vs&&(Z.modelProvider=Ot?.provider??null,Z.modelId=Ot?.modelId??null);const ps=Xl(nt),xi=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";nt!==xi&&(Z.validatorModelProvider=ps?.provider??null,Z.validatorModelId=ps?.modelId??null);const La=Xl(le),Ur=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";le!==Ur&&(Z.planningModelProvider=La?.provider??null,Z.planningModelId=La?.modelId??null);const Xi=e.thinkingLevel??"";he!==Xi&&(Z.thinkingLevel=he!==""?he:null),(e.nodeId??void 0)!==at&&(Z.nodeId=at??null);const tl=e.reviewLevel;ut!==tl&&(Z.reviewLevel=ut);const nl=Ga(e.priority);ue!==nl&&(Z.priority=ue);const sl=Ja(e.executionMode);Ye!==sl&&(Z.executionMode=Ye==="fast"?"fast":null);const Mi=Zl(Et),Zi=Zl(Bt),Ai=Zl(Pt),ea=cA(Ht);if(Mi.length===0&&Zi.length===0&&Ai.length===0&&!ea)e.sourceIssue&&(Z.sourceIssue=null);else{if(!Mi||!Zi||!Ai){h("Source issue provider, repository, and issue identifier are required","error"),Mt(!1);return}const Ns=Number.parseInt(Ai,10),ri=e.sourceIssue?.issueNumber??Ns;if(!Number.isFinite(ri)||ri<=0){h("Source issue identifier must be numeric for new metadata","error"),Mt(!1);return}const B={provider:Mi,repository:Zi,externalIssueId:Ai,issueNumber:ri,...ea?{url:ea}:{}},Ce=e.sourceIssue;(!Ce||Ce.provider!==B.provider||Ce.repository!==B.repository||Ce.externalIssueId!==B.externalIssueId||Ce.issueNumber!==B.issueNumber||(Ce.url??void 0)!==B.url)&&(Z.sourceIssue=B)}if(Object.keys(Z).length>0){const Ns=await Qs(e.id,Z,n);m?.(Ns)}if(Dt.length>0){const Ns=[];for(const ri of Dt)try{const B=await gr(e.id,ri.file,n);$(Ce=>[...Ce,B])}catch{Ns.push(ri.file.name)}Ns.length>0&&h(`Failed to upload: ${Ns.join(", ")}`,"error")}Dt.forEach(Ns=>URL.revokeObjectURL(Ns.previewUrl)),Tt([]),h(`Updated ${e.id}`,"success"),Ke(!1)}catch(Z){h(`Failed to update ${e.id}: ${Se(Z)}`,"error")}finally{Zt.current&&Mt(!1)}},[e,re,se,ze,_e,nt,le,he,at,ut,ue,Ye,vt,Et,Bt,Pt,Ht,Dt,h,n,m]),J=a.useCallback(async Z=>{try{await Qs(e.id,{description:Z},n),h("Description saved","success")}catch(Be){h(`Failed to save: ${Se(Be)}`,"error")}},[e.id,h,n]),Pe=a.useCallback(Z=>{Ie&&(Z.key==="Escape"?(Z.preventDefault(),hn()):Z.key==="Enter"&&(Z.ctrlKey||Z.metaKey)&&(Z.preventDefault(),Vt()))},[Ie,hn,Vt]);a.useEffect(()=>{if(Ie)return document.addEventListener("keydown",Pe),()=>document.removeEventListener("keydown",Pe)},[Ie,Pe]);const Qe=a.useRef(null),{nodes:tt}=Vo(),{confirm:mt}=Bs(),{entries:St,loading:zt,loadMore:Sn,hasMore:an,total:kt,loadingMore:as}=Jf(e.id,f==="logs"&&w==="agent-log",n);a.useEffect(()=>{const Z=Be=>{Be.key==="Escape"&&!Ie&&i()};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[i,Ie]);const js=Si(i),Ps=a.useCallback(async Z=>{try{await o(e.id,Z),i(),h(`Moved to ${Pn[Z]}`,"success")}catch(Be){h(Se(Be),"error")}},[e.id,o,i,h]),Is=a.useCallback(async()=>{if(await mt({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0}))try{await l(e.id),i(),h(`Deleted ${e.id}`,"info")}catch(Be){const lt=lA(Be);if(!lt||lt.dependentIds.length===0){h(Se(Be),"error");return}const Ot=lt.dependentIds.join(", ");if(!await mt({title:"Force Delete Task",message:`${e.id} is a dependency of ${Ot}.
|
|
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(ps){h(Se(ps),"error")}}},[e.id,l,i,h,mt]),si=a.useCallback(async()=>{await mt({title:"Merge Task",message:`Merge ${e.id} into the current branch?`})&&(i(),h(`Merging ${e.id}...`,"info"),c(e.id).then(Be=>{const lt=Be.merged?`Merged ${e.id} (branch: ${Be.branch})`:`Closed ${e.id} (${Be.error||"no branch to merge"})`;h(lt,"success")}).catch(Be=>{h(Se(Be),"error")}))},[e.id,c,i,h,mt]),ks=a.useCallback(()=>{u&&(i(),u(e.id).then(()=>{h(`Retried ${e.id}`,"success")}).catch(Z=>{h(Se(Z),"error")}))},[e.id,u,i,h]),$s=a.useCallback(async()=>{if(!(!d||!await mt({title:"Duplicate Task",message:`Duplicate ${e.id}? This will create a new task in Triage with the same description and prompt.`})))try{const Be=await d(e.id);i(),h(`Duplicated ${e.id} → ${Be.id}`,"success")}catch(Be){h(Se(Be),"error")}},[e.id,d,i,h,mt]),Yi=a.useCallback(async()=>{try{e.paused?(await zv(e.id,n),h(`Unpaused ${e.id}`,"success")):(await rp(e.id,n),h(`Paused ${e.id}`,"success")),i()}catch(Z){h(Se(Z),"error")}},[e.id,e.paused,i,h]),gi=a.useCallback(async()=>{try{await Bv(e.id,n),h(`Plan approved — ${e.id} moved to Todo`,"success"),i()}catch(Z){h(Se(Z),"error")}},[e.id,i,h]),ii=a.useCallback(async()=>{if(await mt({title:"Reject Plan",message:"Reject this plan? The specification will be discarded and regenerated.",danger:!0}))try{await Hv(e.id,n),h(`Plan rejected — ${e.id} returned to Planning for replanning`,"info"),i()}catch(Be){h(Se(Be),"error")}},[e.id,i,h,mt]),ms=a.useCallback(async()=>{if(await mt({title:"Rebuild Plan",message:"Rebuild the plan for this task? The task will move to planning for replanning."}))try{await ey(e.id,n),i(),h(`Replanning ${e.id}...`,"info")}catch(Be){h(Se(Be),"error")}},[e.id,n,i,h,mt]),qs=a.useCallback(()=>{qe(!0),Xe("")},[]),q=a.useCallback(()=>{H(!1),$e(!1)},[]),je=a.useCallback(Z=>{q(),Ps(Z)},[q]),Je=a.useCallback(Z=>{q(),Z()},[q]),bt=a.useCallback(()=>{q(),si()},[q,si]),gt=a.useCallback(()=>{qe(!1),Xe(""),it(!1)},[]),yn=a.useCallback(async()=>{if(!et.trim()){h("Please enter feedback describing what needs refinement","error");return}if(et.length>2e3){h("Feedback must be 2000 characters or less","error");return}it(!0);try{const Z=await ty(e.id,et.trim(),n);h(`Refinement task created: ${Z.id}`,"success"),i()}catch(Z){h(Se(Z),"error")}finally{it(!1)}},[e.id,et,h,i]),en=a.useCallback(async Z=>{V(!0);try{const Be=await gr(e.id,Z,n);$(lt=>[...lt,Be]),h("Screenshot attached","success")}catch(Be){h(Se(Be),"error")}finally{V(!1)}},[e.id,h]),rn=a.useCallback(async Z=>{const Be=Z.target.files?.[0];Be&&(await en(Be),Qe.current&&(Qe.current.value=""))},[en]);a.useEffect(()=>{const Z=Be=>{const lt=Be.clipboardData?.items;if(lt)for(let Ot=0;Ot<lt.length;Ot++){const Vs=lt[Ot];if(Vs.type.startsWith("image/")){const ps=Vs.getAsFile();if(ps){Be.preventDefault(),en(ps);return}}}};return document.addEventListener("paste",Z),()=>document.removeEventListener("paste",Z)},[en]);const pn=a.useCallback(Z=>{Z.preventDefault()},[]),In=a.useCallback(Z=>{Z.preventDefault();const Be=Z.dataTransfer.files;for(let lt=0;lt<Be.length;lt++){const Ot=Be[lt];if(Ot.type.startsWith("image/")){en(Ot);return}}},[en]),qn=a.useCallback(async Z=>{try{await Wv(e.id,Z,n),$(Be=>Be.filter(lt=>lt.filename!==Z)),h("Attachment deleted","info")}catch(Be){h(Se(Be),"error")}},[e.id,h]),Vn=a.useCallback(async Z=>{const Be=Ge;ct(Z);try{const lt=await Qs(e.id,{enabledWorkflowSteps:Z},n);h("Workflow steps updated","success"),m?.(lt)}catch(lt){ct(Be),h(`Failed to update workflow steps: ${Se(lt)}`,"error")}},[e.id,n,Ge,m,h]),_n=a.useCallback(async()=>{be(!0);try{const Z=await Ma(void 0,n);j(Z),K(!0)}catch(Z){h(`Failed to load agents: ${Se(Z)}`,"error"),K(!1)}finally{be(!1)}},[n,h]),Wn=a.useCallback(async Z=>{try{const Be=await su(e.id,Z,n),lt=R.find(Ot=>Ot.id===Z)??null;P(lt||(Ot=>Ot?.id===Z?Ot:null)),K(!1),m?.(Be),h("Assigned agent updated","success")}catch(Be){h(`Failed to assign agent: ${Se(Be)}`,"error")}},[e.id,n,R,m,h]),Ln=a.useCallback(async()=>{try{const Z=await su(e.id,null,n);P(null),K(!1),m?.(Z),h("Agent unassigned","success")}catch(Z){h(`Failed to unassign agent: ${Se(Z)}`,"error")}},[e.id,n,m,h]),hs=a.useCallback(async Z=>{const Be=[...D,Z];T(Be);try{await Qs(e.id,{dependencies:Be},n)}catch(lt){T(D),h(Se(lt),"error")}},[e.id,D,h]),jn=a.useCallback(async(Z,Be)=>{Z.stopPropagation();const lt=D.filter(Ot=>Ot!==Be);T(lt);try{await Qs(e.id,{dependencies:lt},n)}catch(Ot){T(D),h(Se(Ot),"error")}},[e.id,D,h]),zn=a.useCallback(async Z=>{try{const Be=await fr(Z,n);r(Be)}catch{h(`Failed to load dependency ${Z}`,"error")}},[r,h]),rs=a.useCallback(async Z=>{ve(!0);try{await Qs(k.id,{prompt:Z},n),h("Spec updated","success"),v&&(v.prompt=Z)}catch(Be){throw h(Se(Be),"error"),Be}finally{ve(!1)}},[k,v,h]),ws=a.useCallback(async Z=>{oe(!0);try{await Zv(e.id,Z,n),h("AI revision requested. Task moved to planning.","success"),i()}catch(Be){const lt=Se(Be);lt.includes("done")||lt.includes("archived")?h("Cannot request revision: Task must be in 'triage', 'todo', 'in-progress', or 'in-review' column.","error"):h(lt,"error")}finally{oe(!1)}},[e.id,h,i]),Zn=a.useCallback(()=>{pe(!0),ge(k.prompt||""),Ee("")},[k.prompt]),on=a.useCallback(()=>{pe(!1),ge(k.prompt||""),Ee("")},[k.prompt]),On=a.useCallback(async()=>{if(de===(k.prompt||"")){on();return}pe(!1);try{await rs(de)}catch(Z){throw pe(!0),Z}},[de,k.prompt,rs,on]),Ds=a.useCallback(async()=>{ie.trim()&&await ws(ie.trim())},[ie,ws]),Zo=a.useCallback(Z=>{Z.key==="Escape"?(Z.preventDefault(),on()):Z.key==="Enter"&&(Z.ctrlKey||Z.metaKey)&&(Z.preventDefault(),On())},[on,On]),Ei=s.filter(Z=>Z.id!==e.id&&!D.includes(Z.id)).sort((Z,Be)=>{const lt=Be.createdAt.localeCompare(Z.createdAt);if(lt!==0)return lt;const Ot=parseInt(Z.id.slice(Z.id.lastIndexOf("-")+1),10)||0;return(parseInt(Be.id.slice(Be.id.lastIndexOf("-")+1),10)||0)-Ot}),Lr=N?.name??e.assignedAgentId??null,Ls=a.useMemo(()=>{const Z=[];return k.modelProvider&&Z.push(k.modelProvider),k.validatorModelProvider&&!Z.includes(k.validatorModelProvider)&&Z.push(k.validatorModelProvider),k.planningModelProvider&&!Z.includes(k.planningModelProvider)&&Z.push(k.planningModelProvider),Z},[k.modelProvider,k.validatorModelProvider,k.planningModelProvider]),zr=Rc[e.column]||[],Or=["todo","in-progress"],Fr=e.column==="in-review"?Or:zr,Kn=Fr[0],Ia=Fr.slice(1),Rn=Ia.length>0,ai=a.useCallback(()=>{H(!1),dt.current?.focus()},[]),_i=a.useCallback(Z=>{if(!Rn){Kn&&je(Kn);return}const Be=Z.currentTarget.querySelector(".detail-move-btn__arrow");if(!!(Z.target instanceof Element&&Z.target.closest(".detail-move-btn__arrow")||Be&&Z.clientX>0&&Z.clientX>=Be.getBoundingClientRect().left)){H(Ot=>!Ot),$e(!1);return}Kn&&je(Kn)},[Rn,Kn,je]),$a=a.useCallback(Z=>{!Rn||!(Z.key==="ArrowDown"||Z.altKey&&Z.key==="ArrowDown")||(Z.preventDefault(),H(!0),$e(!1))},[Rn]),Qi=a.useCallback(Z=>{Z.key==="Escape"&&(Z.preventDefault(),Z.stopPropagation(),ai())},[ai]);a.useEffect(()=>{if(!At)return;Oe.current?.querySelector(".detail-move-menu-item")?.focus()},[At]);const el={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…"},Da=e.status?el[e.status]:void 0;return t.jsx("div",{className:"modal-overlay open",...js,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg task-detail-modal",ref:Ct,onDragOver:pn,onDrop:In,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:Pn[e.column]})]}),t.jsxs("div",{className:"modal-header-actions",children:[!Ie&&qt&&t.jsx("button",{className:"modal-edit-btn",onClick:En,title:"Edit task","aria-label":"Edit task",children:t.jsx(ts,{size:14})}),t.jsx("button",{className:"modal-close",onClick:i,"aria-label":"Close",children:"×"})]})]}),t.jsxs("div",{className:`detail-body${f==="logs"&&w==="agent-log"&&!Ie?" detail-body--agent-log":""}`,children:[Ie?t.jsx("div",{className:"modal-edit-form",children:t.jsx(Zf,{mode:"edit",title:re,onTitleChange:xe,description:se,onDescriptionChange:Ae,dependencies:ze,onDependenciesChange:me,executorModel:_e,onExecutorModelChange:Fe,validatorModel:nt,onValidatorModelChange:we,planningModel:le,onPlanningModelChange:Te,thinkingLevel:he,onThinkingLevelChange:Me,presetMode:We,onPresetModeChange:Re,selectedPresetId:ht,onSelectedPresetIdChange:yt,selectedWorkflowSteps:vt,onWorkflowStepsChange:pt,pendingImages:Dt,onImagesChange:Tt,tasks:s.filter(Z=>Z.id!==e.id),projectId:n,disabled:jt,addToast:h,isActive:Ie,onAutoSaveDescription:J,reviewLevel:ut,onReviewLevelChange:Q,priority:ue,onPriorityChange:ye,nodeId:at,onNodeIdChange:X,nodeOptions:tt,nodeOverrideDisabled:Lt,nodeOverrideDisabledReason:Lt?"Execution node override is locked while a task is active/in progress.":void 0,executionMode:Ye,onExecutionModeChange:ot,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:Et,onChange:Z=>It(Z.target.value),disabled:jt,"data-testid":"task-source-provider-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Repository (e.g. owner/repo)",value:Bt,onChange:Z=>_t(Z.target.value),disabled:jt,"data-testid":"task-source-repository-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:Pt,onChange:Z=>$t(Z.target.value),disabled:jt,"data-testid":"task-source-external-id-input"}),t.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:Ht,onChange:Z=>Gt(Z.target.value),disabled:jt,"data-testid":"task-source-url-input"})]}),t.jsx("small",{children:"Leave all fields empty to clear source issue metadata."})]})})}):t.jsxs(t.Fragment,{children:[(()=>{const Z=e.title||e.description||e.id,Be=!C&&Z.length>ec;return t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"detail-title",children:Be?Z.slice(0,ec)+"…":Z}),Z.length>ec&&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--${Ga(e.priority)}`,children:["Priority: ",Ga(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"}),un.map((Z,Be)=>{const lt=`plugin-${Be}`;return t.jsx("button",{className:`detail-tab${f===lt?" detail-tab-active":""}`,onClick:()=>x(lt),children:Z.slot.label},`plugin-tab-${Z.pluginId}`)})]}),f==="workflow"?t.jsx("div",{className:"detail-section",children:t.jsx(HM,{taskId:e.id,results:Qt,loading:Ne,enabledWorkflowSteps:Ge,canEdit:qt,projectId:n,isTaskInProgress:e.column==="in-progress"&&e.status!=="paused",onWorkflowStepsChange:Vn})}):f==="model"?t.jsx("div",{className:"detail-section",children:t.jsx(NM,{task:e,addToast:h,onTaskUpdated:m,settings:mn})}):f==="logs"?t.jsxs("div",{className:`detail-section${w==="agent-log"?" detail-section--agent-log":""}`,children:[t.jsxs("div",{className:"log-subview-toggle",children:[t.jsx("button",{className:`log-subview-btn${w==="activity"?" log-subview-btn-active":""}`,onClick:()=>E("activity"),children:"Activity"}),t.jsx("button",{className:`log-subview-btn${w==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>E("agent-log"),children:"Agent Log"})]}),w==="agent-log"?t.jsx(vM,{entries:St,loading:zt,executorModel:tA(e,mn),validatorModel:nA(e,mn),planningModel:iA(e,St,mn),hasMore:an,onLoadMore:Sn,loadingMore:as,totalCount:kt}):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((Z,Be)=>t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-timestamp",children:rA(Z.timestamp)}),t.jsx("span",{className:"detail-log-action",children:Z.action})]}),Z.outcome&&t.jsx("div",{className:"detail-log-outcome",children:Z.outcome})]},Be))}):t.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):f==="changes"?t.jsx(IM,{taskId:e.id,worktree:e.worktree,projectId:n,column:e.column,mergeDetails:e.mergeDetails,modifiedFiles:e.modifiedFiles}):f==="comments"?t.jsx(MM,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):f==="documents"?t.jsx(QM,{taskId:e.id,addToast:h,projectId:n,onTaskUpdated:m,canEdit:qt}):typeof f=="string"&&f.startsWith("plugin-")?t.jsx("div",{className:"detail-section",children:t.jsx(Ho,{slotId:"task-detail-tab",projectId:n})}):f==="stats"?t.jsx("div",{className:"detail-section",children:t.jsx(ZM,{tokenUsage:k.tokenUsage,loading:y,task:k})}):f==="routing"?t.jsx("div",{className:"detail-section",children:t.jsx(KM,{task:e,settings:mn,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(hi,{remarkPlugins:[pi],children:e.summary})})]}),t.jsx(RM,{task:e}),e.sourceIssue&&t.jsxs("div",{className:"detail-section detail-source-section",children:[t.jsxs("div",{className:"detail-source-header",children:[t.jsxs("div",{className:"detail-source-summary",children:[t.jsx("span",{className:"detail-source-label",children:"Source issue"}),e.sourceIssue.url?t.jsx("a",{className:"detail-source-link detail-source-number",href:e.sourceIssue.url,target:"_blank",rel:"noopener noreferrer",children:`(#${e.sourceIssue.issueNumber})`}):t.jsx("span",{className:"detail-source-number",children:`(#${e.sourceIssue.issueNumber})`})]}),t.jsx("button",{type:"button",className:"detail-source-toggle","aria-expanded":M,"aria-label":M?"Collapse source issue details":"Expand source issue details",onClick:()=>ee(Z=>!Z),children:t.jsx(bn,{size:16,className:M?"detail-source-chevron--expanded":void 0})})]}),M&&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:[Ls.length>0&&t.jsx("span",{className:"detail-provider-icons","data-testid":"detail-provider-icons",children:Ls.map(Z=>t.jsx(Dn,{provider:Z,size:"sm"},Z))}),t.jsxs("span",{className:"detail-meta-label",children:[t.jsx(kn,{size:14,style:{verticalAlign:"middle",marginRight:6}}),"Agent"]})]}),t.jsxs("div",{className:"detail-agent-actions",children:[Lr?t.jsxs("span",{className:"detail-agent-chip",children:[t.jsx(kn,{size:14}),Lr,t.jsx("button",{className:"detail-agent-clear",onClick:()=>void Ln(),title:"Unassign agent",children:t.jsx(Kt,{size:12})})]}):t.jsx("button",{className:"btn btn-sm",onClick:()=>{W?K(!1):_n()},children:"Assign Agent"}),W&&t.jsxs("div",{className:"agent-picker-dropdown",children:[ke&&t.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!ke&&R.filter(Z=>Z.state!=="terminated").map(Z=>t.jsxs("button",{className:`agent-picker-item${e.assignedAgentId===Z.id?" selected":""}`,onClick:()=>void Wn(Z.id),children:[t.jsx(kn,{size:14}),t.jsx("span",{className:"agent-picker-name",children:Z.name}),t.jsx("span",{className:"agent-picker-role",children:Z.role})]},Z.id)),!ke&&R.filter(Z=>Z.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((Z,Be)=>t.jsx("div",{className:`step-progress-segment step-progress-segment--${Z.status}`,"data-tooltip":`${Z.name} (${Z.status})`,style:{backgroundColor:aA(Z.status)}},Be))}),t.jsxs("span",{className:"step-progress-label",children:[k.steps.filter(Z=>Z.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:[!te&&t.jsx("div",{className:"detail-spec-edit-trigger",children:t.jsx("button",{className:"btn btn-sm",onClick:Zn,children:"Edit"})}),te?t.jsxs("div",{className:"spec-editor-edit-mode",children:[t.jsx("textarea",{className:"spec-editor-textarea",value:de,onChange:Z=>ge(Z.target.value),onKeyDown:Zo,disabled:ce,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:on,disabled:ce,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void On(),disabled:de===(k.prompt||"")||ce,children:ce?"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:ie,onChange:Z=>Ee(Z.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:O,rows:4,maxLength:2e3}),t.jsxs("div",{className:"spec-editor-revision-actions",children:[t.jsxs("span",{className:"spec-editor-char-count",children:[ie.length,"/2000"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Ds(),disabled:!ie.trim()||O,children:O?"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(hi,{remarkPlugins:[pi],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"}),_.length>0?t.jsx("div",{className:"detail-attachments-grid",children:_.map(Z=>{const Be=ei(`/api/tasks/${e.id}/attachments/${Z.filename}`);return t.jsxs("div",{className:"detail-attachment-card",children:[t.jsx("a",{className:"detail-attachment-link",href:Be,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{src:Be,alt:Z.originalName,className:"detail-attachment-image"})}),t.jsxs("div",{className:"detail-attachment-meta",children:[Z.originalName," (",oA(Z.size),")"]}),t.jsx("button",{className:"detail-attachment-delete",onClick:()=>qn(Z.filename),title:"Delete attachment",children:"×"})]},Z.filename)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no attachments)"}),t.jsx("input",{className:"detail-hidden-file-input",ref:Qe,type:"file",accept:"image/*",onChange:rn}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Qe.current?.click(),disabled:F,children:F?"Uploading…":"Attach Screenshot"})]}),t.jsxs("div",{className:"detail-deps",children:[t.jsx("h4",{children:"Dependencies"}),D.length>0?t.jsx("ul",{className:"detail-dep-list",children:D.map(Z=>{const Be=s.find(Ot=>Ot.id===Z),lt=Be?.title||Be?.description||Z;return t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>zn(Z),onKeyDown:Ot=>{(Ot.key==="Enter"||Ot.key===" ")&&(Ot.preventDefault(),zn(Z))},role:"link",tabIndex:0,title:`Click to view ${Z}`,children:[t.jsx("span",{className:"detail-dep-id",children:Z}),t.jsx("span",{className:"detail-dep-label",children:th(lt,40)})]}),t.jsx("button",{className:"dep-remove-btn",onClick:Ot=>jn(Ot,Z),title:`Remove dependency ${Z}`,children:"×"})]},Z)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no dependencies)"}),t.jsxs("div",{className:"dep-trigger-wrap",children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{I&&ne(""),U(Z=>!Z)},children:"Add Dependency"}),I&&(()=>{const Z=Y.toLowerCase(),Be=Z?Ei.filter(lt=>lt.id.toLowerCase().includes(Z)||lt.title&<.title.toLowerCase().includes(Z)||lt.description&<.description.toLowerCase().includes(Z)):Ei;return t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Y,onChange:lt=>ne(lt.target.value),onClick:lt=>lt.stopPropagation()}),Be.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Be.map(lt=>t.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{hs(lt.id),U(!1)},children:[t.jsx("span",{className:"dep-dropdown-id",children:lt.id}),t.jsx("span",{className:"dep-dropdown-title",children:th(lt.title||lt.description||lt.id,30)})]},lt.id))]})})()]})]}),e.column==="in-review"&&t.jsx(CM,{taskId:e.id,projectId:n,prInfo:e.prInfo,automationStatus:e.status??null,autoMerge:mn?.autoMerge??!1,prAuthAvailable:g??!1,onPrCreated:Z=>{e.prInfo=Z,h(`PR #${Z.number} created`,"success")},onPrUpdated:Z=>{e.prInfo=Z},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:hn,disabled:jt,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Vt,disabled:jt,children:jt?"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:gi,children:"Approve Plan"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:ii,children:"Reject Plan"})]}),e.column==="triage"&&e.status!=="awaiting-approval"&&!A&&t.jsx("button",{className:"btn btn-sm btn-danger",onClick:Is,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(e.column!=="triage"||e.status==="awaiting-approval"||A||e.paused)&&t.jsxs("div",{className:"detail-actions-dropdown",ref:Nt,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{$e(Z=>!Z),H(!1)},"aria-haspopup":"menu","aria-expanded":fe,children:["Actions",t.jsx(Yt,{size:12})]}),fe&&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:()=>Je(Is),children:"Delete"}),d&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Je($s),children:"Duplicate"}),(e.column==="done"||e.column==="in-review")&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Je(qs),children:"Refine"}),t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Je(ms),children:"Respecify"}),A&&u&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Je(ks),children:"Retry"}),e.column!=="done"&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Je(Yi),children:e.paused?"Unpause":"Pause"})]})]}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("div",{className:"detail-move-dropdown",ref:Oe,children:e.column==="in-review"?t.jsxs("div",{className:"detail-move-actions-in-review",children:[t.jsxs("div",{children:[t.jsxs("button",{ref:dt,className:"btn btn-primary btn-sm detail-move-btn",onClick:_i,onKeyDown:$a,disabled:!Kn,"aria-label":Kn?`Move to ${Pn[Kn]}`:void 0,"aria-haspopup":Rn?"menu":void 0,"aria-expanded":Rn?At:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",Kn?Pn[Kn]:""]}),Rn&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(Yt,{size:12})})]}),At&&Rn&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:Qi,children:Ia.map(Z=>t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>je(Z),onKeyDown:Qi,children:Z==="in-progress"?"Back to In Progress":`Move to ${Pn[Z]}`},Z))})]}),Da?t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:Da}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:bt,children:"Merge & Close"})]}):t.jsxs("div",{children:[t.jsxs("button",{ref:dt,className:"btn btn-primary btn-sm detail-move-btn",onClick:_i,onKeyDown:$a,disabled:!Kn,"aria-label":Kn?`Move to ${Pn[Kn]}`:void 0,"aria-haspopup":Rn?"menu":void 0,"aria-expanded":Rn?At:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",Kn?Pn[Kn]:""]}),Rn&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(Yt,{size:12})})]}),At&&Rn&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:Qi,children:Ia.map(Z=>t.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>je(Z),onKeyDown:Qi,children:["Move to ",Pn[Z]]},Z))})]})})]})}),Le&&t.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:gt,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal detail-refine-modal",onClick:Z=>Z.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{className:"detail-refine-title",children:"Refine"}),t.jsx("button",{className:"modal-close",onClick:gt,"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:et,onChange:Z=>Xe(Z.target.value),placeholder:"Enter your feedback here...",rows:6,maxLength:2e3,autoFocus:!0}),t.jsxs("div",{className:"detail-refine-input-group",children:[t.jsxs("div",{className:"detail-refine-char-count",children:[et.length,"/2000 characters"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:yn,disabled:!et.trim()||Ze,children:Ze?"Creating...":"Create Refinement Task"})]})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:gt,disabled:Ze,children:"Cancel"})})]})})]})})}const mA=640;function hA({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([]),[A,w]=a.useState(null),[E,C]=a.useState(null),[z,_]=a.useState(!1),[$,F]=a.useState([]),[V,D]=a.useState(!1),[T,I]=a.useState(""),U=a.useRef(!1),Y=a.useRef(null);ti(Y,e,"fusion:github-modal-size");const ne=Si(n),[N,P]=a.useState(!1),[R,j]=a.useState("list"),W=a.useRef(null),K=new Set;for(const me of i){const _e=me.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);_e&&K.add(_e[1]);const Fe=me.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);Fe&&K.add(Fe[1])}a.useEffect(()=>{if(e)return l(""),u(""),m(""),v([]),y(null),k([]),w(null),f("issues"),C(null),_(!1),F([]),D(!0),I(""),W.current=null,U.current=!0,hy().then(me=>{if(U.current)if(F(me),D(!1),me.length===1){const _e=me[0];l(_e.owner),u(_e.repo),I(_e.name)}else me.length>1&&(l(""),u(""),I(""))}).catch(()=>{U.current&&D(!1)}),()=>{U.current=!1}},[e]);const ke=a.useCallback(me=>{if(I(me),me==="")l(""),u("");else{const _e=$.find(Fe=>Fe.name===me);_e&&(l(_e.owner),u(_e.repo))}},[$]),be=a.useCallback(async()=>{if(!o.trim()||!c.trim()){C("Repository must be selected");return}g(!0),C(null),v([]),y(null);try{const me=d.split(",").map(Fe=>Fe.trim()).filter(Boolean),_e=await cy(o.trim(),c.trim(),30,me.length>0?me:void 0);v(_e),_e.length===0&&C("No open issues found")}catch(me){C(Se(me)||"Failed to fetch issues")}finally{g(!1)}},[o,c,d]),ce=a.useCallback(async()=>{if(!o.trim()||!c.trim()){C("Repository must be selected");return}g(!0),C(null),k([]),w(null);try{const me=await uy(o.trim(),c.trim(),30);k(me),me.length===0&&C("No open pull requests found")}catch(me){C(Se(me)||"Failed to fetch pull requests")}finally{g(!1)}},[o,c]);a.useEffect(()=>{if(!e||!o.trim()||!c.trim()||h||z)return;const me={owner:o.trim(),repo:c.trim(),labels:d.trim(),tab:p};W.current?.owner===me.owner&&W.current?.repo===me.repo&&W.current?.labels===me.labels&&W.current?.tab===me.tab||(W.current=me,p==="issues"?be():ce())},[o,c,d,p,e,h,z,be,ce]),a.useEffect(()=>{if(!e)return;const me=_e=>{_e.key==="Escape"&&n()};return document.addEventListener("keydown",me),()=>document.removeEventListener("keydown",me)},[e,n]),a.useEffect(()=>{if(!e)return;const me=()=>{P(window.innerWidth<=mA)};return me(),window.addEventListener("resize",me),()=>window.removeEventListener("resize",me)},[e]);const ve=a.useCallback(me=>{y(me),N&&j("preview")},[N]),O=a.useCallback(me=>{w(me),N&&j("preview")},[N]),oe=a.useCallback(()=>{j("list")},[]),te=a.useCallback(async()=>{if(p==="issues"){if(b===null)return;_(!0),C(null);try{const me=await dy(o.trim(),c.trim(),b,r);s(me),y(null),N&&R==="preview"&&j("list")}catch(me){const _e=Se(me);_e?.includes("already imported")?C(_e):C(_e||"Failed to import issue")}finally{_(!1)}}else{if(A===null)return;_(!0),C(null);try{const me=await my(o.trim(),c.trim(),A,r);s(me),w(null),N&&R==="preview"&&j("list")}catch(me){const _e=Se(me);_e?.includes("already imported")?C(_e):C(_e||"Failed to import pull request")}finally{_(!1)}}},[p,b,A,o,c,s,N,R]),pe=x.find(me=>me.number===b),de=S.find(me=>me.number===A);if(!e)return null;const ge=$.length>0,ie=$.length===1,Ee=x.filter(me=>K.has(me.html_url)).length,Le=S.filter(me=>K.has(me.html_url)).length,qe=E==="No open issues found",et=E==="No open pull requests found",Xe=p==="issues"?qe:et,Ze=!!E&&!qe&&x.length===0&&!h,it=!!E&&!et&&S.length===0&&!h,Ie=p==="issues"?Ze:it,Ke=h||x.length>0||qe||Ze,re=h||S.length>0||et||it,xe=p==="issues"?Ke:re,se=!!E&&x.length>0&&!qe,Ae=!!E&&S.length>0&&!et,ze=p==="issues"?se:Ae;return t.jsx("div",{className:"modal-overlay open",...ne,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg github-import-modal",ref:Y,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"),w(null)},disabled:h||z,children:[t.jsx(Io,{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(xs,{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:V?t.jsxs("div",{className:"github-import-toolbar__loading",role:"status","aria-live":"polite",children:[t.jsx(rt,{size:16,className:"spin"}),t.jsx("span",{children:"Detecting…"})]}):ge?ie?t.jsxs("div",{className:"github-import-remote-pill","data-testid":"github-import-single-remote",children:[t.jsx("span",{className:"github-import-remote-pill__name",children:$[0].name}),t.jsxs("span",{className:"github-import-remote-pill__repo",children:[$[0].owner,"/",$[0].repo]})]}):t.jsxs("div",{className:"github-import-remote-select",children:[t.jsx("label",{htmlFor:"gh-remote",className:"visually-hidden",children:"Repository"}),t.jsxs("select",{id:"gh-remote",value:T,onChange:me=>ke(me.target.value),disabled:h||z,"aria-label":"Select Git remote",children:[t.jsx("option",{value:"",children:"Select remote…"}),$.map(me=>t.jsxs("option",{value:me.name,children:[me.name," (",me.owner,"/",me.repo,")"]},me.name))]})]}):t.jsx("span",{className:"github-import-toolbar__no-remote",children:"No remotes"})}),t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--filter",children:p==="issues"?t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"gh-labels",className:"visually-hidden",children:"Filter by labels"}),t.jsx("input",{id:"gh-labels",type:"text",placeholder:"Filter: bug,enhancement…",value:d,onChange:me=>m(me.target.value),onKeyDown:me=>me.key==="Enter"&&be(),disabled:h||z||!ge,"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"?be:ce,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(rt,{size:14,className:"spin"}):t.jsx(Mn,{size:14}),t.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!V&&!ge&&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:E}),t.jsxs("div",{className:"github-import-workspace",children:[t.jsxs("section",{className:`github-import-list-pane ${N?"mobile":""} ${R==="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:[Le," imported"]})]})]}),t.jsxs("div",{className:"github-import-pane-content",children:[!xe&&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(rt,{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:E})]})}),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(me=>{const _e=K.has(me.html_url);return t.jsxs("div",{className:`issue-item ${b===me.number?"selected":""} ${_e?"imported":""}`,onClick:()=>!_e&&ve(me.number),children:[t.jsx("input",{type:"radio",name:"issue",checked:b===me.number,onChange:()=>ve(me.number),disabled:_e,"aria-label":`Select issue #${me.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",me.number]}),t.jsx("span",{className:"issue-title",children:me.title})]}),me.labels.length>0&&t.jsx("span",{className:"issue-labels",children:me.labels.map(Fe=>t.jsx("span",{className:"label-chip",children:Fe.name},Fe.name))})]}),_e&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},me.number)})}),p==="pulls"&&S.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:S.map(me=>{const _e=K.has(me.html_url);return t.jsxs("div",{className:`issue-item ${A===me.number?"selected":""} ${_e?"imported":""}`,onClick:()=>!_e&&O(me.number),children:[t.jsx("input",{type:"radio",name:"pull",checked:A===me.number,onChange:()=>O(me.number),disabled:_e,"aria-label":`Select pull request #${me.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",me.number]}),t.jsx("span",{className:"issue-title",children:me.title})]}),t.jsxs("span",{className:"pull-branch-info",children:[me.headBranch," → ",me.baseBranch]})]}),_e&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},me.number)})})]})]}),t.jsxs("section",{className:`github-import-preview-pane ${N?"mobile":""} ${R==="preview"?"active":""}`,"data-testid":"github-import-preview-pane","aria-labelledby":"github-import-preview-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[N&&t.jsxs("button",{className:"github-import-back-button",onClick:oe,"data-testid":"github-import-back-button","aria-label":`Back to ${p==="issues"?"issues":"pull requests"} list`,children:[t.jsx(_a,{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"&&pe?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Issue #",pe.number]}),t.jsx("div",{className:"preview-title",children:pe.title}),t.jsx("div",{className:"preview-body",children:pe.body?pe.body.slice(0,200)+(pe.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"&&de?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Pull Request #",de.number]}),t.jsx("div",{className:"preview-title",children:de.title}),t.jsxs("div",{className:"preview-branch",children:[t.jsx("strong",{children:"Branch:"})," ",de.headBranch," → ",de.baseBranch]}),t.jsx("div",{className:"preview-body",children:de.body?de.body.slice(0,200)+(de.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:te,disabled:(p==="issues"?b===null:A===null)||z,children:z?t.jsx(rt,{size:14,className:"spin"}):"Import"})]})]})})}const pA=["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 fA(e,n){return e&&n?`${e}/${n}`:""}function gA(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 xA({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),A=a.useRef(!1),[w,E]=a.useState(""),[C,z]=a.useState(!0),[_,$]=a.useState(!1),[F,V]=a.useState(!1),[D,T]=a.useState(null),[I,U]=a.useState(0),Y=a.useRef(null),ne=a.useRef(null),N=a.useRef(null),P=a.useRef(null),[R,j]=a.useState(c??null),W=a.useMemo(()=>Gi(),[]),{isLockedByOther:K,takeControl:ke,isLoading:be}=Ko(e?R:null),{activeTabMap:ce,broadcastUpdate:ve,broadcastCompleted:O,broadcastLock:oe,broadcastUnlock:te,broadcastHeartbeat:pe}=Ra(),[de,ge]=a.useState(void 0),[ie,Ee]=a.useState(void 0),[Le,qe]=a.useState([]),[et,Xe]=a.useState(!1),[Ze,it]=a.useState(null),[Ie,Ke]=a.useState([]),[re,xe]=a.useState([]),se=a.useRef(null),[Ae,ze]=a.useState([]),[me,_e]=a.useState(!1),[Fe,nt]=a.useState(c??null),[we,le]=a.useState(!!c),[Te,he]=a.useState(null),Me=a.useRef(!1),We=a.useRef(null);ti(ne,e,"fusion:planning-modal-size"),a.useEffect(()=>{const H=We.current;if(!H)return;H.scrollHeight-H.scrollTop-H.clientHeight<32&&(H.scrollTop=H.scrollHeight)},[w]),a.useEffect(()=>{if(m.type!=="loading"){T(null),U(0);return}const H=Date.now();T(H),U(0);const fe=setInterval(()=>{U(Math.max(0,Math.floor((Date.now()-H)/1e3)))},1e3);return()=>clearInterval(fe)},[m.type]);const Re=a.useCallback(()=>{d(""),h({type:"initial"}),p(null),x([]),b([]),S(null),E(""),$(!1),V(!1),ge(void 0),Ee(void 0),P.current=null,j(null)},[]),ut=fA(de,ie),Q=a.useCallback((H,fe)=>{if(!H||!fe)return"Using default";const $e=Le.find(M=>M.provider===H&&M.id===fe);return $e?`${$e.provider}/${$e.id}`:`${H}/${fe}`},[Le]),ue=a.useCallback(async()=>{Xe(!0),it(null);try{const H=await ds();qe(H.models),Ke(H.favoriteProviders),xe(H.favoriteModels)}catch(H){it(Se(H)||"Failed to load models")}finally{Xe(!1)}},[]),ye=a.useCallback(H=>{Ke(fe=>{const $e=fe,ee=$e.includes(H)?$e.filter(Oe=>Oe!==H):[H,...$e];return cn({favoriteProviders:ee,favoriteModels:re}).catch(()=>{Ke($e)}),ee})},[re]),at=a.useCallback(H=>{xe(fe=>{const $e=fe,ee=$e.includes(H)?$e.filter(Oe=>Oe!==H):[H,...$e];return cn({favoriteProviders:Ie,favoriteModels:ee}).catch(()=>{xe($e)}),ee})},[Ie]),X=a.useCallback(H=>{N.current?.close();const fe=mj(H,l,{onThinking:$e=>{E(M=>M+$e),ve({sessionId:H,status:"generating",needsInput:!1,owningTabId:W,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onQuestion:$e=>{$(!1),V(!1),ia(l),h({type:"question",session:{sessionId:H,currentQuestion:$e,summary:null}}),E(""),ve({sessionId:H,status:"awaiting_input",needsInput:!0,owningTabId:W,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onSummary:$e=>{$(!1),V(!1),ia(l),h({type:"summary",session:{sessionId:H,currentQuestion:null,summary:$e},summary:$e}),S($e),E(""),ve({sessionId:H,status:"complete",needsInput:!1,owningTabId:W,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onError:$e=>{const M=$e||"Session failed while contacting the AI.";$(!0),(async()=>{try{const ee=await di(H);if(ee&&(ee.status==="generating"||ee.status==="awaiting_input")){X(H);return}}catch{}$(!1),V(!1),p(null),h(ee=>ee.type==="question"||ee.type==="summary"||ee.type==="error"?{type:"error",session:ee.session,errorMessage:M}:{type:"error",session:{sessionId:H,currentQuestion:null,summary:null},errorMessage:M}),E(""),P.current=H,ve({sessionId:H,status:"error",needsInput:!1,owningTabId:W,type:"planning",title:u.trim()||"Planning session",projectId:l??null}),O({sessionId:H,status:"error"})})()},onComplete:()=>{$(!1),V(!1),P.current=null,O({sessionId:H,status:"complete"})},onConnectionStateChange:$e=>{$($e==="reconnecting")}});N.current=fe},[O,ve,u,l,W]),Ye=a.useCallback(async H=>{const fe=H??u;if(fe.trim()){p(null),E(""),b([]),x([]),$(!1),h({type:"loading"});try{const $e=de&&ie?{planningModelProvider:de,planningModelId:ie}:void 0,{sessionId:M}=await Jy(fe.trim(),l,$e);P.current=M,j(M),nt(M),X(M),x([])}catch($e){$(!1),p(Se($e)||"Failed to start planning session"),h({type:"initial"}),P.current=null,j(null)}}},[X,u,ie,de,l]);a.useEffect(()=>{e&&m.type==="initial"&&Y.current?.focus()},[e,m.type]),a.useEffect(()=>{e&&ue()},[e,ue]),a.useEffect(()=>{if(e&&o&&!k.current&&m.type==="initial"){d(o);const H=setTimeout(()=>{k.current=!0,Ye(o)},0);return()=>clearTimeout(H)}else if(e&&!o&&!k.current&&!A.current&&m.type==="initial"){A.current=!0;const H=l1(l);H&&d(H)}},[e,o,m.type,Ye,l]);const ot=a.useCallback(async H=>{N.current?.close(),N.current=null,p(null),E(""),x([]),b([]),S(null),V(!1),h({type:"loading"});try{const fe=await di(H);if(!fe){nt(null),le(!1),h({type:"initial"});return}P.current=H,j(H);const $e=ya(fe.conversationHistory);if(b($e),x($e.map(M=>M.response).filter(M=>!!(M&&typeof M=="object"&&!Array.isArray(M)))),fe.status==="awaiting_input"&&fe.currentQuestion){ia(l);const M=JSON.parse(fe.currentQuestion);h({type:"question",session:{sessionId:H,currentQuestion:M,summary:null}}),fe.thinkingOutput&&E(fe.thinkingOutput),X(H)}else if(fe.status==="complete"&&fe.result){ia(l);const M=JSON.parse(fe.result);h({type:"summary",session:{sessionId:H,currentQuestion:null,summary:M},summary:M}),S(M)}else fe.status==="generating"?(h({type:"loading"}),fe.thinkingOutput&&E(fe.thinkingOutput),X(H)):fe.status==="error"&&h({type:"error",session:{sessionId:H,currentQuestion:null,summary:null},errorMessage:fe.error||"Session failed"})}catch{p("Failed to load session"),h({type:"initial"})}},[X,l]);a.useEffect(()=>{!e||!c||P.current!==c&&(nt(c),le(!0),ot(c))},[e,c,ot]),a.useEffect(()=>{e&&Fe&&(c&&c===Fe||N.current?.isConnected()||ot(Fe))},[e]);const ht=a.useCallback(async()=>{_e(!0);try{const fe=(await ad(l)).filter($e=>$e.type==="planning").sort(($e,M)=>Date.parse(M.updatedAt)-Date.parse($e.updatedAt));ze(fe)}catch{}finally{_e(!1)}},[l]);a.useEffect(()=>{e&&ht()},[e,ht]),a.useEffect(()=>{if(!e)return;const H=l?`?projectId=${encodeURIComponent(l)}`:"",fe=M=>{try{const ee=JSON.parse(M.data);if(ee.type!=="planning")return;ze(Oe=>{const dt=Oe.findIndex(Ct=>Ct.id===ee.id);return(dt>=0?[...Oe.slice(0,dt),ee,...Oe.slice(dt+1)]:[ee,...Oe]).sort((Ct,Rt)=>Date.parse(Rt.updatedAt)-Date.parse(Ct.updatedAt))})}catch{}},$e=M=>{try{const ee=JSON.parse(M.data);ze(Oe=>Oe.filter(dt=>dt.id!==ee))}catch{}};return Hs(`/api/events${H}`,{events:{"ai_session:updated":fe,"ai_session:deleted":$e},onReconnect:()=>{ht()}})},[e,l,ht]);const yt=a.useCallback(H=>{if(Fe===H){le(!0);return}nt(H),le(!0),ot(H)},[ot,Fe]),vt=a.useCallback(()=>{N.current?.close(),N.current=null,Re(),nt(null),le(!0)},[Re]),pt=a.useCallback(()=>{le(!1)},[]),Et=a.useCallback(async H=>{const fe=M=>M==="generating"||M==="awaiting_input",$e=Ae.find(M=>M.id===H);if($e&&fe($e.status))try{await cp(H,l,W)}catch{}try{await bp(H)}catch{}O({sessionId:H,status:"complete",timestamp:Date.now()}),ze(M=>M.filter(ee=>ee.id!==H)),Fe===H&&(N.current?.close(),N.current=null,Re(),nt(null),le(!1)),he(null)},[O,Ae,l,Re,Fe,W]);a.useEffect(()=>{e||(k.current=!1,A.current=!1,$(!1),V(!1),j(null))},[e]),a.useEffect(()=>{if(!e){se.current&&(te(se.current,W),se.current=null);return}if(R&&se.current!==R){se.current&&te(se.current,W),oe(R,W),se.current=R;return}!R&&se.current&&(te(se.current,W),se.current=null)},[oe,te,e,R,W]),a.useEffect(()=>{if(!e||!R||se.current!==R)return;pe(W);const H=setInterval(()=>{pe(W)},3e4);return()=>{clearInterval(H)}},[pe,e,R,W]),a.useEffect(()=>()=>{N.current?.close(),N.current=null,se.current&&(te(se.current,W),se.current=null)},[te,W]),a.useEffect(()=>{if(!e)return;const H=()=>{N.current?.close(),N.current=null};return window.addEventListener("beforeunload",H),()=>window.removeEventListener("beforeunload",H)},[e]);const It=a.useCallback(()=>{u&&m.type==="initial"&&o1(u,l),N.current?.close(),N.current=null,$(!1),V(!1),n()},[u,n,l,m.type]);a.useEffect(()=>{if(!e)return;const H=fe=>{fe.key==="Escape"&&It()};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[e,It]);const Bt=a.useCallback(async H=>{if(m.type!=="question")return;const{session:fe}=m,$e=fe.sessionId,M=fe.currentQuestion;if(!M){p("No active question in session");return}p(null),x(ee=>[...ee,H]),b(ee=>[...ee,{question:M,response:H}]),h({type:"loading"}),E("");try{await Yy($e,H,l,W)}catch(ee){p(Se(ee)||"Failed to submit response"),h({type:"question",session:fe})}},[l,W,m]),_t=a.useCallback(async()=>{const H=P.current;if(H){try{await Xy(H,l,W)}catch{}N.current?.close(),N.current=null,$(!1),V(!1),h({type:"error",session:{sessionId:H,currentQuestion:null,summary:null},errorMessage:"Generation stopped by user. You can retry or start a new session."}),E("")}},[l,W]),Pt=a.useCallback(async()=>{if(m.type!=="error")return;const H=m.session;p(null),V(!0),E(""),h({type:"loading"}),X(H.sessionId);try{P.current=H.sessionId,j(H.sessionId),await Qy(H.sessionId,l,W)}catch(fe){let $e=fe;if((Se(fe)||"").includes("not in an error state"))try{const ee=await di(H.sessionId);if(!ee)throw new Error("Failed to refresh planning session.");if(P.current=ee.id,j(ee.id),ee.status==="generating")E(ee.thinkingOutput??""),h({type:"loading"});else if(ee.status==="awaiting_input"){if(!ee.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const Oe=JSON.parse(ee.currentQuestion);ia(l),h({type:"question",session:{sessionId:ee.id,currentQuestion:Oe,summary:null}}),N.current?.isConnected()||X(ee.id)}else if(ee.status==="complete"){if(!ee.result)throw new Error("Planning session is complete but has no result.");const Oe=JSON.parse(ee.result);ia(l),h({type:"summary",session:{sessionId:ee.id,currentQuestion:null,summary:Oe},summary:Oe}),S(Oe)}else ee.status==="error"&&h({type:"error",session:{sessionId:ee.id,currentQuestion:null,summary:null},errorMessage:ee.error||"Retry failed. Please try again."});$(!1);return}catch(ee){$e=ee}N.current?.close(),N.current=null,h({type:"error",session:H,errorMessage:Se($e)||"Retry failed. Please try again."}),$(!1)}finally{V(!1)}},[X,l,W,m]),$t=a.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const H=m.session.sessionId,fe=await Zy(H,y??void 0,l);s(fe),nt(null),ze($e=>$e.filter(M=>M.id!==H)),O({sessionId:H,status:"complete",timestamp:Date.now()}),It()}catch(H){p(Se(H)||"Failed to create task"),h({type:"summary",session:m.session,summary:m.summary})}}},[O,y,m,l,s,It]),Ht=a.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const H=await ej(m.session.sessionId,y??void 0,l);j(H.sessionId),h({type:"breakdown",sessionId:H.sessionId,subtasks:H.subtasks,dirty:!1})}catch(H){p(Se(H)||"Failed to start breakdown"),h({type:"summary",session:m.session,summary:m.summary})}}},[y,m,l]),Gt=a.useCallback(async()=>{if(m.type==="breakdown"){p(null),h({type:"creating"});try{const H=m.sessionId,fe=await tj(H,m.subtasks,l);i(fe.tasks),ze($e=>$e.filter(M=>M.id!==H)),O({sessionId:H,status:"complete",timestamp:Date.now()}),d(""),h({type:"initial"}),p(null),x([]),b([]),S(null),E(""),ge(void 0),Ee(void 0),P.current=null,j(null),nt(null),n()}catch(H){p(Se(H)||"Failed to create tasks"),h({type:"breakdown",sessionId:m.sessionId,subtasks:m.subtasks,dirty:m.dirty})}}},[O,m,i,n,l]),Dt=a.useCallback(()=>{if(m.type==="question"&&f.length>0){const H=f.slice(0,-1);x(H),h({type:"question",session:m.session})}},[m,f]),Tt=()=>m.type==="question"?Math.min(f.length+1,3):3,jt=R?ce.get(R):null,Mt=jt&&jt.tabId!==W,Zt=!!(Mt&&!jt.stale),At=K&&(!Mt||jt.stale);return e?t.jsx("div",{className:"modal-overlay open",onMouseDown:H=>{Me.current=H.target===H.currentTarget},onClick:H=>{H.target===H.currentTarget&&Me.current&&It(),Me.current=!1},role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",ref:ne,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[we&&t.jsx("button",{className:"modal-back planning-mobile-back",onClick:pt,"aria-label":"Back to sessions",title:"Back to sessions",children:t.jsx(Po,{size:18})}),t.jsx(Zs,{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:It,"aria-label":"Close",children:t.jsx(Kt,{size:20})})})]}),t.jsxs("div",{className:`planning-modal-body planning-modal-body--split ${we?"planning-modal-body--show-detail":"planning-modal-body--show-list"}`,children:[t.jsx(kA,{sessions:Ae,loading:me,selectedSessionId:Fe,pendingDeleteId:Te,onSelectSession:yt,onNewSession:vt,onRequestDelete:he,onConfirmDelete:H=>void Et(H),onCancelDelete:()=>he(null)}),t.jsxs("div",{className:"planning-detail",children:[g&&t.jsx("div",{className:"form-error planning-error",children:g}),_&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Zt&&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:Y,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:H=>d(H.target.value),onKeyDown:H=>{H.key==="Enter"&&!H.shiftKey&&u.trim()&&(H.preventDefault(),Ye())}})]}),t.jsxs("div",{className:"planning-examples",children:[t.jsx("span",{className:"planning-examples-label",children:"Try an example:"}),t.jsx("div",{className:"planning-example-chips",children:pA.map((H,fe)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>d(H),children:H.length>40?H.slice(0,40)+"...":H},fe))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"planning-modal-model",className:"form-label",children:["Planning Model",et&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(Bn,{id:"planning-modal-model",label:"Planning Model",value:ut,onChange:H=>{const{provider:fe,modelId:$e}=gA(H);ge(fe),Ee($e)},models:Le,disabled:et,favoriteProviders:Ie,onToggleFavorite:ye,favoriteModels:re,onToggleModelFavorite:at}),Ze&&t.jsxs("div",{className:"form-hint form-hint-error",children:[Ze," ",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 ${de&&ie?"model-badge-custom":"model-badge-default"}`,children:Q(de,ie)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>Ye(),disabled:!u.trim(),children:[t.jsx(Zs,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),m.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(rt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:w?"AI is thinking...":"Generating next question..."}),D&&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 _t(),children:[t.jsx(tx,{size:14}),t.jsx("span",{className:"icon-ml-6",children:"Stop"})]})}),C&&w&&t.jsx("div",{className:"planning-thinking-output",ref:We,children:t.jsx("pre",{children:w})})]})]}),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(Ts,{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 Pt(),disabled:F,children:[F?t.jsx(rt,{size:14,className:"spin"}):t.jsx(Mn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:F?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:It,disabled:F,children:"Dismiss"})]})]})]})}),m.type==="creating"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(rt,{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(bA,{question:m.session.currentQuestion,progress:Tt(),historyEntries:v,onSubmit:Bt,onBack:f.length>0?Dt:void 0})}),m.type==="summary"&&y&&t.jsx(vA,{summary:y,historyEntries:v,onSummaryChange:S,tasks:r,onCreateTask:$t,onBreakIntoTasks:Ht,onRefine:()=>{h({type:"question",session:m.session})},isLoading:!1}),m.type==="breakdown"&&t.jsx(jA,{subtasks:m.subtasks,dirty:m.dirty,isLoading:!1,onUpdateSubtasks:H=>h({...m,subtasks:H,dirty:!0}),onCreateTasks:Gt,onBack:()=>{const fe={sessionId:m.sessionId,currentQuestion:null,summary:y??null};y&&h({type:"summary",session:fe,summary:y})}})]}),K&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Lo,{size:16}),t.jsx("span",{children:At?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),At&&t.jsx("button",{type:"button",onClick:()=>{ke()},disabled:be,className:"btn btn-primary session-lock-take-control",children:be?"Taking control...":"Take Control"})]})})]})]})}):null}function bA({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(Ts,{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(vn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!1?"selected":""}`,onClick:()=>l({[e.id]:!1}),children:[t.jsx(Kt,{size:18}),"No"]})]})]})]})]})]}),t.jsxs("div",{className:"planning-actions",children:[r&&t.jsxs("button",{className:"btn",onClick:r,children:[t.jsx(_a,{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(Nr,{size:16,className:"icon-ml-4"})]})]})]})}function vA({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(Ts,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(vn,{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(_a,{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(rt,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Do,{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(rt,{size:16,className:"spin icon-mr-8"}),"Creating..."]}):t.jsxs(t.Fragment,{children:[t.jsx(vn,{size:16,className:"icon-mr-8"}),"Create Task"]})})]})]})]})}function sh(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 yA(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function jA({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(E=>!E.title.trim())?!0:sh(e),[e]),f=a.useCallback((E,C)=>{i(e.map(z=>z.id===E?{...z,...C}:z))},[e,i]),x=a.useCallback(()=>{i([...e,yA(e.length+1)])},[e,i]),v=a.useCallback(E=>{i(e.filter(C=>C.id!==E).map(C=>({...C,dependsOn:C.dependsOn.filter(z=>z!==E)})))},[e,i]),b=a.useCallback((E,C)=>{if(C<0||C>=e.length)return;const z=[...e],[_]=z.splice(E,1);z.splice(C,0,_),i(z)},[e,i]),y=a.useCallback(E=>C=>{c(E),C.dataTransfer.setData("text/plain",E),C.dataTransfer.effectAllowed="move"},[]),S=a.useCallback(()=>{c(null),d(null),h(null)},[]),k=a.useCallback(E=>C=>{if(C.preventDefault(),E===l)return;const z=C.currentTarget.getBoundingClientRect(),_=z.top+z.height/2,$=C.clientY<_?"before":"after";d(E),h($)},[l]),A=a.useCallback(E=>C=>{C.preventDefault();const z=C.dataTransfer.getData("text/plain");if(!z||z===E){S();return}const _=e.findIndex(T=>T.id===z),$=e.findIndex(T=>T.id===E);if(_===-1||$===-1){S();return}const F=[...e],[V]=F.splice(_,1);let D=$;m==="after"&&_<$&&D--,m==="after"&&D++,F.splice(D,0,V),i(F),S()},[e,m,i,S]),w=a.useCallback(E=>{const C=E.currentTarget.getBoundingClientRect(),z=E.clientX,_=E.clientY;(z<C.left||z>C.right||_<C.top||_>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(Do,{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((E,C)=>{const z=l===E.id,_=u===E.id,$=["task-detail-section","subtask-item",z?"subtask-item-dragging":"",_?"subtask-item-drop-target":"",_&&m==="before"?"subtask-item-drop-before":"",_&&m==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:$,"data-testid":`subtask-item-${C}`,draggable:!s,onDragStart:y(E.id),onDragEnd:S,onDragOver:k(E.id),onDrop:A(E.id),onDragLeave:w,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(td,{size:16}),t.jsx("strong",{children:E.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(zi,{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(wr,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>v(E.id),disabled:s,children:[t.jsx(nn,{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:E.title,onChange:F=>f(E.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:E.description,onChange:F=>f(E.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:E.suggestedSize,onChange:F=>f(E.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!==E.id).map(F=>{const V=E.dependsOn.includes(F.id);return t.jsxs("label",{className:`planning-dep-chip ${V?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:V,onChange:()=>{const D=V?E.dependsOn.filter(T=>T!==F.id):[...E.dependsOn,F.id];f(E.id,{dependsOn:D})},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!==E.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},E.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:x,disabled:s,children:[t.jsx(sn,{size:16,className:"icon-mr-6"})," Add subtask"]}),sh(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(_a,{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(rt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]})}function kA({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(pb,{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(wA,{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(NA,{status:d.status}),t.jsx("span",{"aria-hidden":!0,children:" · "}),t.jsx("span",{children:SA(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(nn,{size:14})})]},d.id)})]})]})}function wA({status:e}){switch(e){case"generating":return t.jsx(rt,{size:14,className:"spin planning-sidebar-status-icon planning-sidebar-status-generating"});case"awaiting_input":return t.jsx(bc,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-awaiting"});case"complete":return t.jsx(vn,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-complete"});case"error":return t.jsx(ss,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-error"});default:return t.jsx(wi,{size:14,className:"planning-sidebar-status-icon"})}}function NA({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 SA(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 CA(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function ih(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 EA({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),[A,w]=a.useState(s),[E,C]=a.useState(null),[z,_]=a.useState(!1),[$,F]=a.useState(null),[V,D]=a.useState(null),[T,I]=a.useState(null),U=a.useRef(null),Y=a.useRef([]),ne=a.useRef(!1),N=a.useRef(null),P=c.type==="generating"||c.type==="editing"||c.type==="creating"||c.type==="error"?c.sessionId:null,R=a.useMemo(()=>Gi(),[]),{isLockedByOther:j,takeControl:W,isLoading:K}=Ko(e?P:null),{activeTabMap:ke,broadcastUpdate:be,broadcastCompleted:ce,broadcastLock:ve,broadcastUnlock:O,broadcastHeartbeat:oe}=Ra(),te=a.useMemo(()=>d.length===0||d.some(le=>!le.title.trim())?!0:ih(d),[d]),pe=c.type==="generating"||c.type==="editing"||c.type==="error",de=P?ke.get(P):null,{confirm:ge}=Bs(),ie=de&&de.tabId!==R,Ee=!!(ie&&!de.stale),Le=j&&(!ie||de.stale),qe=a.useCallback(()=>{A&&c1(A,o),U.current?.close(),U.current=null,u({type:"initial"}),m([]),g([]),f(""),v(!0),y(!1),k(!1),C(null),_(!1),ne.current=!1},[A,o]),et=a.useCallback(()=>{U.current?.close(),U.current=null,n()},[n]),Xe=a.useCallback(async()=>{if(!((z||c.type==="editing"||c.type==="creating")&&!await ge({title:"Discard Changes",message:"Close subtask breakdown? Unsaved changes will be lost.",danger:!0}))){if(P)try{await mp(P,o,R)}catch{}qe(),n()}},[z,n,qe,P,R,c.type,o,ge]),Ze=a.useCallback(le=>{U.current?.close(),U.current=_j(le,o,{onThinking:Te=>{f(he=>he+Te),be({sessionId:le,status:"generating",needsInput:!1,owningTabId:R,type:"subtask",title:A.trim()||"Subtask breakdown",projectId:o??null})},onSubtasks:Te=>{y(!1),k(!1),kl(o),m(Te),u({type:"editing",sessionId:le}),_(!1),be({sessionId:le,status:"awaiting_input",needsInput:!0,owningTabId:R,type:"subtask",title:A.trim()||"Subtask breakdown",projectId:o??null})},onError:Te=>{const he=Te||"Session failed while contacting the AI.";y(!1),k(!1),C(null),u({type:"error",sessionId:le,errorMessage:he}),be({sessionId:le,status:"error",needsInput:!1,owningTabId:R,type:"subtask",title:A.trim()||"Subtask breakdown",projectId:o??null}),ce({sessionId:le,status:"error"})},onComplete:()=>{ce({sessionId:le,status:"complete"})},onConnectionStateChange:Te=>{y(Te==="reconnecting")}})},[ce,be,A,o,R]),it=a.useCallback(async()=>{if(A.trim()){C(null),g([]),f(""),y(!1);try{const{sessionId:le}=await Sj(A.trim(),o);u({type:"generating",sessionId:le}),Ze(le)}catch(le){C(Se(le)||"Failed to start subtask breakdown"),u({type:"initial"})}}},[Ze,A,o]);a.useEffect(()=>{if(!e){qe();return}if(e&&s&&!ne.current)w(s),ne.current=!0,it();else if(e&&!s&&!ne.current){const le=d1(o);le&&w(le)}},[e,s,it,qe]),a.useEffect(()=>{!e||!l||c.type!=="initial"||(async()=>{try{const le=await di(l);if(!le)return;const Te=ya(le.conversationHistory);if(g(Te),le.status==="generating"||le.status==="awaiting_input")f(le.thinkingOutput??""),u({type:"generating",sessionId:l}),Ze(l);else if(le.status==="complete"&&le.result){kl(o);const he=JSON.parse(le.result);m(he),u({type:"editing",sessionId:l})}else le.status==="error"&&(C(null),u({type:"error",sessionId:l,errorMessage:le.error??"Session encountered an error"}))}catch(le){C(Se(le)||"Failed to resume session")}})()},[Ze,e,l,c.type,o]),a.useEffect(()=>{if(!e){N.current&&(O(N.current,R),N.current=null);return}if(P&&N.current!==P){N.current&&O(N.current,R),ve(P,R),N.current=P;return}!P&&N.current&&(O(N.current,R),N.current=null)},[ve,O,e,P,R]),a.useEffect(()=>{if(!e||!P||N.current!==P)return;oe(R);const le=setInterval(()=>{oe(R)},3e4);return()=>{clearInterval(le)}},[oe,e,P,R]),a.useEffect(()=>()=>{U.current?.close(),N.current&&(O(N.current,R),N.current=null)},[O,R]),a.useEffect(()=>{if(!e)return;const le=Te=>{Te.key==="Escape"&&(Te.preventDefault(),Xe())};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[e,Xe]);const Ie=a.useCallback((le,Te)=>{m(he=>he.map(Me=>Me.id===le?{...Me,...Te}:Me)),_(!0)},[]),Ke=a.useCallback(()=>{m(le=>[...le,CA(le.length+1)]),_(!0)},[]),re=a.useCallback(le=>{m(Te=>Te.filter(he=>he.id!==le).map(he=>({...he,dependsOn:he.dependsOn.filter(Me=>Me!==le)}))),_(!0)},[]),xe=a.useCallback(le=>Te=>{F(le),Te.dataTransfer.setData("text/plain",le),Te.dataTransfer.effectAllowed="move"},[]),se=a.useCallback(()=>{F(null),D(null),I(null)},[]),Ae=a.useCallback(le=>Te=>{if(Te.preventDefault(),le===$)return;const he=Te.currentTarget.getBoundingClientRect(),Me=he.top+he.height/2,We=Te.clientY<Me?"before":"after";D(le),I(We)},[$]),ze=a.useCallback(le=>Te=>{Te.preventDefault();const he=Te.dataTransfer.getData("text/plain");if(!he||he===le){F(null),D(null),I(null);return}m(Me=>{const We=Me.findIndex(ye=>ye.id===he),Re=Me.findIndex(ye=>ye.id===le);if(We===-1||Re===-1)return Me;const ut=[...Me],[Q]=ut.splice(We,1);let ue=Re;return T==="after"&&We<Re&&ue--,T==="after"&&ue++,ut.splice(ue,0,Q),ut}),_(!0),F(null),D(null),I(null)},[T]),me=a.useCallback(le=>{const Te=le.currentTarget.getBoundingClientRect(),he=le.clientX,Me=le.clientY;(he<Te.left||he>Te.right||Me<Te.top||Me>Te.bottom)&&(D(null),I(null))},[]),_e=a.useCallback((le,Te)=>{Te<0||Te>=d.length||(m(he=>{const Me=[...he],[We]=Me.splice(le,1);return Me.splice(Te,0,We),Me}),_(!0))},[d.length]),Fe=a.useCallback(le=>{Y.current[le+1]?.focus()},[]),nt=a.useCallback(async()=>{if(!(!P||te)){C(null),u({type:"creating",sessionId:P});try{const le=await Mj(P,d,r,o);i(le.tasks),qe(),n()}catch(le){C(Se(le)||"Failed to create tasks"),u({type:"editing",sessionId:P})}}},[te,n,i,r,o,qe,P,d]),we=a.useCallback(async()=>{if(c.type!=="error")return;const le=c.sessionId;C(null),k(!0),f(""),u({type:"generating",sessionId:le}),Ze(le);try{await Cj(le,o,R)}catch(Te){let he=Te;if((Se(Te)||"").includes("not in an error state"))try{const We=await di(le);if(!We)throw new Error("Failed to refresh subtask session.");if(g(ya(We.conversationHistory)),We.status==="generating"||We.status==="awaiting_input")f(We.thinkingOutput??""),u({type:"generating",sessionId:We.id}),U.current?.isConnected()||Ze(We.id);else if(We.status==="complete"){if(!We.result)throw new Error("Subtask session is complete but has no result.");kl(o);const Re=JSON.parse(We.result);m(Re),u({type:"editing",sessionId:We.id}),_(!1)}else We.status==="error"&&u({type:"error",sessionId:We.id,errorMessage:We.error??"Retry failed. Please try again."});y(!1);return}catch(We){he=We}U.current?.close(),U.current=null,u({type:"error",sessionId:le,errorMessage:Se(he)||"Retry failed. Please try again."}),y(!1)}finally{k(!1)}},[Ze,o,R,c]);return e?t.jsx("div",{className:"modal-overlay open",onClick:le=>le.target===le.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(Do,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Subtask Breakdown"})]}),t.jsxs("div",{className:"modal-header-actions",children:[pe&&t.jsx("button",{className:"modal-send-to-background",onClick:et,title:"Send to background","aria-label":"Send to background",children:t.jsx(Er,{size:16})}),t.jsx("button",{className:"modal-close",onClick:()=>void Xe(),"aria-label":"Close",children:t.jsx(Kt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[E&&t.jsx("div",{className:"form-error planning-error",children:E}),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:A})]})}),c.type==="generating"&&t.jsxs("div",{className:"planning-loading",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ts,{entries:h,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsx(rt,{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(Ts,{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 we(),disabled:S,children:[S?t.jsx(rt,{size:14,className:"spin"}):t.jsx(Mn,{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(Ts,{entries:h}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(vn,{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((le,Te)=>{const he=$===le.id,Me=V===le.id,We=["task-detail-section","subtask-item",he?"subtask-item-dragging":"",Me?"subtask-item-drop-target":"",Me&&T==="before"?"subtask-item-drop-before":"",Me&&T==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:We,"data-testid":`subtask-item-${Te}`,draggable:c.type!=="creating",onDragStart:xe(le.id),onDragEnd:se,onDragOver:Ae(le.id),onDrop:ze(le.id),onDragLeave:me,children:[t.jsxs("div",{className:"detail-title-row subtask-item-header subtask-item-header--between",children:[t.jsxs("div",{className:"subtask-drag-handle",title:"Drag to reorder",children:[t.jsx(td,{size:16}),t.jsx("strong",{children:le.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>_e(Te,Te-1),disabled:c.type==="creating"||Te===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(zi,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>_e(Te,Te+1),disabled:c.type==="creating"||Te===d.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(wr,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>re(le.id),disabled:c.type==="creating",children:[t.jsx(nn,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:Re=>{Y.current[Te]=Re},value:le.title,onChange:Re=>Ie(le.id,{title:Re.target.value}),onKeyDown:Re=>{Re.key==="Enter"&&(Re.preventDefault(),Fe(Te))},disabled:c.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:8,value:le.description,onChange:Re=>Ie(le.id,{description:Re.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:le.suggestedSize,onChange:Re=>Ie(le.id,{suggestedSize:Re.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,Te).filter(Re=>Re.id!==le.id).map(Re=>{const ut=le.dependsOn.includes(Re.id);return t.jsxs("label",{className:`planning-dep-chip ${ut?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:ut,onChange:()=>{const Q=ut?le.dependsOn.filter(ue=>ue!==Re.id):[...le.dependsOn,Re.id];Ie(le.id,{dependsOn:Q})},disabled:c.type==="creating"}),t.jsx("span",{className:"planning-dep-id",children:Re.id}),t.jsx("span",{className:"planning-dep-title",children:Re.title||"Untitled"})]},Re.id)}),Te===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),Te>0&&d.slice(0,Te).filter(Re=>Re.id!==le.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},le.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:Ke,disabled:c.type==="creating",children:[t.jsx(sn,{size:16,className:"icon-mr-6"})," Add subtask"]}),ih(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 nt(),disabled:c.type==="creating"||te,children:c.type==="creating"?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]}),j&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Lo,{size:16}),t.jsx("span",{children:Le?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Le&&t.jsx("button",{type:"button",onClick:()=>{W()},disabled:K,className:"btn btn-primary session-lock-take-control",children:K?"Taking control...":"Take Control"})]})})]})]})}):null}const _A=5,MA=1e3,AA=45e3;function oo(){return{scrollback:null,connected:null,data:[]}}function RA(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(oo()),S=a.useCallback(D=>{p.current.add(D);const T=y.current;return T.data.length>0&&(T.data.forEach(I=>D(I)),T.data=[]),()=>p.current.delete(D)},[]),k=a.useCallback(D=>(f.current.add(D),()=>f.current.delete(D)),[]),A=a.useCallback(D=>{x.current.add(D);const T=y.current;return T.connected&&(D(T.connected),T.connected=null),()=>x.current.delete(D)},[]),w=a.useCallback(D=>{v.current.add(D);const T=y.current;return T.scrollback&&(D(T.scrollback),T.scrollback=null),()=>v.current.delete(D)},[]),E=a.useCallback(D=>(b.current.add(D),()=>b.current.delete(D)),[]),C=a.useCallback(D=>{const T=u.current;T?.readyState===WebSocket.OPEN&&T.send(JSON.stringify({type:"input",data:D}))},[]),z=a.useCallback((D,T)=>{const I=u.current;I?.readyState===WebSocket.OPEN&&I.send(JSON.stringify({type:"resize",cols:D,rows:T}))},[]),_=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=oo()},[]),$=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=oo()},[]),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 D=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 U=new WebSocket(ei(I));u.current=U,U.onopen=()=>{if(r.current!==D){U.close();return}y.current=oo(),i("connected"),d.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===D&&U.readyState===WebSocket.OPEN&&U.send(JSON.stringify({type:"ping"}))},AA)},U.onmessage=Y=>{if(r.current===D)try{const ne=JSON.parse(Y.data),N=y.current;switch(ne.type){case"data":ne.data&&(p.current.size===0&&N.data.push(ne.data),p.current.forEach(P=>P(ne.data)));break;case"scrollback":ne.data&&(N.scrollback=ne.data,v.current.forEach(P=>P(ne.data)));break;case"connected":ne.shell&&ne.cwd&&(N.connected={shell:ne.shell,cwd:ne.cwd},x.current.forEach(P=>P({shell:ne.shell,cwd:ne.cwd})));break;case"exit":ne.exitCode!==void 0&&f.current.forEach(P=>P(ne.exitCode));break;case"ping":U.readyState===WebSocket.OPEN&&U.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},U.onclose=Y=>{if(r.current!==D)return;if(u.current=null,h.current&&(clearInterval(h.current),h.current=null),g.current){i("disconnected");return}if(Y.code===4e3||Y.code===4004){i("disconnected"),Y.code===4004&&b.current.forEach(P=>P());return}if(d.current++,d.current>_A){i("disconnected");return}const ne=MA*Math.pow(2,d.current-1);i("reconnecting");const N=r.current;m.current=setTimeout(()=>{r.current===N&&(g.current||F())},Math.min(ne,16e3))},U.onerror=()=>{}},[e,n]),V=a.useCallback(()=>{d.current=0,$(),F()},[$,F]);return a.useEffect(()=>(c&&(_(),d.current=0,i("disconnected")),e?F():i("disconnected"),$),[e,n,c,F,$,_]),{connectionStatus:s,sendInput:C,resize:z,onData:S,onExit:k,onConnect:A,onScrollback:w,reconnect:V,onSessionInvalid:E}}const eg="kb-terminal-tabs",TA=15e3,PA=15e3;function ah(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function rh(e){if(typeof window>"u")return[];try{const n=Hn(eg,e);if(n)return JSON.parse(n)}catch{}return[]}function tc(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function oh(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 IA(e){const[n,s]=a.useState(()=>rh(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(rh(e)),r(!1),l(!0),u(null)},[e]),a.useEffect(()=>{try{ls(eg,JSON.stringify(n),e)}catch{}},[e,n]),a.useEffect(()=>{let A=!1;const w=h.current;return(async()=>{if(!A)try{const C=await oh(ky(e),TA,"listTerminalSessions");if(A||w!==h.current)return;const z=new Set(C.map(_=>_.id));l(!0),s(_=>{if(A||w!==h.current)return _;const F=_.map(T=>({...T,_verified:z.has(T.sessionId)})).filter(T=>T._verified);if(F.length===0)return[];const V=F.map(({_verified:T,...I})=>I);return V.find(T=>T.isActive)?V:V.map((T,I)=>({...T,isActive:I===0}))}),r(!0)}catch(C){if(A||w!==h.current)return;const z=tc(C);z||console.warn("Failed to validate terminal sessions with server:",C),l(!z),r(!0)}})(),()=>{A=!0}},[e]),a.useEffect(()=>{if(n.length===0&&i&&o){const A=h.current,w=setTimeout(()=>{oh(Hr(void 0,void 0,void 0,e),PA,"createTerminalSession").then(E=>{if(A!==h.current)return;const C={id:ah(),sessionId:E.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(z=>z.length>0?z:[...z.map($=>({...$,isActive:!1})),C]),u(null)}).catch(E=>{if(A!==h.current)return;tc(E)||console.error(E);const C=E instanceof Error?E.message:typeof E=="string"?E:"Failed to create terminal session";u(C)})},0);return()=>clearTimeout(w)}},[i,o,n.length,d]);const g=a.useCallback(async()=>{const A=await Hr(void 0,void 0,void 0,e),w={id:ah(),sessionId:A.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(E=>[...E.map(z=>({...z,isActive:!1})),w]),w},[n.length]),p=a.useCallback(async()=>g(),[g]),f=a.useCallback(A=>{s(w=>{const E=w.find($=>$.id===A);if(!E)return w;Kd(E.sessionId,e).catch($=>{console.warn(`Failed to kill terminal session ${E.sessionId}:`,$)});const C=w.findIndex($=>$.id===A),z=E.isActive,_=w.filter($=>$.id!==A);if(_.length===0)return[];if(z){const $=Math.min(C,_.length-1);return _.map((F,V)=>({...F,isActive:V===$}))}return _})},[]),x=a.useCallback(A=>{s(w=>{let E=!1;const C=w.map(z=>z.id===A?(E=!0,{...z,isActive:!0}):{...z,isActive:!1});return E?C:w})},[]),v=a.useCallback((A,w)=>{s(E=>E.map(C=>C.id===A?{...C,title:w}:C))},[]),b=a.useCallback(async()=>{s(E=>{const C=E.find(z=>z.isActive);return C&&Kd(C.sessionId,e).catch(z=>{console.warn(`Failed to kill old session ${C.sessionId}:`,z)}),E});const A=n.find(E=>E.isActive);if(!A)return;const w=await Hr(void 0,void 0,void 0,e);s(E=>E.map(C=>C.id===A.id?{...C,sessionId:w.sessionId}:C))},[n]),y=a.useCallback(async()=>{const A=n.find(w=>w.isActive);if(A)try{const w=await Hr(void 0,void 0,void 0,e);s(E=>E.map(C=>C.id===A.id?{...C,sessionId:w.sessionId}:C)),u(null)}catch(w){tc(w)||console.error(w);const E=w instanceof Error?w.message:typeof w=="string"?w:"Failed to create terminal session";u(E)}},[n]),S=n.find(A=>A.isActive)??null,k=a.useCallback(()=>{u(null),h.current+=1,m(A=>A+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 $A=1e4,DA=[500,1500,3e3],tg="kb-terminal-font-size",ar=14,LA=8,zA=32;function OA(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 FA(e){return`\x1B${e}`}const UA=[{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 rr(e){return Math.min(zA,Math.max(LA,e))}function BA(){if(typeof window>"u")return ar;try{const e=window.localStorage.getItem(tg);if(!e)return ar;const n=Number.parseInt(e,10);return Number.isFinite(n)?rr(n):ar}catch{return ar}}function HA(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 qA(e){return new Promise(n=>setTimeout(n,e))}async function VA(e,n=DA){let s;for(let i=0;i<=n.length;i+=1)try{return await e()}catch(r){if(!HA(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 qA(o)}throw s??new Error("Dynamic import failed")}function lh(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}function WA(){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=KA()-e.offsetTop-e.height;return i>=30&&i>80?i:0}let nc=null;function KA(){return nc===null&&(nc=window.innerHeight),nc}function GA({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(()=>BA()),[k,A]=a.useState(!1),[w,E]=a.useState(null),C=a.useRef(null),z=a.useRef(null),_=a.useRef(!1);ti(z,e,"fusion:terminal-modal-size");const $=a.useRef(null),F=a.useRef(null),V=a.useRef(!1),D=a.useRef(!1),T=a.useRef(null),I=a.useRef(()=>{}),U=a.useRef(null),Y=a.useRef(0),ne=a.useRef(y),N=a.useRef(null),P=a.useRef(i);Y.current=f,ne.current=y;const R=a.useCallback(he=>{if(he&&D.current!==he)return;const Me=F.current,We=$.current,Re=T.current;if(!(!Me||!We)&&!(he&&D.current!==he))try{Me.fit(),Re&&Re(We.cols,We.rows)}catch{}},[]);a.useEffect(()=>{e&&p(he=>he+1)},[e]),a.useEffect(()=>{if(!e||!lh())return;const he=window.visualViewport;if(!he)return;const Me=()=>{const We=WA();x(We),b(he.height),We>0&&z.current?.scrollIntoView&&z.current.scrollIntoView({block:"end",behavior:"smooth"}),N.current!==null&&(cancelAnimationFrame(N.current),N.current=null);const Re=typeof D.current=="string"?D.current:void 0;N.current=requestAnimationFrame(()=>{N.current=null,R(Re)})};return Me(),he.addEventListener("resize",Me),he.addEventListener("scroll",Me),()=>{he.removeEventListener("resize",Me),he.removeEventListener("scroll",Me),N.current!==null&&(cancelAnimationFrame(N.current),N.current=null),x(0),b(null)}},[R,e]),a.useEffect(()=>{if(!e)return;const he=z.current;if(!he||typeof ResizeObserver>"u")return;let Me=null;const We=new ResizeObserver(()=>{Me!==null&&cancelAnimationFrame(Me),Me=requestAnimationFrame(()=>{Me=null;const Re=typeof D.current=="string"?D.current:void 0;R(Re)})});return We.observe(he),()=>{We.disconnect(),Me!==null&&cancelAnimationFrame(Me)}},[R,e]);const{tabs:j,activeTab:W,isReady:K,bootstrapError:ke,createTab:be,closeTab:ce,setActiveTab:ve,updateTabTitle:O,restartActiveTab:oe,retryBootstrap:te,replaceActiveTabSession:pe}=IA(i),{connectionStatus:de,sendInput:ge,resize:ie,onData:Ee,onConnect:Le,onExit:qe,onScrollback:et,reconnect:Xe,onSessionInvalid:Ze}=RA(W?.sessionId??null,i);T.current=ie,I.current=ge,a.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(tg,String(y))}catch{}},[y]);const it=a.useCallback(()=>{const he=$.current;if(he)try{F.current?.fit(),ie(he.cols,he.rows)}catch{}},[ie]);a.useEffect(()=>{if(!e||!K)return;const he=W?.sessionId;if(!he)return;const Me=P.current!==i;if(Me&&(P.current=i),D.current===he&&$.current&&!Me)return;$.current&&(D.current!==he||Me)&&($.current.dispose(),$.current=null,F.current=null,D.current=!1,U.current&&(window.removeEventListener("resize",U.current),U.current=null),d(!1),h(null));let We=!0,Re;return(async()=>{const Q=VA(()=>Promise.all([ln(()=>import("./vendor-xterm-DzcZoU0P.js").then(X=>X.x),__vite__mapDeps([0,1,2])),ln(()=>import("./addon-fit-C7jRorKK.js").then(X=>X.a),__vite__mapDeps([3,1])),ln(()=>import("./addon-web-links-CkJwd4cQ.js").then(X=>X.a),__vite__mapDeps([4,1]))])),ue=new Promise((X,Ye)=>{Re=setTimeout(()=>{Ye(new Error("xterm initialization timed out"))},$A)});let ye,at;try{const[{Terminal:X},{FitAddon:Ye},{WebLinksAddon:ot}]=await Promise.race([Q,ue]);if(!We||!C.current||$.current)return;ye=new X({cursorBlink:!0,cursorStyle:"block",fontSize:ne.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}),at=new Ye,ye.loadAddon(at);const ht=new ot;if(ye.loadAddon(ht),!lh())try{const{WebglAddon:pt}=await ln(async()=>{const{WebglAddon:It}=await import("./addon-webgl-BjvOw43o.js").then(Bt=>Bt.a);return{WebglAddon:It}},__vite__mapDeps([5,1])),Et=new pt;Et.onContextLoss(()=>{Et.dispose()}),ye.loadAddon(Et)}catch{}ye.open(C.current),Re&&clearTimeout(Re);const yt=C.current?.querySelector(".xterm-helper-textarea");if(yt&&yt.focus(),C.current)try{C.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{at.fit();const pt=C.current?.querySelector(".xterm-helper-textarea");pt&&pt.focus()},50),$.current=ye,F.current=at,D.current=he,Y.current>0&&(N.current!==null&&(cancelAnimationFrame(N.current),N.current=null),N.current=requestAnimationFrame(()=>{N.current=null,R(he)})),ye.onData(pt=>{D.current===he&&I.current(pt)});const vt=()=>{if(D.current===he&&F.current&&$.current)try{F.current.fit();const{cols:pt,rows:Et}=$.current;T.current?.(pt,Et)}catch{}};window.addEventListener("resize",vt),U.current&&window.removeEventListener("resize",U.current),U.current=vt,d(!0),h(null)}catch(X){if(Re&&clearTimeout(Re),!We)return;const Ye=X instanceof Error?X.message:"xterm initialization failed";h(Ye)}})(),()=>{We=!1,Re&&clearTimeout(Re)}},[R,e,K,W?.sessionId,i]),a.useEffect(()=>{e||($.current&&($.current.dispose(),$.current=null),F.current=null,D.current=!1,U.current&&(window.removeEventListener("resize",U.current),U.current=null),d(!1),h(null),V.current=!1,o(null),c(null),A(!1),E(null))},[e]),a.useEffect(()=>{if(!u||!$.current||!W)return;const he=W.sessionId,Me=ue=>{D.current===he&&$.current?.write(ue)},We=Ee(ue=>{Me(ue)}),Re=et(ue=>{Me(ue)}),ut=Le(ue=>{O(W.id,ld(ue.shell)||ue.shell)}),Q=qe(ue=>{D.current===he&&(c(ue),$.current?.write(`\r
|
|
653
|
-
\x1B[33m[Process exited with code ${ue}]\x1B[0m\r
|
|
654
|
-
`))});return()=>{We(),Re(),ut(),Q()}},[u,W?.sessionId,W?.id,W,de,Ee,et,Le,qe,O]),a.useEffect(()=>{de==="connected"&&s&&V.current!==s&&W&&(V.current=s,setTimeout(()=>{ge(s+`
|
|
655
|
-
`)},500))},[de,s,ge,W,g]),a.useEffect(()=>{if(!u||!$.current)return;$.current.options.fontSize=y,N.current!==null&&(cancelAnimationFrame(N.current),N.current=null);const he=requestAnimationFrame(()=>{N.current=null,it()});return N.current=he,()=>{N.current===he&&(cancelAnimationFrame(he),N.current=null)}},[y,u,it]),a.useEffect(()=>{if(!e)return;const he=Me=>{if(!(!Me.ctrlKey&&!Me.metaKey)){if(Me.code==="Equal"||Me.code==="NumpadAdd"){Me.preventDefault(),S(We=>rr(We+1));return}if(Me.code==="Minus"||Me.code==="NumpadSubtract"){Me.preventDefault(),S(We=>rr(We-1));return}if(Me.code==="Digit0"||Me.code==="Numpad0"){Me.preventDefault(),S(ar);return}}};return window.addEventListener("keydown",he),()=>window.removeEventListener("keydown",he)},[e,it]),a.useEffect(()=>{if(!e)return;const he=Me=>{Me.key==="Escape"&&n()};return document.addEventListener("keydown",he),()=>document.removeEventListener("keydown",he)},[e,n]),a.useEffect(()=>{de==="connected"&&$.current&&setTimeout(()=>{if(!$.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)},[de]);const Ie=a.useCallback(()=>{if(!C.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;$.current?.focus();const Me=C.current.querySelector(".xterm-helper-textarea");if(!Me)return;Me.autocapitalize="off",Me.autocomplete="off",Me.autocorrect="off",Me.spellcheck=!1,Me.setAttribute("inputmode","text");try{Me.focus({preventScroll:!0})}catch{Me.focus()}const We=Me.value.length;Me.setSelectionRange(We,We)},[]);a.useEffect(()=>Ze(()=>{$.current?.clear(),c(null),V.current=!1,$.current&&($.current.dispose(),$.current=null),F.current=null,D.current=!1,U.current&&(window.removeEventListener("resize",U.current),U.current=null),d(!1),h(null),pe().catch(Me=>{console.error("Failed to replace invalid terminal session:",Me)})}),[Ze,pe]);const Ke=a.useCallback(he=>{he.target===he.currentTarget&&(_.current=!0)},[]),re=a.useCallback(he=>{_.current&&he.target===he.currentTarget&&n(),_.current=!1},[n]),xe=a.useCallback(()=>{$.current?.clear()},[]),se=a.useCallback(async()=>{$.current?.clear(),c(null),V.current=!1;try{await oe()}catch(he){o(Se(he)||"Failed to restart terminal session")}},[oe]),Ae=a.useCallback(()=>{$.current&&($.current.dispose(),$.current=null),F.current=null,D.current=!1,U.current&&(window.removeEventListener("resize",U.current),U.current=null),h(null),d(!1)},[]),ze=a.useCallback(()=>{window.location.reload()},[]),me=a.useCallback(()=>{S(he=>rr(he+1))},[]),_e=a.useCallback(()=>{S(he=>rr(he-1))},[]),Fe=a.useCallback(he=>{E(Me=>Me===he?null:he)},[]),nt=a.useCallback(he=>{if(w==="ctrl"){ge(OA(he)),E(null);return}if(w==="alt"){ge(FA(he)),E(null);return}ge(he)},[ge,w]),we=a.useCallback(he=>{ge(he),E(null)},[ge]);if(!e)return null;const le=()=>{switch(de){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}},Te=!K||!W&&!ke;return t.jsx("div",{className:"modal-overlay open",onMouseDown:Ke,onMouseUp:re,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:[j.map(he=>t.jsxs("div",{className:`terminal-tab ${he.isActive?"terminal-tab--active":""}`,onClick:()=>ve(he.id),title:he.title,role:"tab","aria-selected":he.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:he.title}),j.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:Me=>{Me.stopPropagation(),ce(he.id)},title:"Close tab",children:"×"})]},he.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:be,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(ci,{size:16}),le()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[de==="disconnected"&&W&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:Xe,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(Mn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:se,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(Mn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:xe,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[t.jsx(nn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:()=>A(he=>!he),"data-testid":"terminal-shortcut-toggle",title:"Shortcuts","aria-pressed":k,children:[t.jsx(Zx,{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(Kt,{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:[Te&&!ke&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),ke&&!W&&t.jsx("div",{className:"terminal-loading","data-testid":"terminal-bootstrap-error",children:t.jsxs("div",{className:"terminal-error-content",children:[t.jsxs("span",{children:["Failed to start terminal: ",ke]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:te,"data-testid":"terminal-retry-btn",children:[t.jsx(Mn,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:ze,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(Mn,{size:14}),"Refresh page"]})]})]})}),m&&W&&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:Ae,"data-testid":"terminal-reinit-btn",children:[t.jsx(Mn,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:ze,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(Mn,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:C,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:Ie,onTouchStart:Ie},W?.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 ${w==="ctrl"?"is-active":""}`,"data-testid":"terminal-modifier-ctrl",onClick:()=>Fe("ctrl"),"aria-pressed":w==="ctrl",children:"Ctrl"}),t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${w==="alt"?"is-active":""}`,"data-testid":"terminal-modifier-alt",onClick:()=>Fe("alt"),"aria-pressed":w==="alt",children:"Alt"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>we("\x1B"),children:"ESC"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>we(" "),children:"Tab"})]}),UA.map(he=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>nt(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 ${de}`,children:[de==="connected"&&"Connected",de==="connecting"&&"Connecting...",de==="reconnecting"&&"Reconnecting...",de==="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:_e,"data-testid":"terminal-font-size-decrease","aria-label":"Decrease terminal font size",children:t.jsx(bb,{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:me,"data-testid":"terminal-font-size-increase","aria-label":"Increase terminal font size",children:t.jsx(sn,{size:14})})]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • ⌨ Shortcuts panel • Esc close"})]})]})})}const Ya={name:"",command:""};function ch(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function JA(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function YA({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(Ya),[x,v]=a.useState(!1),[b,y]=a.useState(null),[S,k]=a.useState(null),A=Si(n),w=a.useCallback(async()=>{try{u(!0);const I=await br(i);l(I)}catch(I){s(Se(I)||"Failed to load scripts","error")}finally{u(!1)}},[s,i]);a.useEffect(()=>{e&&w()},[e,w]);const E=a.useCallback(()=>{m(!0),g(null),f(Ya),k(null)},[]),C=a.useCallback((I,U)=>{g(I),m(!1),f({name:I,command:U}),k(null)},[]),z=a.useCallback(()=>{g(null),m(!1),f(Ya),k(null)},[]),_=a.useCallback(I=>{f(U=>({...U,name:I})),I&&!ch(I)?k("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):k(null)},[]),$=a.useCallback(async()=>{const I=p.name.trim(),U=p.command.trim();if(!I){s("Script name is required","error");return}if(!ch(I)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!U){s("Script command is required","error");return}v(!0);try{await wj(I,U,i),s(h?"Script updated":"Script created","success"),g(null),m(!1),f(Ya),k(null),await w()}catch(Y){const ne=Se(Y);ne?.includes("already exists")?s("A script with this name already exists","error"):s(ne||"Failed to save script","error")}finally{v(!1)}},[p,h,s,w,i]),F=a.useCallback(async I=>{try{await Nj(I,i),s("Script deleted","success"),y(null),h===I&&(g(null),f(Ya)),await w()}catch(U){s(Se(U)||"Failed to delete script","error")}},[h,s,w,i]),V=a.useCallback((I,U)=>{r&&r(I,U)},[r]);if(!e)return null;const D=d||h!==null,T=Object.entries(o).map(([I,U])=>({name:I,command:U}));return t.jsx("div",{className:"modal-overlay open",...A,"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(ci,{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(rt,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),"Loading scripts..."]}):D?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=>_(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(U=>({...U,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:$,disabled:x||!!S,"data-testid":"script-save-btn",children:x?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:14,className:"spin",style:{marginRight:"6px"}}),"Saving..."]}):h?"Update":"Create"})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"scripts-modal-list-header",style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[t.jsx("div",{style:{fontSize:"13px",color:"var(--text-muted)"},children:T.length===0?"No scripts defined":`${T.length} script${T.length===1?"":"s"}`}),t.jsxs("button",{className:"btn btn-primary",onClick:E,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx(sn,{size:14}),"Add Script"]})]}),T.length===0?t.jsxs("div",{style:{textAlign:"center",padding:"32px",color:"var(--text-muted)",fontSize:"14px",border:"1px dashed var(--border)",borderRadius:"8px"},"data-testid":"empty-state",children:[t.jsx(ci,{size:32,style:{margin:"0 auto 12px",opacity:.5}}),t.jsx("div",{children:"No scripts defined yet."}),t.jsx("div",{style:{marginTop:"4px",fontSize:"12px"},children:"Add scripts to quickly run common commands from the dashboard."})]}):t.jsx("div",{className:"scripts-modal-list",style:{display:"flex",flexDirection:"column",gap:"8px"},children:T.map(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:JA(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:()=>V(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(wn,{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(sn,{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(nn,{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(Kt,{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(nn,{size:14})})]})]})},I.name))})]})})]})})}function QA(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 Fy(e,o==="."?void 0:o,s);x||r(b.entries)}catch(b){x||(m(Se(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 XA(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 A=await Uy(e,n,i);S||(o(A.content),c(A.content),d(A.mtime))}catch(A){S||(x(Se(A)||"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 By(e,n,r,i);c(r),d(S.mtime)}catch(S){throw x(Se(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 ZA=1e4;function eR(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function tR(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function nR(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 Oy(e);if(d)return;s(eR(g.project)),r(g.tasks.map(tR)),u(null)}catch(g){d||u(Se(g)||"Failed to load workspaces")}finally{d||l(!1)}}m();const h=window.setInterval(()=>{m()},ZA);return()=>{d=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:i,loading:o,error:c}}function sR(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function iR(e){return e?new Date(e).toLocaleDateString():""}function dh(e,n){return dw(e,n)}const Qa={visible:!1,x:0,y:0,entry:null,entryFullPath:""},sc={type:null,entry:null,entryFullPath:""},aR=200,rR=500,uh=10;function oR({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:jb,disabled:!1},{id:"rename",label:"Rename",icon:ts,disabled:!1},...u?[{id:"download-zip",label:"Download as ZIP",icon:To,disabled:!1}]:[{id:"download",label:"Download",icon:hx,disabled:!1}],{id:"divider",label:"",icon:Fi,disabled:!0},{id:"delete",label:"Delete",icon:nn,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 lR({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 cR({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(Qa),[g,p]=a.useState(sc),[f,x]=a.useState(!1),[v,b]=a.useState(null),[y,S]=a.useState(!1),[k,A]=a.useState(null),w=a.useRef(null),E=a.useRef(null),C=a.useRef(null),z=a.useRef(!1),_=a.useCallback(()=>{w.current!==null&&(window.clearTimeout(w.current),w.current=null),E.current!==null&&(window.clearTimeout(E.current),E.current=null)},[]),$=a.useCallback(()=>{_(),C.current=null,S(!1),A(null)},[_]);a.useEffect(()=>()=>{_()},[_]);const F=a.useCallback((P,R,j,W)=>{h({visible:!0,x:P,y:R,entry:j,entryFullPath:W})},[]),V=a.useCallback((P,R,j)=>{if(P.touches.length!==1)return;const W=P.touches[0];W&&($(),C.current={x:W.clientX,y:W.clientY},E.current=window.setTimeout(()=>{S(!0),A(j)},aR),w.current=window.setTimeout(()=>{const K=C.current;K&&(z.current=!0,S(!1),A(null),_(),F(K.x,K.y,R,j))},rR))},[$,_,F]),D=a.useCallback(P=>{const R=C.current,j=P.touches[0];!R||!j||(Math.abs(j.clientX-R.x)>uh||Math.abs(j.clientY-R.y)>uh)&&$()},[$]),T=a.useCallback(()=>{$()},[$]);a.useEffect(()=>{if(!m.visible)return;const P=document.querySelector(".file-browser-list"),R=()=>{z.current=!1,$(),h(Qa)};return P?.addEventListener("scroll",R),()=>P?.removeEventListener("scroll",R)},[$,m.visible]),a.useEffect(()=>{if(!m.visible)return;const P=R=>{R.key==="Escape"&&(z.current=!1,h(Qa))};return document.addEventListener("keydown",P),()=>document.removeEventListener("keydown",P)},[m.visible]);const I=a.useCallback((P,R)=>{P.preventDefault(),P.stopPropagation(),$(),z.current=!1,F(P.clientX,P.clientY,R,dh(n,R.name))},[$,n,F]),U=a.useCallback(P=>{if(!m.entry)return;z.current=!1;const R=m.entry,j=m.entryFullPath;if(h(Qa),P==="download"){if(!c)return;const W=lp(c,j,d);window.open(ei(W),"_blank");return}if(P==="download-zip"){if(!c)return;const W=Gy(c,j,d);window.open(ei(W),"_blank");return}p({type:P,entry:R,entryFullPath:j}),b(null)},[m,c,d]),Y=a.useCallback(async P=>{if(!(!g.type||!g.entry||!c)){x(!0),b(null);try{switch(g.type){case"copy":await qy(c,g.entryFullPath,P,d);break;case"move":await Vy(c,g.entryFullPath,P,d);break;case"rename":await Ky(c,g.entryFullPath,P,d);break;case"delete":await Wy(c,g.entryFullPath,d);break}p(sc),u?.()}catch(R){b(Se(R)||"Operation failed")}finally{x(!1)}}},[g,c,u,d]),ne=a.useCallback(()=>{p(sc),b(null)},[]),N=a.useCallback((P,R)=>{if(z.current){z.current=!1;return}m.visible||(P.type==="directory"?i(R):s(R))},[m.visible,i,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(rt,{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:()=>{i(uw(n))},children:[t.jsx(bn,{size:16,style:{transform:"rotate(-90deg)"}}),"Up one level"]}),t.jsx("span",{className:"file-browser-path",children:n==="."?"Root":Aa(n)})]}),t.jsx("div",{className:"file-browser-list",children:e.length===0?t.jsx("div",{className:"file-browser-empty",children:"(empty directory)"}):e.map(P=>{const R=dh(n,P.name),j=y&&k===R;return t.jsxs("div",{className:`file-node file-node--${P.type} ${j?"file-node--long-pressing":""}`,onClick:()=>N(P,R),onContextMenu:W=>I(W,P),onTouchStart:W=>V(W,P,R),onTouchMove:D,onTouchEnd:T,onTouchCancel:T,children:[t.jsx("div",{className:"file-node-icon",children:P.type==="directory"?t.jsx(Un,{size:16}):t.jsx(Gh,{size:16})}),t.jsx("div",{className:"file-node-name",children:P.name}),P.type==="file"&&P.size!==void 0&&t.jsx("div",{className:"file-node-size",children:sR(P.size)}),P.mtime&&t.jsx("div",{className:"file-node-time",children:iR(P.mtime)})]},P.name)})}),m.visible&&m.entry&&t.jsx(oR,{x:m.x,y:m.y,entry:m.entry,onAction:U,onClose:()=>{z.current=!1,h(Qa)}}),g.type&&g.entry&&t.jsx(lR,{type:g.type,entry:g.entry,entryFullPath:g.entryFullPath,onConfirm:Y,onCancel:ne,loading:f,error:v})]})}function dR(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function uR({content:e,onChange:n,readOnly:s,filePath:i}){const[r,o]=a.useState(!1),[l,c]=a.useState(!0),u=dR(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(Kh,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${d?"btn-primary":""}`,onClick:h,disabled:d,"aria-label":"Preview mode",children:[t.jsx(fa,{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(xo,{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(xo,{size:14})})]}),d?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(hi,{remarkPlugins:[pi],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 mR(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function hR({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(Ld,{size:14}):t.jsx(kc,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(Yt,{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(Ld,{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(kc,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:mR(c.title)})]},c.id))]})]})]})}const pR=768,ng=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),fR=new Set([...ng,".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 mh(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return fR.has(n)}function gR(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return ng.has(n)}function xR({initialWorkspace:e="project",onClose:n,onWorkspaceChange:s,projectId:i}){const{projectName:r,workspaces:o}=nR(i),l=a.useRef(null);ti(l,!0,"fusion:files-modal-size");const c=Si(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:A}=QA(u,!0,i),{content:w,setContent:E,originalContent:C,loading:z,saving:_,error:$,save:F,hasChanges:V,mtime:D}=XA(u,m,!0,i);a.useEffect(()=>{d(e)},[e]),a.useEffect(()=>{const j=()=>{p(window.innerWidth<=pR)};return j(),window.addEventListener("resize",j),()=>window.removeEventListener("resize",j)},[]),a.useEffect(()=>{m||x("list")},[m]),a.useEffect(()=>{const j=W=>{W.key==="Escape"&&n(),(W.metaKey||W.ctrlKey)&&W.key==="s"&&(W.preventDefault(),V&&!_&&F())};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[n,V,_,F]);const T=a.useCallback(j=>{h(j),g&&x("editor")},[g]),I=a.useCallback(()=>{x("list")},[]),U=a.useCallback(()=>{E(C)},[C,E]),Y=a.useCallback(j=>{d(j),h(null),x("list"),s?.(j)},[s]),N=`Files — ${a.useMemo(()=>u==="project"?"Project":o.find(j=>j.id===u)?.id??u,[u,o])}`,P=a.useMemo(()=>!m||!gR(m)?null:lp(u,m,i),[m,u,i]),R=j=>{const W=new Blob([j]).size;return W<1024?`${W} B`:`${(W/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(Un,{size:18}),t.jsx("span",{children:N}),m&&t.jsx("span",{className:"file-browser-header-path",children:m})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsx(hR,{currentWorkspace:u,projectName:r,workspaces:o,onSelect:Y}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Kt,{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(cR,{entries:v,currentPath:b,onSelectFile:T,onNavigate:y,loading:S,error:k,onRetry:A,workspace:u,onRefresh:A,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(_a,{size:16}),t.jsx("span",{children:"Back"})]}),m,mh(m)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(Tx,{size:12}),"Binary file — read only"]}),D&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(D).toLocaleString()]}),z&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!P&&V&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:U,disabled:_,children:[t.jsx(Tb,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void F(),disabled:_,children:[t.jsx(ep,{size:14}),_?"Saving...":"Save"]})]})})]}),$&&!P&&t.jsx("div",{className:"file-browser-error-banner",children:$}),P?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:P,alt:m??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(uR,{content:w,onChange:E,filePath:m,readOnly:mh(m)})}),!P&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:R(w)}),V&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(Un,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}function bR(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 ny();r({providers:m,loading:!1,error:null,lastUpdated:new Date})}catch(m){if(m instanceof Error&&m.name==="AbortError")return;r(h=>({...h,loading:!1,error:Se(m)||"Failed to fetch usage data"}))}},[]);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 vR(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 yR(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const sg="kb-usage-hidden-windows";function hh(e){const n=Hn(sg,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 jR(e,n){ls(sg,JSON.stringify(e),n)}function ig(e,n,s){return s[e]?.includes(n)??!1}function kR({window:e,viewMode:n,isHidden:s,onToggleHidden:i}){const r=yR(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(fa,{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:vR(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(nd,{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(ev,{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(vn,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:m.message})]})]})]})}function wR(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 NR({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(Dn,{provider:wR(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=ig(e.name,c.label,s);return t.jsx(kR,{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 SR(){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 CR({isOpen:e,onClose:n,projectId:s,anchorRect:i}){const{providers:r,loading:o,error:l,lastUpdated:c,refresh:u}=bR({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(()=>hh(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 T=()=>{g(window.innerWidth>=769)};return window.addEventListener("resize",T),()=>window.removeEventListener("resize",T)},[]),a.useEffect(()=>{!y.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&u(),y.current=e},[e,c,u]),a.useEffect(()=>{const T=Hn("kb-usage-view-mode",s);if(T==="used"||T==="remaining"){f(T);return}f("used")},[s]);const k=a.useCallback(T=>{f(T),ls("kb-usage-view-mode",T,s)},[s]);a.useEffect(()=>{v(hh(s))},[s]),a.useEffect(()=>{jR(x,s)},[x,s]);const A=a.useCallback((T,I)=>{v(U=>{if(ig(T,I,U)){const Y=(U[T]??[]).filter(ne=>ne!==I);if(Y.length===0){const{[T]:ne,...N}=U;return N}return{...U,[T]:Y}}return{...U,[T]:[...U[T]??[],I]}})},[]),w=a.useCallback(T=>{v(I=>{if(!I[T])return I;const{[T]:U,...Y}=I;return Y})},[]),E=a.useCallback(async()=>{m(!0),await u(),m(!1)},[u]);a.useEffect(()=>{if(!e)return;const T=I=>{I.key==="Escape"&&n()};return document.addEventListener("keydown",T),()=>document.removeEventListener("keydown",T)},[e,n]);const C=a.useCallback(T=>{T.target===T.currentTarget&&n()},[n]);if(!e)return null;const z=!!(i&&h),F=z?Math.min((i?.bottom??0)+8,window.innerHeight-12):void 0,V=z?Math.max(window.innerWidth-(i?.right??0),0):void 0,D=t.jsxs("div",{className:`usage-modal${z?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:z?{position:"fixed",top:F,right:V}:void 0,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Rs,{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(Kt,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:b,children:(o||!S.current&&!l)&&r.length===0?t.jsx(SR,{}):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:E,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=>t.jsx(NR,{provider:T,viewMode:p,hiddenWindows:x,onToggleWindow:A,onShowAllHidden:w},T.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:E,disabled:o||d,"data-testid":"usage-refresh-btn",children:[t.jsx(Mn,{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"}),D]}):t.jsx("div",{className:"modal-overlay open",onClick:C,"data-testid":"usage-modal-overlay",children:D})}function ag(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 Mo(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 ER={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},rg={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},_R={cron:Vh,webhook:np,api:Wh,manual:Fn},MR={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},AR={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function RR({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(vn,{size:12}):t.jsx(Sr,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:ag(n)})]})}function TR({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"} ${Mo(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(vn,{size:12}):t.jsx(Sr,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:Mo(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:rg[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:ag(r)}),s?t.jsx(ui,{size:12}):t.jsx(Yt,{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 PR({routine:e,onEdit:n,onDelete:s,onRun:i,onToggle:r,running:o,lastRunOutput:l}){const[c,u]=a.useState(!1),{confirm:d}=Bs(),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=ER[e.trigger.type],g=_R[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}),rg[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($o,{size:10}):t.jsx(Un,{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(rt,{size:14,className:"spinner"}):t.jsx(wn,{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(Fs,{size:14}):t.jsx(wn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(ts,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:m,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(nn,{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(Bi,{size:12}),t.jsxs("span",{className:"routine-policy-badge",children:[e.steps.length," step",e.steps.length===1?"":"s"]})]}):e.command?t.jsx("div",{className:"routine-meta-item routine-meta-command-preview",title:e.command,children:t.jsx("code",{className:"routine-cron",children:e.command})}):null,e.trigger.type==="cron"&&p&&t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(wi,{size:12}),t.jsx("code",{className:"routine-cron",children:p})]}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Execution policy: ${e.executionPolicy}`,children:MR[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:AR[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:Mo(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:Mo(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(RR,{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(ui,{size:12}):t.jsx(Yt,{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(TR,{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 IR({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(ci,{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(ab,{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 ic(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function $R(e){return e==="command"?{id:ic(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:ic(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:ic(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function DR({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"),[A,w]=a.useState(e.timeoutMs),[E,C]=a.useState(e.continueOnFailure??!1),[z,_]=a.useState({}),[$,F]=a.useState([]),[V,D]=a.useState(!1),[T,I]=a.useState(null);a.useEffect(()=>{let P=!1;return D(!0),I(null),ds().then(R=>{P||F(R.models)}).catch(R=>{P||I(R instanceof Error?R.message:"Failed to load models")}).finally(()=>{P||D(!1)}),()=>{P=!0}},[]);const U=a.useCallback(()=>{const P={};return i.trim()||(P.name="Step name is required"),o==="command"&&!c.trim()&&(P.command="Command is required"),o==="ai-prompt"&&!d.trim()&&(P.prompt="Prompt is required"),o==="create-task"&&!b.trim()&&(P.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(h||p)&&(!h||!p)&&(P.modelProvider="Both model provider and model ID must be set together"),A!==void 0&&A<1e3&&(P.timeoutMs="Timeout must be at least 1 second (1000ms)"),_(P),Object.keys(P).length===0},[i,o,c,d,b,h,p,A]),Y=h&&p?`${h}/${p}`:"",ne=a.useCallback(P=>{if(!P)g(""),f("");else{const R=P.indexOf("/");R!==-1&&(g(P.slice(0,R)),f(P.slice(R+1)))}},[]),N=a.useCallback(()=>{if(!U())return;const P={...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:A||void 0,continueOnFailure:E};o!=="ai-prompt"&&delete P.prompt,o!=="create-task"&&(delete P.taskTitle,delete P.taskDescription,delete P.taskColumn),n(P)},[U,n,e,i,o,c,d,x,b,S,h,p,A,E]);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:P=>r(P.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:P=>l(P.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:P=>u(P.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:P=>m(P.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(Bn,{id:`step-model-${e.id}`,label:"Model",models:$,value:Y,onChange:ne,placeholder:"Use default",disabled:V}),T&&t.jsx("small",{className:"field-error",children:T}),t.jsx("small",{children:"AI model for this step. Uses default if not selected."})]})]}),o==="create-task"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-title-${e.id}`,children:"Task Title (optional)"}),t.jsx("input",{id:`step-task-title-${e.id}`,type:"text",placeholder:"e.g. Review weekly dependencies",value:x,onChange:P=>v(P.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:P=>y(P.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:P=>k(P.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(Bn,{id:`step-task-model-${e.id}`,label:"Model",models:$,value:Y,onChange:ne,placeholder:"Use default",disabled:V}),T&&t.jsx("small",{className:"field-error",children:T}),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:A??"",onChange:P=>w(P.target.value?Number(P.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:E,onChange:P=>C(P.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:N,children:"Save Step"})]})]})}function LR({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=$R(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(DR,{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(td,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(IR,{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(ui,{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(Yt,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(d.id),title:"Edit","aria-label":`Edit ${d.name}`,children:t.jsx(ts,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(d.id),title:"Delete","aria-label":`Delete ${d.name}`,children:t.jsx(nn,{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(sn,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx(sn,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx(sn,{size:14}),"Add Create Task Step"]})]})]})}const og={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},zR={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function OR(e){const n=e.trim();for(const[s,i]of Object.entries(og))if(i===n)return s;return"custom"}function FR(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function UR(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 BR(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 HR=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],qR=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function ph(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function fh({routine:e,onSubmit:n,onCancel:s,scope:i,projectId:r,onScopeChange:o}){const l=!!e,c=e?BR(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":OR(c.cronExpression)),[y,S]=a.useState(c.webhookPath),[k,A]=a.useState(c.webhookSecret),[w,E]=a.useState(c.endpoint),[C,z]=a.useState(e?.executionPolicy??"queue"),[_,$]=a.useState(e?.catchUpPolicy??"run_one"),[F,V]=a.useState(e?.enabled??!0),D=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,T=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[I,U]=a.useState(e?.steps&&e.steps.length>0&&!D&&!T?"advanced":"simple"),[Y,ne]=a.useState(()=>D?"ai-prompt":T?"create-task":"command"),[N,P]=a.useState(e?.command??""),[R,j]=a.useState(e?.steps??[]),[W,K]=a.useState(!1),[ke,be]=a.useState(e?.timeoutMs??3e5),[ce,ve]=a.useState(D?e.steps?.[0]?.prompt??"":""),[O,oe]=a.useState(T?e.steps?.[0]?.taskTitle??"":""),[te,pe]=a.useState(T?e.steps?.[0]?.taskDescription??"":""),[de,ge]=a.useState(T?e.steps?.[0]?.taskColumn??"triage":"triage"),[ie,Ee]=a.useState(D||T?e.steps?.[0]?.modelProvider??"":""),[Le,qe]=a.useState(D||T?e.steps?.[0]?.modelId??"":""),[et,Xe]=a.useState([]),[Ze,it]=a.useState(!1),[Ie,Ke]=a.useState(null),[re,xe]=a.useState(i??"global"),[se,Ae]=a.useState({}),[ze,me]=a.useState(!1),_e=a.useRef(!0);a.useEffect(()=>()=>{_e.current=!1},[]),a.useEffect(()=>{i&&xe(i)},[i]),a.useEffect(()=>{let X=!1;return it(!0),Ke(null),ds().then(Ye=>{X||Xe(Ye.models)}).catch(Ye=>{X||Ke(Ye instanceof Error?Ye.message:"Failed to load models")}).finally(()=>{X||it(!1)}),()=>{X=!0}},[]);const Fe=ie&&Le?`${ie}/${Le}`:"",nt=a.useCallback(X=>{if(!X){Ee(""),qe("");return}const Ye=X.indexOf("/");Ye!==-1&&(Ee(X.slice(0,Ye)),qe(X.slice(Ye+1)))},[]),we=a.useCallback(()=>{const X={};if(u.trim()||(X.name="Name is required"),re==="project"&&!r&&(X.scope="Project-specific entries require an active project."),g==="cron"&&v==="custom"&&(f.trim()?FR(f)||(X.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):X.cronExpression="Cron expression is required"),g==="webhook"&&!y.trim()&&(X.webhookPath="Webhook path is required"),g==="api"&&!w.trim()&&(X.endpoint="API endpoint is required"),I==="simple")Y==="command"&&!N.trim()&&(X.command="Command is required"),Y==="ai-prompt"&&!ce.trim()&&(X.prompt="Prompt is required"),Y==="create-task"&&!te.trim()&&(X.taskDescription="Task description is required"),(ie.trim()&&!Le.trim()||!ie.trim()&&Le.trim())&&(X.model="Both model provider and model ID must be set, or both must be empty");else{R.length===0&&(X.steps="At least one step is required"),W&&(X.stepsEditing="Please save or cancel all step edits before saving the routine");const Ye=[];R.forEach((ot,ht)=>{ot.name?.trim()||Ye.push(`Step ${ht+1}: Name is required`),ot.type==="command"&&!ot.command?.trim()&&Ye.push(`Step ${ht+1}: Command is required`),ot.type==="ai-prompt"&&!ot.prompt?.trim()&&Ye.push(`Step ${ht+1}: Prompt is required`),ot.type==="create-task"&&!ot.taskDescription?.trim()&&Ye.push(`Step ${ht+1}: Task description is required`)}),Ye.length>0&&(X.steps=Ye.join("; "))}return ke<1e3&&(X.timeoutMs="Timeout must be at least 1 second (1000ms)"),Ae(X),Object.keys(X).length===0},[u,g,f,v,y,w,re,r,I,Y,N,ce,te,ie,Le,R,W,ke]),le=a.useCallback(async X=>{if(X.preventDefault(),!!we()){me(!0);try{let Ye=e?.scope??re??(r?"project":"global");Ye==="project"&&!r&&(Ye="global");const ot=UR(g,f,y,k,w);let ht,yt;I==="simple"?Y==="command"?ht=N.trim()||void 0:Y==="ai-prompt"?yt=[{id:ph(),type:"ai-prompt",name:u.trim(),prompt:ce.trim(),modelProvider:ie.trim()||void 0,modelId:Le.trim()||void 0}]:yt=[{id:ph(),type:"create-task",name:u.trim(),taskTitle:O.trim()||void 0,taskDescription:te.trim(),taskColumn:de,modelProvider:ie.trim()||void 0,modelId:Le.trim()||void 0}]:yt=R;const vt={name:u.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:ot,command:ht,steps:yt,timeoutMs:ke,executionPolicy:C,catchUpPolicy:_,enabled:F,scope:Ye};await n(vt)}finally{_e.current&&me(!1)}}},[we,n,u,m,g,f,y,k,w,I,Y,N,ce,ie,Le,O,te,de,R,ke,C,_,F,re,r,e?.scope,e?.agentId]),Te="routine-name-error",he="routine-cron-error",Me="routine-webhook-error",We="routine-endpoint-error",Re="routine-command-error",ut="routine-prompt-error",Q="routine-task-description-error",ue="routine-model-error",ye="routine-timeout-error",at=a.useCallback(X=>{b(X),X!=="custom"&&x(og[X])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:le,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:X=>d(X.target.value),"aria-invalid":!!se.name,"aria-describedby":se.name?Te:void 0}),se.name&&t.jsx("small",{id:Te,className:"field-error",children:se.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:X=>h(X.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${re==="global"?" active":""}`,onClick:()=>{xe("global"),o?.("global")},role:"radio","aria-checked":re==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:"Global scope",children:[t.jsx($o,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${re==="project"?" active":""}`,onClick:()=>{xe("project"),o?.("project")},role:"radio","aria-checked":re==="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(Un,{size:12}),"Project"]})]}),t.jsx("small",{children:!r&&!e?.scope?"No active project. Routines will be created at global scope.":re==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),se.scope&&t.jsx("small",{className:"field-error",children:se.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(Vh,{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(np,{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(Wh,{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(Fn,{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:X=>at(X.target.value),children:Object.entries(zR).map(([X,Ye])=>t.jsx("option",{value:X,children:Ye},X))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:f,onChange:X=>x(X.target.value),disabled:v!=="custom","aria-invalid":!!se.cronExpression,"aria-describedby":se.cronExpression?he:void 0}),se.cronExpression?t.jsx("small",{id:he,className:"field-error",children:se.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:X=>S(X.target.value),"aria-invalid":!!se.webhookPath,"aria-describedby":se.webhookPath?Me:void 0}),se.webhookPath?t.jsx("small",{id:Me,className:"field-error",children:se.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:X=>A(X.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:w,onChange:X=>E(X.target.value),"aria-invalid":!!se.endpoint,"aria-describedby":se.endpoint?We:void 0}),se.endpoint?t.jsx("small",{id:We,className:"field-error",children:se.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:()=>U("simple"),role:"radio","aria-checked":I==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${I==="advanced"?" active":""}`,onClick:()=>U("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${Y==="command"?" active":""}`,onClick:()=>ne("command"),role:"radio","aria-checked":Y==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${Y==="ai-prompt"?" active":""}`,onClick:()=>ne("ai-prompt"),role:"radio","aria-checked":Y==="ai-prompt",children:"AI Prompt"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${Y==="create-task"?" active":""}`,onClick:()=>ne("create-task"),role:"radio","aria-checked":Y==="create-task",children:"Create Task"})]})]}),Y==="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:N,onChange:X=>P(X.target.value),"aria-invalid":!!se.command,"aria-describedby":se.command?Re:void 0}),se.command?t.jsx("small",{id:Re,className:"field-error",children:se.command}):t.jsx("small",{children:"Shell command to execute."})]}):Y==="ai-prompt"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-prompt",children:"Prompt"}),t.jsx("textarea",{id:"routine-prompt",placeholder:"e.g. Summarize recent activity and create action items",value:ce,onChange:X=>ve(X.target.value),rows:3,"aria-invalid":!!se.prompt,"aria-describedby":se.prompt?ut:void 0}),se.prompt?t.jsx("small",{id:ut,className:"field-error",children:se.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(Bn,{id:"routine-model",label:"Model",models:et,value:Fe,onChange:nt,placeholder:"Use default",disabled:Ze}),Ie&&t.jsx("small",{className:"field-error",children:Ie}),se.model&&t.jsx("small",{id:ue,className:"field-error",children:se.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:O,onChange:X=>oe(X.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:te,onChange:X=>pe(X.target.value),rows:4,"aria-invalid":!!se.taskDescription,"aria-describedby":se.taskDescription?Q:void 0}),se.taskDescription?t.jsx("small",{id:Q,className:"field-error",children:se.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:de,onChange:X=>ge(X.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(Bn,{id:"routine-task-model",label:"Executor Model",models:et,value:Fe,onChange:nt,placeholder:"Use default",disabled:Ze}),Ie&&t.jsx("small",{className:"field-error",children:Ie}),se.model&&t.jsx("small",{id:ue,className:"field-error",children:se.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(LR,{steps:R,onChange:j,onEditingChange:K}),se.steps&&t.jsx("small",{className:"field-error",children:se.steps}),se.stepsEditing&&t.jsx("small",{className:"field-error",children:se.stepsEditing})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-timeout",children:"Timeout (ms)"}),t.jsx("input",{id:"routine-timeout",type:"number",min:1e3,step:1e3,value:ke,onChange:X=>be(Number(X.target.value)),"aria-invalid":!!se.timeoutMs,"aria-describedby":se.timeoutMs?ye:void 0}),se.timeoutMs?t.jsx("small",{id:ye,className:"field-error",children:se.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:X=>z(X.target.value),children:HR.map(X=>t.jsx("option",{value:X.value,children:X.label},X.value))}),t.jsx("small",{children:"How to handle concurrent executions of this routine"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-catchup-policy",children:"Catch-up Policy"}),t.jsx("select",{id:"routine-catchup-policy",value:_,onChange:X=>$(X.target.value),children:qR.map(X=>t.jsx("option",{value:X.value,children:X.label},X.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:X=>V(X.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 VR=3e4;function WR({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);ti(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 D=await hj(v);l(D),f(T=>{const I={...T};for(const U of D){const Y=I[U.id];if(!Y||!U.lastRunResult)continue;const ne=U.lastRunResult;ne.success===Y.success&&(ne.output||"")===Y.output&&(ne.error||"")===(Y.error||"")&&delete I[U.id]}return I})}catch(D){n(Se(D)||"Failed to load routines","error")}},[n,v]);a.useEffect(()=>{b()},[b]),a.useEffect(()=>{const D=setInterval(()=>{b()},VR);return()=>clearInterval(D)},[b]),a.useEffect(()=>{const D=T=>{T.key==="Escape"&&(c!=="list"?(u("list"),m(void 0)):e())};return document.addEventListener("keydown",D),()=>document.removeEventListener("keydown",D)},[e,c]);const y=Si(e),S=a.useCallback(async D=>{try{await pj(D,v),n("Routine created","success"),u("list"),await b()}catch(T){n(Se(T)||"Failed to create routine","error")}},[n,b,v]),k=a.useCallback(D=>{m(D),u("edit")},[]),A=a.useCallback(async D=>{if(d)try{await Zd(d.id,D,v),n("Routine updated","success"),u("list"),m(void 0),await b()}catch(T){n(Se(T)||"Failed to update routine","error")}},[d,n,b,v]),w=a.useCallback(async D=>{try{await fj(D.id,v),n(`Deleted "${D.name}"`,"success"),await b()}catch(T){n(Se(T)||"Failed to delete routine","error")}},[n,b,v]),E=a.useCallback(async D=>{g(D.id);try{const{result:T}=await gj(D.id,v);f(I=>({...I,[D.id]:{output:T.output||"",error:T.error,success:T.success}})),T.success?n(`"${D.name}" completed successfully`,"success"):n(`"${D.name}" failed: ${T.error||"Unknown error"}`,"error"),await b()}catch(T){n(Se(T)||"Failed to run routine","error")}finally{g(null)}},[n,b,v]),C=a.useCallback(async D=>{try{await Zd(D.id,{enabled:!D.enabled},v),n(`"${D.name}" ${D.enabled?"disabled":"enabled"}`,"success"),await b()}catch(T){n(Se(T)||"Failed to toggle routine","error")}},[n,b,v]),z=a.useCallback(()=>{u("list"),m(void 0)},[]);a.useEffect(()=>{c!=="list"&&f({})},[c]);const _=a.useCallback(D=>{r(D),u("list"),m(void 0),f({})},[]),$=()=>c==="create"?t.jsx(fh,{onSubmit:S,onCancel:z,scope:i,projectId:s}):c==="edit"&&d?t.jsx(fh,{routine:d,onSubmit:A,onCancel:z,scope:i,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(Fn,{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(sn,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map(D=>t.jsx(PR,{routine:D,onEdit:k,onDelete:w,onRun:E,onToggle:C,running:h===D.id,lastRunOutput:p[D.id]??null},D.id))}),F=()=>$(),V=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(Fn,{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(Kt,{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:()=>_("global"),"aria-pressed":i==="global",title:"Global (user-level) automations",children:[t.jsx($o,{size:14}),"Global"]}),t.jsxs("button",{type:"button",className:`scope-btn${i==="project"?" active":""}`,onClick:()=>_("project"),"aria-pressed":i==="project",title:"Project-scoped automations",children:[t.jsx(Un,{size:14}),"Project"]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(Fn,{size:14}),o.length," automation",o.length===1?"":"s"]})]}),t.jsx("div",{className:"scheduling-toolbar-right",children:V&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>u("create"),"aria-label":"Create new automation",children:[t.jsx(sn,{size:14}),"New Automation"]})})]}),t.jsx("div",{className:"schedule-modal-content",id:"scheduled-tasks-content",children:F()})]})})}const KR=3e4,Gc=new Map,ac=new Map;function gh(e){return e??"default"}function xh(e){const n=Gc.get(e);return n?Date.now()>=n.expiresAt?(Gc.delete(e),null):n:null}function GR(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 JR(e){const n=ac.get(e);if(n)return n;const s=xr().then(({providers:i,ghCli:r})=>{const l={...GR(i,r),ghCli:r,expiresAt:Date.now()+KR};return Gc.set(e,l),l}).finally(()=>{ac.delete(e)});return ac.set(e,s),s}function lg(e){const n=gh(e),s=xh(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=gh(e),p=xh(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 JR(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 cg({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(Kt,{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 YR({isOpen:e,onClose:n,projectId:s,tasks:i,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const{confirm:u}=Bs(),[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(""),[A,w]=a.useState(""),[E,C]=a.useState(""),[z,_]=a.useState(""),[$,F]=a.useState("default"),[V,D]=a.useState(!1),[T,I]=a.useState([]),[U,Y]=a.useState(!1),[ne,N]=a.useState(void 0),[P,R]=a.useState(bs),[j,W]=a.useState(void 0),[K,ke]=a.useState(null),[be,ce]=a.useState([]),[ve,O]=a.useState(!1),[oe,te]=a.useState(!1),pe=a.useRef(null),[de,ge]=a.useState(!1),[ie,Ee]=a.useState(""),Le=a.useRef(null),{hasAiProvider:qe,hasGithub:et,loading:Xe}=lg(s),{nodes:Ze}=Vo(),it=a.useCallback(we=>{Y(!0),I(we)},[]),Ie=a.useCallback(()=>{Y(!1)},[]),Ke=a.useCallback(async()=>{if(be.length>0){O(!0);return}te(!0);try{const we=await Ma(void 0,s);ce(we),O(!0)}catch(we){const le=Se(we);o(le?`Failed to load agents: ${le}`:"Failed to load agents","error"),O(!1)}finally{te(!1)}},[be.length,s,o]);a.useEffect(()=>{if(!ve)return;const we=le=>{pe.current&&!pe.current.contains(le.target)&&O(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[ve]),a.useEffect(()=>{if(!de)return;const we=le=>{Le.current&&!Le.current.contains(le.target)&&(ge(!1),Ee(""))};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[de]);const re=i.filter(we=>!h.includes(we.id)).sort((we,le)=>{const Te=le.createdAt.localeCompare(we.createdAt);if(Te!==0)return Te;const he=parseInt(we.id.slice(we.id.lastIndexOf("-")+1),10)||0;return(parseInt(le.id.slice(le.id.lastIndexOf("-")+1),10)||0)-he}),xe=ie?re.filter(we=>we.id.toLowerCase().includes(ie.toLowerCase())||we.title&&we.title.toLowerCase().includes(ie.toLowerCase())||we.description&&we.description.toLowerCase().includes(ie.toLowerCase())):re,se=(we,le)=>we.length>le?we.slice(0,le)+"…":we;a.useEffect(()=>{const we=d.trim()!==""||h.length>0||p.length>0||b!==""||S!==""||A!==""||E!==""||T.length>0||K!==null||ne!==void 0||P!==bs||j!==void 0;D(we)},[d,h,p,b,S,A,E,T,K,ne,P,j]);const Ae=a.useCallback(async()=>{V&&!await u({title:"Discard Changes",message:"You have unsaved changes. Discard them?",danger:!0})||(p.forEach(we=>URL.revokeObjectURL(we.previewUrl)),f([]),m(""),g([]),y(""),k(""),w(""),C(""),_(""),F("default"),I([]),Y(!1),ke(null),O(!1),N(void 0),R(bs),W(void 0),D(!1),n())},[V,n,p,u]),ze=a.useCallback(async()=>{const we=d.trim();if(!(!we||x)){v(!0);try{const le=b.indexOf("/"),Te=S.indexOf("/"),he=A.indexOf("/"),Me=await r({title:void 0,description:we,column:"triage",dependencies:h.length?h:void 0,enabledWorkflowSteps:U?T.length>0?T:[]:void 0,...K?{assignedAgentId:K}:{},modelPresetId:$==="preset"&&z||void 0,modelProvider:b&&le!==-1?b.slice(0,le):void 0,modelId:b&&le!==-1?b.slice(le+1):void 0,validatorModelProvider:S&&Te!==-1?S.slice(0,Te):void 0,validatorModelId:S&&Te!==-1?S.slice(Te+1):void 0,planningModelProvider:A&&he!==-1?A.slice(0,he):void 0,planningModelId:A&&he!==-1?A.slice(he+1):void 0,thinkingLevel:E!==""?E:void 0,reviewLevel:ne,priority:P,nodeId:j});if(p.length>0){const We=[];for(const Re of p)try{await gr(Me.id,Re.file,s)}catch{We.push(Re.file.name)}We.length>0&&o(`Failed to upload: ${We.join(", ")}`,"error")}p.forEach(We=>URL.revokeObjectURL(We.previewUrl)),f([]),m(""),g([]),y(""),k(""),w(""),C(""),_(""),F("default"),I([]),Y(!1),ke(null),O(!1),N(void 0),R(bs),W(void 0),o(`Created ${Me.id}`,"success"),n()}catch(le){o(Se(le)||"Failed to create task","error")}finally{v(!1)}}},[d,h,p,b,S,A,E,x,r,o,n,s,$,z,T,U,K,ne,P,j]),me=a.useCallback(we=>{we.key==="Escape"&&(we.preventDefault(),Ae())},[Ae]),Fe=(K?be.find(we=>we.id===K):void 0)?.name??K,nt=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:Le,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>ge(we=>!we),disabled:x,"data-testid":"dep-trigger",children:h.length>0?`${h.length} selected`:"Add dependencies"}),de&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:ie,onChange:we=>Ee(we.target.value),onClick:we=>we.stopPropagation()}),xe.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):xe.map(we=>t.jsxs("div",{className:`dep-dropdown-item${h.includes(we.id)?" selected":""}`,onClick:()=>{g(h.includes(we.id)?h.filter(le=>le!==we.id):[...h,we.id]),ge(!1),Ee("")},onMouseDown:le=>le.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:we.id}),t.jsx("span",{className:"dep-dropdown-title",children:se(we.title||we.description||we.id,30)})]},we.id))]})]}),h.length>0&&t.jsx("div",{className:"selected-deps",children:h.map(we=>t.jsxs("span",{className:"dep-chip",children:[we,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>g(h.filter(le=>le!==we)),disabled:x,children:"×"})]},we))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:pe,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{ve?O(!1):Ke()},disabled:x,"data-testid":"new-task-agent-button",children:[t.jsx(kn,{size:12,style:{verticalAlign:"middle"}}),Fe?` ${Fe}`:" Assign agent"]}),ve&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:we=>we.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),oe&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!oe&&be.filter(we=>we.state!=="terminated").map(we=>t.jsxs("div",{className:`dep-dropdown-item${K===we.id?" selected":""}`,onMouseDown:le=>le.preventDefault(),onClick:()=>{ke(we.id===K?null:we.id),O(!1)},"data-testid":`agent-option-${we.id}`,children:[t.jsx(kn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:we.role}),t.jsx("span",{className:"dep-dropdown-title",children:we.name})]},we.id)),!oe&&be.filter(we=>we.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),K&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:we=>we.preventDefault(),onClick:()=>{ke(null),O(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:Ae,onKeyDown:me,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:we=>we.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:Ae,disabled:x,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!Xe&&t.jsx(cg,{hasAiProvider:qe,hasGithub:et}),t.jsx(Zf,{mode:"create",description:d,onDescriptionChange:m,dependencies:h,onDependenciesChange:g,executorModel:b,onExecutorModelChange:y,validatorModel:S,onValidatorModelChange:k,presetMode:$,onPresetModeChange:F,selectedPresetId:z,onSelectedPresetIdChange:_,selectedWorkflowSteps:T,onWorkflowStepsChange:it,onDefaultOnApplied:Ie,pendingImages:p,onImagesChange:f,tasks:i,projectId:s,disabled:x,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:Ae,planningModel:A,onPlanningModelChange:w,thinkingLevel:E,onThinkingLevelChange:C,reviewLevel:ne,onReviewLevelChange:N,priority:P,onPriorityChange:R,nodeId:j,onNodeIdChange:W,nodeOptions:Ze,renderBelowPrimary:nt,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Ae,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 li(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 bh(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function QR(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function XR(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function ZR(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function rc(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function eT(e){if(!e)return"Not yet";const n=new Date(e);return Number.isNaN(n.getTime())?"Not yet":n.toLocaleString()}function tT({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),[A,w]=a.useState(null),E=a.useCallback(async P=>{l(!0);try{const R=await Bj(s);r(R),u(null),w(Date.now()),P?.preserveKillResult||y(null)}catch(R){u(R instanceof Error?R.message:"Failed to load system stats")}finally{l(!1)}},[s]);a.useEffect(()=>{if(!e)return;E();const P=window.setInterval(()=>{E()},5e3);return()=>{window.clearInterval(P)}},[e,E]),a.useEffect(()=>{if(!e)return;(async()=>{try{const R=await Ki();m(R.vitestAutoKillEnabled??!0),g(R.vitestKillThresholdPct??90),k(null)}catch(R){k(R instanceof Error?R.message:"Failed to load vitest settings")}})()},[e]),a.useEffect(()=>{if(!e)return;const P=R=>{R.key==="Escape"&&n()};return document.addEventListener("keydown",P),()=>document.removeEventListener("keydown",P)},[e,n]);const C=a.useMemo(()=>{if(!i)return[];const P=i.systemStats,R=rc(QR(P.heapUsed,P.heapLimit)),j=rc(XR(P.rss,P.systemTotalMem));return[{label:"RSS",value:li(P.rss),detail:bh(P.rss,P.systemTotalMem),className:j},{label:"Heap Used",value:li(P.heapUsed),detail:`of ${li(P.heapTotal)}`,className:R},{label:"Heap Limit",value:li(P.heapLimit),detail:"V8 limit"},{label:"External",value:li(P.external)},{label:"Array Buffers",value:li(P.arrayBuffers)}]},[i]),z=a.useCallback(async P=>{m(P);try{await cn({vitestAutoKillEnabled:P}),k(null)}catch(R){k(R instanceof Error?R.message:"Failed to save vitest settings")}},[]),_=a.useCallback(async P=>{const R=Math.min(99,Math.max(50,Number.isFinite(P)?Math.round(P):90));g(R);try{await cn({vitestKillThresholdPct:R}),k(null)}catch(j){k(j instanceof Error?j.message:"Failed to save vitest settings")}},[]),$=a.useCallback(async()=>{if(!p){if(!x){v(!0);return}f(!0);try{const P=await Hj(s);y(P),v(!1),await E({preserveKillResult:!0})}catch(P){u(P instanceof Error?P.message:"Failed to kill vitest processes")}finally{f(!1)}}},[x,p,E,s]);if(!e)return null;const F=i?.systemStats,V=o&&!!i,D=A?`Updated ${new Date(A).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`:"Waiting for first update",T=i?.taskStats,I=F?F.systemTotalMem-F.systemFreeMem:0,U=F?rc(ZR(I,F.systemTotalMem)):"",Y=i?.vitestProcessCount,ne=b?b.killed>0?"system-stats-modal__kill-result system-stats-modal__kill-result--success":"system-stats-modal__kill-result system-stats-modal__kill-result--error":"",N=eT(i?.vitestLastAutoKillAt);return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"system-stats-modal-title",onClick:P=>{P.target===P.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(hr,{}),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:D})]}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void E(),title:"Refresh","aria-label":"Refresh system stats",children:t.jsx(Mn,{size:16,className:V?"system-stats-modal__refresh--spinning":void 0})}),t.jsx("button",{type:"button",className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Kt,{})})]})]}),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(P=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:P.label}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${P.className}`.trim(),children:P.value}),P.detail?t.jsx("span",{className:"system-stats-modal__detail",children:P.detail}):null]})]},P.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(P=>P.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 ${U}`.trim(),children:F?li(I):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:F?`${bh(I,F.systemTotalMem)} of ${li(F.systemTotalMem)}`:""})]})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Free"}),t.jsx("dd",{children:F?li(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:T?.total??0})]}),Object.entries(T?.byColumn??{}).map(([P,R])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:P}),t.jsx("dd",{children:R})]},P))]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Agent stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Agents"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"idle"}),t.jsx("dd",{children:T?.agents.idle??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"active"}),t.jsx("dd",{children:T?.agents.active??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"running"}),t.jsx("dd",{children:T?.agents.running??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"error"}),t.jsx("dd",{children:T?.agents.error??0})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Vitest controls",children:[t.jsxs("h3",{className:"system-stats-modal__section-title system-stats-modal__section-title--with-icon",children:[t.jsx(Ub,{}),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:Y??"—"})]})}),t.jsxs("div",{className:"system-stats-modal__vitest-controls",children:[t.jsx("div",{className:"system-stats-modal__kill-row",children:t.jsxs("button",{type:"button",className:"btn btn-danger",onClick:()=>void $(),disabled:p||Y===0,children:[t.jsx(Vb,{}),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:P=>{z(P.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:P=>{const R=Number.parseInt(P.target.value,10);_(Number.isNaN(R)?90:R)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:h,"aria-label":"Kill threshold (%)",onChange:P=>{const R=Number.parseInt(P.target.value,10);_(Number.isNaN(R)?90:R)},onBlur:()=>{_(h)}})]})]}),b&&t.jsxs("p",{className:ne,children:["Killed ",b.killed," processes"]}),t.jsxs("p",{className:"system-stats-modal__last-kill",children:["Last auto-kill: ",N]}),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 nT=5e3;function sT(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 ru({limit:i,projectId:n,type:s}):S=(await eu({limit:i,type:s,projectId:n})).map(A=>({...A,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 ru({limit:i,projectId:n,type:s,since:x.current}):S=(await eu({limit:i,type:s,since:x.current,projectId:n})).map(A=>({...A,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()},nT),()=>{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 oc={"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"},iT={"task:created":t.jsx(sn,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(Nr,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(Mn,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(Kt,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(vn,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(Sr,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(or,{size:14,className:"activity-icon settings"})};function aT(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 rT({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:A}=sT({projectId:x,type:f,limit:100,autoRefresh:e,useCentralFeed:v}),w=b.map($=>({id:$.id,timestamp:$.timestamp,type:$.type,taskId:$.taskId,taskTitle:$.taskTitle,details:$.details,metadata:$.metadata,projectId:$.projectId,projectName:$.projectName})),E=async()=>{try{await xj(),k(),p(!1)}catch{p(!1)}},C=$=>{i&&i($)},z=$=>{h($),l?.($==="all"?void 0:$)};a.useEffect(()=>{if(!e)return;const $=F=>{F.key==="Escape"&&(g?p(!1):n())};return document.addEventListener("keydown",$),()=>document.removeEventListener("keydown",$)},[e,n,g]);const _=u!=="all"||m!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:$=>{$.target===$.currentTarget&&n()},role:"dialog","aria-modal":"true","data-testid":"activity-log-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg activity-log-modal","data-testid":"activity-log-modal",children:[t.jsxs("div",{className:"modal-header activity-log-header",children:[t.jsxs("div",{className:"activity-log-title",children:[t.jsx(mr,{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(Un,{size:14}),t.jsxs("select",{value:m,onChange:$=>z($.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map($=>t.jsx("option",{value:$.id,children:$.name},$.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(go,{size:14}),t.jsxs("select",{value:u,onChange:$=>d($.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(oc).map(([$,F])=>t.jsx("option",{value:$,children:F},$))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>k(),title:"Refresh","data-testid":"activity-refresh",children:y?t.jsx(rt,{size:14,className:"spin"}):t.jsx(Mn,{size:14})}),w.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:t.jsx(nn,{size:14})})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",title:"Close","data-testid":"activity-close",children:"×"})]}),_&&t.jsxs("div",{className:"activity-log-active-filters",children:[t.jsx("span",{className:"activity-log-filter-label",children:"Active filters:"}),m!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Project: ",o.find($=>$.id===m)?.name||m]}),u!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",oc[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(ss,{size:16}),t.jsx("span",{children:S})]}),w.length===0&&!y&&!S&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(mr,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:_?"No activity matches the current filters":"No activity recorded yet"}),_&&t.jsx("button",{className:"btn btn-secondary",onClick:()=>{d("all"),h("all"),l?.(void 0)},children:"Clear Filters"})]}),t.jsx("div",{className:"activity-log-list",children:w.map($=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:iT[$.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:oc[$.type]}),t.jsx("span",{className:"activity-log-entry-time",children:aT($.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[$.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>C($.taskId),"data-testid":"activity-task-link",children:$.taskId}),$.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:$.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:$.details})]}),$.metadata&&Object.keys($.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof $.metadata.from=="string"&&typeof $.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[$.metadata.from," → ",$.metadata.to]}),typeof $.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${$.metadata.merged?"success":"error"}`,children:$.metadata.merged?"Merged":"Not merged"})]})]})]},$.id))}),A&&!y&&t.jsx("button",{className:"activity-log-load-more",onClick:k,"data-testid":"activity-load-more",children:"Load More"}),y&&w.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(rt,{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:E,children:"Clear Log"})]})]})})]})}):null}const Xa=[{id:"status",label:"Status",icon:Zh},{id:"changes",label:"Changes",icon:jc},{id:"commits",label:"Commits",icon:Cr},{id:"branches",label:"Branches",icon:Xs},{id:"worktrees",label:"Worktrees",icon:Wx},{id:"stashes",label:"Stashes",icon:To},{id:"remotes",label:"Remotes",icon:Jh}];function vh({status:e}){switch(e){case"added":case"untracked":return t.jsx(Ex,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(Kh,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(Nx,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(Ui,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(Mx,{size:14,className:"gm-file-icon"})}}function yh({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 oT(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 wa(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 lT({isOpen:e,onClose:n,tasks:s,addToast:i,projectId:r}){const o=Bs(),[l,c]=a.useState("status"),[u,d]=a.useState(!1),[m,h]=a.useState(null),g=a.useRef(null);ti(g,e,"fusion:git-modal-size");const p=Si(n),f=oT(i),[x,v]=a.useState(null),[b,y]=a.useState([]),[S,k]=a.useState(new Set),[A,w]=a.useState(""),[E,C]=a.useState(!1),[z,_]=a.useState(null),[$,F]=a.useState(!1),[V,D]=a.useState(null),[T,I]=a.useState(null),U=a.useRef(0),[Y,ne]=a.useState([]),[N,P]=a.useState(null),[R,j]=a.useState(null),[W,K]=a.useState(!1),[ke,be]=a.useState(20),[ce,ve]=a.useState(""),[O,oe]=a.useState([]),[te,pe]=a.useState(""),[de,ge]=a.useState(""),[ie,Ee]=a.useState(""),[Le,qe]=a.useState(null),[et,Xe]=a.useState([]),[Ze,it]=a.useState(!1),[Ie,Ke]=a.useState(null),[re,xe]=a.useState(null),[se,Ae]=a.useState(!1),[ze,me]=a.useState([]),[_e,Fe]=a.useState([]),[nt,we]=a.useState(""),[le,Te]=a.useState(null),[he,Me]=a.useState(null),[We,Re]=a.useState(null),ut=a.useCallback(async()=>{if(e){d(!0),h(null);try{switch(l){case"status":{const H=await zs(r);v(H);break}case"changes":{const[H,fe]=await Promise.all([zs(r),na(r)]);v(H),y(fe),k(new Set),I(null),_(null),D(null);break}case"commits":{const H=await wy(ke,r);ne(H);break}case"branches":{const[H,fe]=await Promise.all([za(r),zs(r)]);oe(H),v(fe);break}case"worktrees":{const H=await Ey(r);me(H);break}case"stashes":{const H=await qr(r);Fe(H);break}case"remotes":{const H=await zs(r);v(H);break}}}catch(H){h(Se(H)||"Failed to fetch git data"),i(Se(H)||"Failed to fetch git data","error")}finally{d(!1)}}},[l,e,ke,i,r]);a.useEffect(()=>{e&&ut()},[ut,e]),a.useEffect(()=>{if(!e)return;const H=fe=>{if(fe.key==="Escape"){n();return}if((fe.key==="ArrowUp"||fe.key==="ArrowDown")&&fe.altKey){fe.preventDefault();const $e=Xa.findIndex(M=>M.id===l);fe.key==="ArrowUp"&&$e>0?c(Xa[$e-1].id):fe.key==="ArrowDown"&&$e<Xa.length-1&&c(Xa[$e+1].id)}};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[e,n,l]);const Q=a.useCallback(async H=>{try{await Jd(H,r),i(`Staged ${H.length} file(s)`,"success");const fe=await na(r);y(fe),k(new Set),I(null),_(null),D(null)}catch(fe){i(Se(fe)||"Failed to stage files","error")}},[i,r]),ue=a.useCallback(async H=>{try{await Ly(H,r),i(`Unstaged ${H.length} file(s)`,"success");const fe=await na(r);y(fe),k(new Set),I(null),_(null),D(null)}catch(fe){i(Se(fe)||"Failed to unstage files","error")}},[i,r]),ye=a.useCallback(async H=>{if(await o.confirm({title:"Discard Changes",message:`Discard changes to ${H.length} file(s)? This cannot be undone.`,danger:!0}))try{await zy(H,r),i(`Discarded changes to ${H.length} file(s)`,"success");const[$e,M]=await Promise.all([na(r),zs(r)]);y($e),v(M),k(new Set),I(null),_(null),D(null)}catch($e){i(Se($e)||"Failed to discard changes","error")}},[i,r,confirm]),at=a.useCallback(async H=>{if(H.preventDefault(),!!A.trim()){C(!0);try{const fe=await Yd(A.trim(),r);i(`Committed: ${fe.hash}`,"success"),w("");const[$e,M]=await Promise.all([na(r),zs(r)]);y($e),v(M),I(null),_(null),D(null)}catch(fe){i(Se(fe)||"Failed to commit","error")}finally{C(!1)}}},[A,i,r]),X=a.useCallback(async()=>{if(A.trim()){C(!0);try{const H=b.filter(ee=>!ee.staged).map(ee=>ee.file);H.length>0&&await Jd(H,r);const fe=await Yd(A.trim(),r);i(`Committed: ${fe.hash}`,"success"),w("");const[$e,M]=await Promise.all([na(r),zs(r)]);y($e),v(M),I(null),_(null),D(null)}catch(H){i(Se(H)||"Failed to commit","error")}finally{C(!1)}}},[A,b,i,r]),Ye=a.useCallback(async(H,fe)=>{I({file:H,staged:fe}),F(!0),D(null);const $e=U.current+1;U.current=$e;try{const M=await Dy(H,fe,r);if(U.current!==$e)return;_(M)}catch(M){if(U.current!==$e)return;const ee=Se(M)||"Failed to load file diff";_(null),D(ee),i(ee,"error")}finally{U.current===$e&&F(!1)}},[i,r]),ot=a.useCallback(H=>{k(fe=>{const $e=new Set(fe);return $e.has(H)?$e.delete(H):$e.add(H),$e})},[]),ht=a.useCallback(async H=>{if(N===H){P(null),j(null);return}P(H),K(!0);try{const fe=await vo(H,r);j(fe)}catch(fe){i(Se(fe)||"Failed to load diff","error"),j(null)}finally{K(!1)}},[N,i,r]),yt=a.useCallback(()=>{be(H=>Math.min(H+20,100))},[]),vt=a.useMemo(()=>{if(!ce.trim())return Y;const H=ce.toLowerCase();return Y.filter(fe=>fe.message.toLowerCase().includes(H)||fe.author.toLowerCase().includes(H)||fe.shortHash.toLowerCase().includes(H))},[Y,ce]),pt=a.useCallback(async H=>{if(H.preventDefault(),!!te.trim()){d(!0);try{await _y(te.trim(),de.trim()||void 0,r),i(`Created branch ${te}`,"success"),pe(""),ge("");const fe=await za(r);oe(fe)}catch(fe){i(Se(fe)||"Failed to create branch","error")}finally{d(!1)}}},[te,de,i,r]),Et=a.useCallback(async H=>{d(!0);try{await My(H,r),i(`Switched to ${H}`,"success");const[fe,$e]=await Promise.all([zs(r),za(r)]);v(fe),oe($e)}catch(fe){i(Se(fe)||"Failed to checkout branch","error")}finally{d(!1)}},[i,r]),It=a.useCallback(async H=>{if(await o.confirm({title:"Delete Branch",message:`Delete branch "${H}"?`,danger:!0})){d(!0);try{await Gd(H,void 0,r),i(`Deleted branch ${H}`,"success");const $e=await za(r);oe($e)}catch($e){if(Se($e).includes("not fully merged")){if(await o.confirm({title:"Force Delete Branch",message:"Branch has unmerged commits. Force delete?",danger:!0}))try{await Gd(H,!0,r),i(`Force deleted branch ${H}`,"success");const ee=await za(r);oe(ee)}catch(ee){i(Se(ee)||"Failed to delete branch","error")}}else i(Se($e)||"Failed to delete branch","error")}finally{d(!1)}}},[i,r,confirm]),Bt=a.useMemo(()=>{if(!ie.trim())return O;const H=ie.toLowerCase();return O.filter(fe=>fe.name.toLowerCase().includes(H))},[O,ie]),_t=a.useCallback(async H=>{if(Le===H){qe(null),Xe([]),Ke(null),xe(null);return}qe(H),Xe([]),Ke(null),xe(null),it(!0);try{const fe=await Cy(H,10,r);Xe(fe)}catch{Xe([])}finally{it(!1)}},[Le,r]),Pt=a.useCallback(async H=>{if(Ie===H){Ke(null),xe(null);return}Ke(H),xe(null),Ae(!0);try{const fe=await vo(H,r);xe(fe)}catch{xe(null)}finally{Ae(!1)}},[Ie,r]),$t=a.useCallback(()=>{qe(null),Xe([]),Ke(null),xe(null)},[]),Ht=a.useCallback(async H=>{H.preventDefault(),Te("create");try{await Py(nt.trim()||void 0,r),i("Changes stashed","success"),we("");const fe=await qr(r);Fe(fe)}catch(fe){i(Se(fe)||"Failed to stash changes","error")}finally{Te(null)}},[nt,i,r]),Gt=a.useCallback(async(H,fe=!1)=>{Te(`apply-${H}`);try{await Iy(H,fe,r),i(fe?"Stash popped":"Stash applied","success");const $e=await qr(r);Fe($e)}catch($e){i(Se($e)||"Failed to apply stash","error")}finally{Te(null)}},[i,r]),Dt=a.useCallback(async H=>{if(await o.confirm({title:"Drop Stash",message:`Drop stash@{${H}}? This cannot be undone.`,danger:!0})){Te(`drop-${H}`);try{await $y(H,r),i("Stash dropped","success");const $e=await qr(r);Fe($e)}catch($e){i(Se($e)||"Failed to drop stash","error")}finally{Te(null)}}},[i,r,confirm]),Tt=a.useCallback(async()=>{Me("fetch");try{const H=await Ay(void 0,r);Re(H),i(H.message||"Fetch completed",H.fetched?"success":"info");const fe=await zs(r);v(fe)}catch(H){i(Se(H)||"Fetch failed","error")}finally{Me(null)}},[i,r]),jt=a.useCallback(async()=>{Me("pull");try{const H=await Ry(r);Re(H),H.conflict?i("Merge conflict detected. Resolve manually.","error"):i(H.message||"Pull completed","success");const fe=await zs(r);v(fe)}catch(H){i(Se(H)||"Pull failed","error")}finally{Me(null)}},[i,r]),Mt=a.useCallback(async()=>{Me("push");try{const H=await Ty(r);Re(H),i(H.message||"Push completed","success");const fe=await zs(r);v(fe)}catch(H){i(Se(H)||"Push failed","error")}finally{Me(null)}},[i,r]),Zt=a.useMemo(()=>b.filter(H=>H.staged),[b]),At=a.useMemo(()=>b.filter(H=>!H.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(kc,{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:ut,disabled:u,title:"Refresh",children:t.jsx(Mn,{size:14,className:u?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Kt,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:Xa.map(H=>{const fe=H.icon;return t.jsxs("button",{role:"tab","aria-selected":l===H.id,className:`gm-nav-item${l===H.id?" active":""}`,onClick:()=>c(H.id),children:[t.jsx(fe,{size:16}),t.jsx("span",{className:"gm-nav-label",children:H.label})]},H.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[u&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(rt,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),m&&!u&&t.jsxs("div",{className:"gm-error",children:[t.jsx(ss,{size:18}),t.jsx("span",{children:m}),t.jsx("button",{className:"btn btn-sm",onClick:ut,children:"Retry"})]}),l==="status"&&!u&&x&&t.jsx(cT,{status:x,copyToClipboard:f}),l==="changes"&&!u&&t.jsx(dT,{status:x,stagedFiles:Zt,unstagedFiles:At,selectedFiles:S,toggleFileSelection:ot,onStageFiles:Q,onUnstageFiles:ue,onDiscardChanges:ye,onSelectDiffFile:Ye,selectedDiffTarget:T,changeDiff:z,loadingChangeDiff:$,changeDiffError:V,commitMessage:A,setCommitMessage:w,onCommit:at,onStageAllAndCommit:X,committing:E}),l==="commits"&&!u&&t.jsx(uT,{commits:vt,commitSearch:ce,setCommitSearch:ve,selectedCommit:N,commitDiff:R,loadingDiff:W,onCommitClick:ht,onLoadMore:yt,canLoadMore:Y.length>=ke&&ke<100,copyToClipboard:f}),l==="branches"&&!u&&t.jsx(mT,{branches:Bt,branchSearch:ie,setBranchSearch:Ee,newBranchName:te,setNewBranchName:pe,branchBase:de,setBranchBase:ge,onCreateBranch:pt,onCheckoutBranch:Et,onDeleteBranch:It,loading:u,allBranches:O,selectedBranch:Le,branchCommits:et,loadingBranchCommits:Ze,expandedBranchCommit:Ie,branchCommitDiff:re,loadingBranchCommitDiff:se,onSelectBranch:_t,onBranchCommitClick:Pt,onCloseBranchDetails:$t}),l==="worktrees"&&!u&&t.jsx(hT,{worktrees:ze}),l==="stashes"&&!u&&t.jsx(pT,{stashes:_e,stashMessage:nt,setStashMessage:we,onCreateStash:Ht,onApplyStash:Gt,onDropStash:Dt,stashLoading:le}),l==="remotes"&&!u&&t.jsx(fT,{status:x,remoteLoading:he,lastRemoteResult:We,onFetch:Tt,onPull:jt,onPush:Mt,addToast:i,projectId:r,copyToClipboard:f})]})]})]})}):null}function cT({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(Xs,{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(ss,{size:12}),"Modified"]}):t.jsxs(t.Fragment,{children:[t.jsx(vn,{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(zi,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx(wr,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(vn,{size:12}),"Up to date"]})]})]})]})]})}function dT({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(Xs,{size:14}),e.branch]}),e.isDirty&&t.jsx("span",{className:"gm-dirty-badge",children:"Modified"})]}),t.jsxs("div",{className:"gm-changes-split",children:[t.jsxs("div",{className:"gm-changes-lists",children:[t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Unstaged Changes (",s.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[y.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(y.map(k=>k.file)),title:"Stage selected",children:[t.jsx(sn,{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(Sr,{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 A=d?.file===k.file&&d.staged===!1;return t.jsxs("div",{className:`gm-file-item${A?" active":""}`,onClick:()=>u(k.file,!1),role:"button",tabIndex:0,onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),u(k.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:w=>w.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`unstaged:${k.file}`),onChange:()=>r(`unstaged:${k.file}`)})}),t.jsx(vh,{status:k.status}),t.jsx("span",{className:"gm-file-name",title:k.file,children:t.jsx("bdo",{dir:"ltr",children:k.file})}),t.jsx(yh,{status:k.status}),t.jsx("button",{className:"gm-icon-btn",onClick:w=>{w.stopPropagation(),o([k.file])},title:"Stage file",children:t.jsx(sn,{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 A=d?.file===k.file&&d.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${A?" active":""}`,onClick:()=>u(k.file,!0),role:"button",tabIndex:0,onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),u(k.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:w=>w.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`staged:${k.file}`),onChange:()=>r(`staged:${k.file}`)})}),t.jsx(vh,{status:k.status}),t.jsx("span",{className:"gm-file-name",title:k.file,children:t.jsx("bdo",{dir:"ltr",children:k.file})}),t.jsx(yh,{status:k.status}),t.jsx("button",{className:"gm-icon-btn",onClick:w=>{w.stopPropagation(),l([k.file])},title:"Unstage file",children:t.jsx(Kt,{size:12})})]},`staged:${k.file}`)})})]})]}),t.jsx("div",{className:"gm-changes-diff",children:d||h||m||g?t.jsxs("div",{className:"gm-diff-section",children:[d&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(jc,{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(rt,{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("div",{className:"gm-diff-empty",children:[t.jsx(jc,{size:20}),t.jsx("span",{children:"Select a file to view its diff"})]})})]}),t.jsxs("form",{className:"gm-commit-form",onSubmit:x,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:k=>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(rt,{size:14,className:"spin"}):t.jsx(Li,{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 uT({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(ma,{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:wa(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(rt,{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 mT({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(ma,{size:14}),t.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:A=>s(A.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:c,children:[t.jsx("input",{type:"text",placeholder:"New branch name",value:i,onChange:A=>r(A.target.value),disabled:m}),t.jsxs("select",{value:o,onChange:A=>l(A.target.value),disabled:m,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:"Base: HEAD"}),h.map(A=>t.jsx("option",{value:A.name,children:A.name},A.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:m||!i.trim(),children:[t.jsx(sn,{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(A=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${A.isCurrent?" current":""}${g===A.name?" selected":""}`,onClick:()=>y(A.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[A.isCurrent&&t.jsx($n,{size:14,className:"gm-current-icon"}),A.name]}),A.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",A.remote]}),A.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:wa(A.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!A.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:w=>{w.stopPropagation(),u(A.name)},disabled:m,title:"Checkout",children:t.jsx(Xs,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:w=>{w.stopPropagation(),d(A.name)},disabled:m,title:"Delete",children:t.jsx(nn,{size:14})})]})})]}),g===A.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(Cr,{size:14}),"Commits on ",A.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:k,title:"Close","data-testid":"close-branch-details",children:t.jsx(Kt,{size:14})})]}),f?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(rt,{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(w=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>S(w.hash),"data-testid":`branch-commit-${w.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:w.shortHash}),t.jsx("span",{className:"gm-commit-message",title:w.message,children:w.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:w.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:wa(w.date)}),w.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),x===w.hash&&t.jsx("div",{className:"gm-commit-diff",children:b?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(rt,{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"})})]},w.hash))})]})]},A.name))})]})}function hT({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:ld(n.path)||n.path})]}),t.jsxs("div",{className:"gm-worktree-detail",children:[n.branch&&t.jsxs("span",{className:"gm-worktree-branch",children:[t.jsx(Xs,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function pT({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(rt,{size:14,className:"spin"}):t.jsx(To,{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(Xs,{size:12}),c.branch]}),t.jsx("span",{children:wa(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(rt,{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(rt,{size:14,className:"spin"}):t.jsx(nn,{size:14})})]})]},c.index))})]})}function fT({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:i,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:u}){const d=se=>{try{return new URL(se).hostname}catch{return se.replace(/^git@/,"").split(":")[0]||se}},[m,h]=a.useState([]),[g,p]=a.useState(!1),[f,x]=a.useState(null),[v,b]=a.useState(""),[y,S]=a.useState(""),[k,A]=a.useState(null),[w,E]=a.useState(""),[C,z]=a.useState(""),[_,$]=a.useState(!1),[F,V]=a.useState([]),[D,T]=a.useState(!1),[I,U]=a.useState(null),[Y,ne]=a.useState([]),[N,P]=a.useState(!1),[R,j]=a.useState(null),W=m.find(se=>se.name===I),[K,ke]=a.useState(null),[be,ce]=a.useState(null),[ve,O]=a.useState(!1),[oe,te]=a.useState(null),[pe,de]=a.useState(null),[ge,ie]=a.useState(!1);a.useEffect(()=>{Ee()},[]),a.useEffect(()=>{e&&e.ahead>0?Le():e&&e.ahead===0&&V([])},[e?.ahead]),a.useEffect(()=>{m.length>0&&!I&&U(m[0].name)},[m]),a.useEffect(()=>{I?qe(I):(ne([]),j(null))},[I]),a.useEffect(()=>{I&&!m.find(se=>se.name===I)&&U(m.length>0?m[0].name:null)},[m,I]);const Ee=async()=>{p(!0);try{const se=await py(c);h(se)}catch(se){l(Se(se)||"Failed to load remotes","error")}finally{p(!1)}},Le=async()=>{T(!0);try{const se=await Ny(c);V(se)}catch{V([])}finally{T(!1)}},qe=async se=>{P(!0),j(null);try{const Ae=await Sy(se,void 0,10,c);ne(Ae)}catch(Ae){j(Se(Ae)||"Failed to load remote commits"),ne([])}finally{P(!1)}},et=Bs(),Xe=async se=>{if(se.preventDefault(),!(!v.trim()||!y.trim())){x("add");try{await fy(v.trim(),y.trim(),c),l(`Remote '${v}' added successfully`,"success"),b(""),S(""),$(!1),await Ee()}catch(Ae){l(Se(Ae)||"Failed to add remote","error")}finally{x(null)}}},Ze=async se=>{if(await et.confirm({title:"Remove Remote",message:`Are you sure you want to remove remote '${se}'?`,danger:!0})){x(`remove-${se}`);try{await gy(se,c),l(`Remote '${se}' removed`,"success"),await Ee()}catch(ze){l(Se(ze)||"Failed to remove remote","error")}finally{x(null)}}},it=async se=>{if(C.trim()){x(`rename-${se}`);try{await xy(se,C.trim(),c),l(`Remote renamed to '${C.trim()}'`,"success"),A(null),z(""),await Ee()}catch(Ae){l(Se(Ae)||"Failed to rename remote","error")}finally{x(null)}}},Ie=async se=>{if(w.trim()){x(`url-${se}`);try{await by(se,w.trim(),c),l("Remote URL updated","success"),A(null),E(""),await Ee()}catch(Ae){l(Se(Ae)||"Failed to update remote URL","error")}finally{x(null)}}},Ke=a.useCallback(async(se,Ae)=>{if(Ae==="ahead"){if(K===se){ke(null),ce(null);return}ke(se),ce(null),O(!0);try{const ze=await vo(se);ce(ze)}catch{ce(null)}finally{O(!1)}}else{if(oe===se){te(null),de(null);return}te(se),de(null),ie(!0);try{const ze=await vo(se);de(ze)}catch{de(null)}finally{ie(!1)}}},[K,oe]),re=se=>{A(`url-${se.name}`),E(se.pushUrl||se.fetchUrl)},xe=se=>{A(`name-${se.name}`),z(se.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:()=>$(!_),disabled:f!==null,title:_?"Cancel":"Add Remote",children:_?t.jsx(Kt,{size:14}):t.jsx(sn,{size:14})})]}),_&&t.jsxs("form",{className:"gm-remote-form",onSubmit:Xe,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:v,onChange:se=>b(se.target.value),disabled:f==="add",className:"gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:y,onChange:se=>S(se.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(rt,{size:12,className:"spin"}):t.jsx(sn,{size:12}),"Add"]})]}),g?t.jsxs("div",{className:"gm-loading",children:[t.jsx(rt,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(se=>t.jsxs("div",{className:`gm-remote-selector-item${I===se.name?" selected":""}`,onClick:()=>U(se.name),role:"button",tabIndex:0,children:[t.jsxs("div",{className:"gm-remote-selector-info",children:[t.jsxs("span",{className:"gm-remote-selector-name",children:[se.name,se.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",children:d(se.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:Ae=>{Ae.stopPropagation(),Ze(se.name)},disabled:f!==null,title:"Remove remote",children:t.jsx(nn,{size:14})})]},se.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[I&&W?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(zi,{size:14}),e.ahead," to push"]}),e.behind>0&&t.jsxs("div",{className:"gm-remote-indicator behind",children:[t.jsx(wr,{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(rt,{size:14,className:"spin"}):t.jsx(Mn,{size:14}),"Fetch"]}),t.jsxs("button",{className:"btn btn-primary",onClick:r,disabled:n!==null||g,children:[n==="pull"?t.jsx(rt,{size:14,className:"spin"}):t.jsx(xs,{size:14}),"Pull"]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||g,children:[n==="push"?t.jsx(rt,{size:14,className:"spin"}):t.jsx(zi,{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:w,onChange:se=>E(se.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(rt,{size:12,className:"spin"}):t.jsx($n,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{A(null),E("")},title:"Cancel",children:t.jsx(Kt,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:W.fetchUrl,children:W.fetchUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(W.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(Fi,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>re(W),disabled:f!==null,title:"Edit remote URL",children:t.jsx(ts,{size:14})})]})]}),W.pushUrl&&W.pushUrl!==W.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:W.pushUrl,children:W.pushUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(W.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:se=>z(se.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(rt,{size:12,className:"spin"}):t.jsx($n,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{A(null),z("")},title:"Cancel",children:t.jsx(Kt,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>xe(W),disabled:f!==null,title:"Edit remote name",children:t.jsx(ts,{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(zi,{size:14}),"Commits to Push (",e.ahead,")"]})}),D?t.jsxs("div",{className:"gm-loading",children:[t.jsx(rt,{size:14,className:"spin"}),"Loading..."]}):F.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:F.map(se=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Ke(se.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:se.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:se.message,children:se.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:se.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:wa(se.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:K===se.hash?t.jsx(Yt,{size:14}):t.jsx(bn,{size:14})})]}),K===se.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:ve?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(rt,{size:16,className:"spin"}),"Loading diff..."]}):be?t.jsxs(t.Fragment,{children:[se.message&&t.jsx("div",{className:"gm-commit-message-full",children:se.message}),be.stat&&t.jsx("pre",{className:"gm-diff-stat",children:be.stat}),t.jsx("pre",{className:"gm-diff-patch",children:be.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},se.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(Zh,{size:14}),"Recent commits on ",I]})}),N?t.jsxs("div",{className:"gm-loading",children:[t.jsx(rt,{size:14,className:"spin"}),"Loading commits..."]}):R?t.jsxs("div",{className:"gm-error",children:[t.jsx(ss,{size:14}),R]}):Y.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:Y.map(se=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Ke(se.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:se.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:se.message,children:se.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:se.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:wa(se.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:oe===se.hash?t.jsx(Yt,{size:14}):t.jsx(bn,{size:14})})]}),oe===se.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:ge?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(rt,{size:16,className:"spin"}),"Loading diff..."]}):pe?t.jsxs(t.Fragment,{children:[se.message&&t.jsx("div",{className:"gm-commit-message-full",children:se.message}),pe.stat&&t.jsx("pre",{className:"gm-diff-stat",children:pe.stat}),t.jsx("pre",{className:"gm-diff-patch",children:pe.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},se.hash))})]})]}):t.jsx("div",{className:"gm-empty",children:"Select a remote to view details"}),s&&t.jsx("div",{className:"gm-remote-result",children:s.message})]})]})})}const Za={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function gT(e,n){return e&&n?`${e}/${n}`:""}function xT(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 bT(e){switch(e){case"file-text":return Ui;case"check-circle":return vn;case"shield":return Hb;case"zap":return Fn;case"eye":return fa;case"globe":return $o;case"layout-grid":return Hi;default:return vn}}function vT(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 yT({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(Za),[k,A]=a.useState(!1),[w,E]=a.useState(!1),[C,z]=a.useState(null),[_,$]=a.useState(null),[F,V]=a.useState({}),[D,T]=a.useState([]),I=a.useRef(null);ti(I,e,"fusion:workflow-steps-modal-size");const U=a.useCallback(async()=>{try{d(!0);const O=await Uo(i);o(O)}catch(O){s(Se(O)||"Failed to load workflow steps","error")}finally{d(!1)}},[s,i]),Y=a.useCallback(async()=>{try{const O=await br(i);V(O||{})}catch{}},[i]),ne=a.useCallback(async()=>{try{const O=await ds();T(O.models||[])}catch{}},[]),N=a.useCallback(async()=>{try{h(!0);const O=await jj();c(O.templates)}catch(O){s(Se(O)||"Failed to load templates","error")}finally{h(!1)}},[s]);a.useEffect(()=>{e&&(U(),N(),Y(),ne())},[e,U,N,Y,ne]);const P=a.useCallback(()=>{b(!0),x(null),S(Za)},[]),R=a.useCallback(O=>{x(O.id),b(!1),S({name:O.name,description:O.description,mode:O.mode||"prompt",phase:O.phase||"pre-merge",prompt:O.prompt,scriptName:O.scriptName||"",enabled:O.enabled,defaultOn:O.defaultOn||!1,modelProvider:O.modelProvider||"",modelId:O.modelId||""})},[]),j=a.useCallback(()=>{x(null),b(!1),S(Za)},[]),W=a.useCallback(async()=>{if(!y.name.trim()||!y.description.trim()){s("Name and description are required","error");return}A(!0);try{const O=y.mode==="prompt"&&y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:y.mode==="prompt"?{modelProvider:void 0,modelId:void 0}:{};if(v){const oe={name:y.name.trim(),description:y.description.trim(),mode:y.mode,phase:y.phase,prompt:y.mode==="prompt"&&y.prompt.trim()||void 0,scriptName:y.mode==="script"?y.scriptName.trim():void 0,enabled:y.enabled,defaultOn:y.defaultOn||void 0,...O};await tu(oe,i),s("Workflow step created","success")}else f&&(await bj(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,...O},i),s("Workflow step updated","success"));b(!1),x(null),S(Za),await U()}catch(O){s(Se(O)||"Failed to save workflow step","error")}finally{A(!1)}},[y,v,f,s,U]),K=a.useCallback(async O=>{try{await vj(O,i),s("Workflow step deleted","success"),z(null),f===O&&(x(null),S(Za)),await U()}catch(oe){s(Se(oe)||"Failed to delete workflow step","error")}},[f,s,U]),ke=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}A(!0);try{const O=y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:{},oe={name:y.name.trim(),description:y.description.trim(),mode:"prompt",prompt:y.prompt.trim()||void 0,enabled:y.enabled,defaultOn:y.defaultOn||void 0,...O},te=await tu(oe,i);b(!1),x(te.id),E(!0);const pe=await nu(te.id,i);S(de=>({...de,prompt:pe.prompt})),s("Prompt refined with AI","success"),await U()}catch(O){s(Se(O)||"Failed to refine prompt","error")}finally{A(!1),E(!1)}return}if(f){E(!0);try{const O=await nu(f,i);S(oe=>({...oe,prompt:O.prompt})),s("Prompt refined with AI","success"),await U()}catch(O){s(Se(O)||"Failed to refine prompt","error")}finally{E(!1)}}}},[f,v,y,s,U]),be=a.useCallback(async O=>{$(O.id);try{await kj(O.id,i),s(`Added ${O.name} workflow step`,"success"),await U(),p("my-steps")}catch(oe){const te=Se(oe);te?.includes("already exists")?s(`A workflow step named '${O.name}' already exists`,"error"):s(te||"Failed to add workflow step from template","error")}finally{$(null)}},[s,U]),ce=Si(n);if(!e)return null;const ve=v||f!==null;return t.jsx("div",{className:"modal-overlay open",...ce,"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:[!ve&&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(zg,{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(Hi,{size:14}),"Templates (",l.length,")"]})]}),g==="my-steps"&&!ve&&t.jsxs(t.Fragment,{children:[r.length===0&&t.jsx("div",{className:"wfm-empty","data-testid":"empty-state",children:"No workflow steps defined. Create one to get started, or add one from the Templates tab."}),r.length>0&&t.jsx("div",{className:"wfm-step-list",children:r.map(O=>t.jsx("div",{className:"wfm-step-card","data-testid":`workflow-step-${O.id}`,children:t.jsxs("div",{className:"wfm-step-card-top",children:[t.jsxs("div",{className:"wfm-step-card-info",children:[t.jsxs("div",{className:"wfm-step-card-title-row",children:[t.jsx("span",{className:"wfm-step-card-name",children:O.name}),t.jsx("span",{className:`wfm-badge ${O.enabled?"wfm-badge-enabled":"wfm-badge-disabled"}`,children:O.enabled?"Enabled":"Disabled"}),t.jsx("span",{className:`wfm-badge ${(O.mode||"prompt")==="script"?"wfm-badge-script":"wfm-badge-prompt"}`,children:(O.mode||"prompt")==="script"?"Script":"AI Prompt"}),t.jsx("span",{className:`wfm-badge ${(O.phase||"pre-merge")==="post-merge"?"wfm-badge-post-merge":"wfm-badge-pre-merge"}`,children:(O.phase||"pre-merge")==="post-merge"?"Post-merge":"Pre-merge"}),O.defaultOn&&t.jsx("span",{className:"wfm-badge wfm-badge-default-on",children:"Default on"})]}),t.jsx("div",{className:"wfm-step-card-desc",children:O.description})]}),t.jsxs("div",{className:"wfm-step-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>R(O),title:"Edit","aria-label":`Edit ${O.name}`,children:t.jsx(ts,{size:14})}),C===O.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>K(O.id),title:"Confirm delete","aria-label":`Confirm delete ${O.name}`,children:t.jsx($n,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>z(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(Kt,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>z(O.id),title:"Delete","aria-label":`Delete ${O.name}`,children:t.jsx(nn,{size:14})})]})]})},O.id))})]}),g==="templates"&&!ve&&t.jsx(t.Fragment,{children:m?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(rt,{size:24,className:"spin wfm-spinner"}),"Loading templates..."]}):l.length===0?t.jsx("div",{className:"wfm-empty","data-testid":"no-templates-state",children:"No templates available."}):t.jsx("div",{className:"wfm-template-list",children:l.map(O=>{const oe=bT(O.icon),te=vT(O.category),pe=_===O.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`template-${O.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(oe,{size:20})}),t.jsxs("div",{className:"wfm-template-content",children:[t.jsxs("div",{className:"wfm-template-title-row",children:[t.jsx("span",{className:"wfm-template-name",children:O.name}),t.jsx("span",{className:te,children:O.category})]}),t.jsx("div",{className:"wfm-template-desc",children:O.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>be(O),disabled:pe,"data-testid":`add-template-${O.id}`,children:pe?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(sn,{size:12}),"Add"]})})]})]})},O.id)})})}),ve&&t.jsxs("div",{className:"wfm-form","data-testid":"workflow-step-form",children:[t.jsx("h3",{className:"wfm-form-title",children:v?"New Workflow Step":"Edit Workflow Step"}),t.jsxs("div",{className:"wfm-form-fields",children:[t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Name"}),t.jsx("input",{type:"text",value:y.name,onChange:O=>S(oe=>({...oe,name:O.target.value})),placeholder:"e.g. Documentation Review","data-testid":"workflow-step-name"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{value:y.description,onChange:O=>S(oe=>({...oe,description:O.target.value})),placeholder:"Brief description of what this step does",rows:2,"data-testid":"workflow-step-description"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Mode"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-mode-selector",children:[t.jsxs("button",{className:`btn ${y.mode==="prompt"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>S(O=>({...O,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(ji,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${y.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>S(O=>({...O,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(ci,{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(O=>({...O,phase:"pre-merge"})),"data-testid":"phase-pre-merge",children:"Pre-merge"}),t.jsx("button",{className:`btn ${y.phase==="post-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>S(O=>({...O,phase:"post-merge"})),"data-testid":"phase-post-merge",children:"Post-merge"})]}),t.jsx("div",{className:"wfm-field-hint",children:y.phase==="pre-merge"?"Runs before merge — can block merge on failure":"Runs after merge success — failures are logged but do not block"})]}),y.mode==="prompt"&&t.jsxs("div",{className:"wfm-field",children:[t.jsxs("div",{className:"wfm-prompt-header",children:[t.jsx("label",{children:"Agent Prompt"}),t.jsxs("button",{className:"btn-icon wfm-refine-btn",onClick:ke,disabled:!y.description.trim()||w,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[w?t.jsx(rt,{size:12,className:"spin"}):t.jsx(Qn,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:y.prompt,onChange:O=>S(oe=>({...oe,prompt:O.target.value})),placeholder:"Leave empty to use AI refinement",rows:6,className:"wfm-prompt-textarea","data-testid":"workflow-step-prompt"})]}),y.mode==="prompt"&&t.jsxs("div",{className:"wfm-field","data-testid":"workflow-step-model-field",children:[t.jsxs("div",{className:"wfm-model-header",children:[t.jsx("label",{children:"Model Override"}),y.modelProvider&&y.modelId&&t.jsxs("button",{type:"button",className:"btn-icon wfm-model-clear-btn",onClick:()=>S(O=>({...O,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(Kt,{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(Bn,{models:D,value:gT(y.modelProvider,y.modelId),onChange:O=>{const oe=xT(O);S(te=>({...te,modelProvider:oe.provider,modelId:oe.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:O=>S(oe=>({...oe,scriptName:O.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(F).map(([O,oe])=>t.jsxs("option",{value:O,children:[O," (",oe,")"]},O))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:y.enabled,onChange:O=>S(oe=>({...oe,enabled:O.target.checked})),"data-testid":"workflow-step-enabled"}),"Enabled (available for selection on new tasks)"]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:y.defaultOn,onChange:O=>S(oe=>({...oe,defaultOn:O.target.checked})),"data-testid":"workflow-step-default-on"}),"Default on for new tasks"]}),t.jsxs("div",{className:"wfm-form-actions",children:[t.jsx("button",{className:"btn btn-secondary",onClick:j,disabled:k,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:W,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"})]})]})]})]})}),!ve&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:P,"data-testid":"add-workflow-step",children:[t.jsx(sn,{size:14}),"Add Workflow Step"]})})]})})}const jT=36e5,kT=3e5,lc=[{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 wT(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 NT(e){return typeof e!="number"||!Number.isFinite(e)?jT:Math.max(kT,Math.round(e))}function FD(e){if(lc.some(s=>s.value===e))return[...lc];const n={value:e,label:`${wT(e)} (custom)`};return[...lc,n].sort((s,i)=>s.value-i.value)}const ST=4,CT=5*6e4;function ET(e){const n=NT(e?.heartbeatIntervalMs);return Math.max(n*ST,CT)}function _T(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 MT(e){const{state:n,lastHeartbeatAt:s,lastError:i,pauseReason:r,runtimeConfig:o}=e,l=_T(e),c=l||o?.enabled!==!1;if(n==="terminated")return{label:"Terminated",icon:t.jsx(gs,{size:14}),color:"var(--state-error-text)",stateDerived:!0};if(n==="error")return{label:i??"Error",icon:t.jsx(Rs,{size:14}),color:"var(--state-error-text)",stateDerived:!i};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(Fs,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(Rs,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!c)return{label:"Heartbeat Disabled",icon:t.jsx(Fs,{size:14}),color:"var(--state-paused-text)",stateDerived:!1};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(kn,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const u=new Date(s).getTime(),d=Date.now()-u,m=ET(o);return d>m?{label:"Unresponsive",icon:t.jsx(Rs,{size:14}),color:"var(--state-error-text)",stateDerived:!1}:{label:"Healthy",icon:t.jsx(Gx,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}const er=[{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 AT({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 R=Hn("fn-agent-view",i);return R==="board"||R==="list"?R:"list"});a.useEffect(()=>{const R=Hn("fn-agent-view",i);if(R==="board"||R==="list"){b(R);return}b("list")},[i]),a.useEffect(()=>{ls("fn-agent-view",v,i)},[i,v]);const[y,S]=a.useState(null),k=a.useRef(null),[A,w]=a.useState(new Set),[E,C]=a.useState(new Map),{confirm:z}=Bs(),_=a.useMemo(()=>E.size===0?r:r.map(R=>{const j=E.get(R.id);return j?{...R,state:j}:R}),[r,E]),$=a.useMemo(()=>f==="all"?_.filter(R=>R.state!=="terminated"):_,[_,f]),F=a.useCallback(async()=>{c(!0);try{const j=await Ma(f!=="all"?{state:f}:void 0,i);o(j)}catch(R){s(`Failed to load agents: ${Se(R)}`,"error")}finally{c(!1)}},[f,s,i]);a.useEffect(()=>{e&&F()},[e,F]),a.useEffect(()=>{if(!e)return;const R=setInterval(()=>{F()},3e4);return()=>{clearInterval(R)}},[e,F]);const V=async()=>{if(m.trim())try{await Rj({name:m.trim(),role:g},i),s(`Agent "${m}" created`,"success"),h(""),d(!1),F()}catch(R){s(`Failed to create agent: ${Se(R)}`,"error")}},D=async(R,j)=>{if(!A.has(R)){w(W=>new Set(W).add(R)),C(W=>{const K=new Map(W);return K.set(R,j),K});try{await Pj(R,j,i),s(`Agent state updated to ${j}`,"success"),await F(),C(W=>{const K=new Map(W);return K.delete(R),K})}catch(W){C(K=>{const ke=new Map(K);return ke.delete(R),ke}),s(`Failed to update state: ${Se(W)}`,"error")}finally{w(W=>{const K=new Set(W);return K.delete(R),K})}}},T=async(R,j)=>{if(await z({title:"Delete Agent",message:`Delete agent "${j}"? This cannot be undone.`,danger:!0}))try{await Ij(R,i),s(`Agent "${j}" deleted`,"success"),F()}catch(K){s(`Failed to delete agent: ${Se(K)}`,"error")}},I=async(R,j)=>{const W=r.find(K=>K.id===R);if(W){if(W.role===j){S(null);return}try{await Tj(R,{role:j},i),s(`Agent role updated to ${er.find(K=>K.value===j)?.label??j}`,"success"),S(null),F()}catch(K){s(`Failed to update role: ${Se(K)}`,"error")}}},U=(R,j)=>{R.key==="Escape"&&S(null)},Y=R=>er.find(j=>j.value===R)?.label??R,ne=R=>er.find(j=>j.value===R)?.icon??"◆",N=R=>MT(R),P=R=>R.color==="var(--state-active-text)"?"active":R.color==="var(--state-paused-text)"?"paused":R.color==="var(--state-error-text)"?"error":"muted";return e?t.jsx("div",{className:"modal-overlay open",onClick:R=>R.target===R.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(kn,{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(Hi,{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(wc,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void F(),title:"Refresh",disabled:l,children:t.jsx(Mn,{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(go,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:f,onChange:R=>x(R.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(sn,{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:R=>h(R.target.value),onKeyDown:R=>R.key==="Enter"&&V(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:g,onChange:R=>p(R.target.value),children:er.map(R=>t.jsxs("option",{value:R.value,children:[R.icon," ",R.label]},R.value))}),t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:()=>void V(),children:"Create"})]}),t.jsx("div",{className:v==="board"?"agent-board":"agent-list",children:$.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(kn,{size:48,opacity:.3}),t.jsx("p",{children:"No agents found"}),t.jsx("p",{className:"text-secondary",children:"Create an agent to get started"})]}):v==="board"?$.map(R=>{const j=N(R),W=P(j);return t.jsxs("div",{className:"agent-board-card","data-state":R.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:ne(R.role)}),t.jsx("span",{className:"agent-board-badge","data-state":R.state,children:R.state}),t.jsx("span",{className:"agent-board-health","data-health":W,title:j.label,children:j.icon})]}),t.jsx("div",{className:"agent-board-name",title:R.name,children:R.name}),t.jsx("div",{className:"agent-board-id",children:R.id}),t.jsxs("div",{className:"agent-board-actions",children:[R.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void D(R.id,"active"),disabled:A.has(R.id),title:"Activate",children:t.jsx(wn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void T(R.id,R.name),title:"Delete",children:t.jsx(nn,{size:14})})]}),R.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void D(R.id,"paused"),disabled:A.has(R.id),title:"Pause",children:t.jsx(Fs,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void D(R.id,"terminated"),disabled:A.has(R.id),title:"Stop",children:t.jsx(gs,{size:14})})]}),R.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void D(R.id,"active"),disabled:A.has(R.id),title:"Resume",children:t.jsx(wn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void D(R.id,"terminated"),disabled:A.has(R.id),title:"Stop",children:t.jsx(gs,{size:14})})]}),R.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void D(R.id,"paused"),disabled:A.has(R.id),title:"Pause",children:t.jsx(Fs,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void D(R.id,"terminated"),disabled:A.has(R.id),title:"Stop",children:t.jsx(gs,{size:14})})]}),R.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void D(R.id,"active"),disabled:A.has(R.id),title:"Retry",children:t.jsx(wn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void D(R.id,"terminated"),disabled:A.has(R.id),title:"Stop",children:t.jsx(gs,{size:14})})]}),R.state==="terminated"&&t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void T(R.id,R.name),title:"Delete",children:t.jsx(nn,{size:14})})]})]},R.id)}):$.map(R=>{const j=N(R),W=P(j);return t.jsxs("div",{className:"agent-card","data-state":R.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[y===R.id?t.jsx("select",{ref:k,className:"select agent-role-select",value:R.role,onChange:K=>void I(R.id,K.target.value),onKeyDown:K=>U(K,R.id),onBlur:()=>S(null),autoFocus:!0,children:er.map(K=>t.jsxs("option",{value:K.value,children:[K.icon," ",K.label]},K.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>S(R.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&S(R.id)},children:ne(R.role)}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:R.name}),t.jsx("span",{className:"agent-id text-secondary",children:R.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":R.state,children:R.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":W,title:j.label,children:[j.icon,!j.stateDerived&&` ${j.label}`]}),t.jsx("span",{className:"badge text-secondary",children:Y(R.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[R.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:R.taskId})]}),R.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date(R.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[R.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void D(R.id,"active"),disabled:A.has(R.id),title:"Activate",children:[t.jsx(wn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void T(R.id,R.name),title:"Delete",children:[t.jsx(nn,{size:14})," Delete"]})]}),R.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void D(R.id,"paused"),disabled:A.has(R.id),title:"Pause",children:[t.jsx(Fs,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void D(R.id,"terminated"),disabled:A.has(R.id),title:"Stop",children:[t.jsx(gs,{size:14})," Stop"]})]}),R.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void D(R.id,"active"),disabled:A.has(R.id),title:"Resume",children:[t.jsx(wn,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void D(R.id,"terminated"),disabled:A.has(R.id),title:"Stop",children:[t.jsx(gs,{size:14})," Stop"]})]}),R.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void D(R.id,"paused"),disabled:A.has(R.id),title:"Pause",children:[t.jsx(Fs,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void D(R.id,"terminated"),disabled:A.has(R.id),title:"Stop",children:[t.jsx(gs,{size:14})," Stop"]})]}),R.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void D(R.id,"active"),disabled:A.has(R.id),title:"Retry",children:[t.jsx(wn,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void D(R.id,"terminated"),disabled:A.has(R.id),title:"Stop",children:[t.jsx(gs,{size:14})," Stop"]})]}),R.state==="terminated"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm btn-task-create",onClick:()=>void D(R.id,"active"),disabled:A.has(R.id),title:"Start",children:[t.jsx(wn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void T(R.id,R.name),title:"Delete",children:[t.jsx(nn,{size:14})," Delete"]})]})]})]},R.id)})})]})]})}):null}function RT({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 sy();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 iy(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(rt,{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(Dn,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(TT,{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(jh,{status:i,authenticated:e}),c&&t.jsx(kh,{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(Dn,{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(jh,{status:i,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(kh,{action:c})]})}function TT({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 jh({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(rt,{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 kh({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 PT(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 cc({instructions:e,"data-testid":n}){const[s,i]=a.useState(!1),r=PT(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($n,{size:12}):t.jsx(Fi,{size:12})})]})]},d))}):e})}const Wi="fusion_model_onboarding_state",Na=[],Sa=[],Ao=!1,Ro=!1,Ca={},IT=void 0,yi=["ai-setup","github","project-setup","first-task"],$T={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function ys(){if(typeof window>"u")return null;try{const e=localStorage.getItem(Wi);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?DT(n):null}catch{return null}}function DT(e){const n=e.postOnboardingDismissedAt??IT;return{...e,completedSteps:e.completedSteps??Na,skippedSteps:e.skippedSteps??Sa,dismissed:e.dismissed??Ao,completed:e.completed??Ro,stepData:e.stepData??Ca,...n?{postOnboardingDismissedAt:n}:{}}}function lo(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:Na,skippedSteps:Sa,dismissed:Ao,completed:Ro,stepData:Ca};try{localStorage.setItem(Wi,JSON.stringify(s))}catch{}return}try{const s=ys(),i=new Date().toISOString(),r=n.completed??Ro;let o=n.dismissed??Ao;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??Na,c=n.skippedSteps??s?.skippedSteps??Sa,u={...s?.stepData??Ca};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(Wi,JSON.stringify(d))}catch{}}}function LT(e){if(!(typeof window>"u"))try{const n=ys(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:Na,skippedSteps:[e],dismissed:Ao,completed:Ro,stepData:Ca};localStorage.setItem(Wi,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(Wi,JSON.stringify(r))}catch{}}function wh(){if(!(typeof window>"u"))try{const e=ys(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:Na,skippedSteps:Sa,dismissed:!1,completed:!0,stepData:Ca};localStorage.setItem(Wi,JSON.stringify(s))}catch{}}function Ea(){const e=ys();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function zT(){if(!(typeof window>"u"))try{const e=ys(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:Na,skippedSteps:Sa,dismissed:!1,completed:!1,stepData:Ca,postOnboardingDismissedAt:n};localStorage.setItem(Wi,JSON.stringify(s))}catch{}}function dg(){const e=ys();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function OT(){const e=ys();return!e||Ea()?!1:e.currentStep!=="complete"}function FT(){const e=ys();if(!e||Ea()||e.currentStep==="complete")return null;const n=e.currentStep,s=$T[n]??HT(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function UT(){const e=ys();return e?e.skippedSteps:Sa}function BT(e){const n=ys();return!n||!n.stepData?null:n.stepData[e]??null}function HT(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const ug="fusion_onboarding_events",Nh="fusion_onboarding_session_id",qT=200,VT=50;function _s(e,n={}){if(!(typeof window>"u"))try{const s=KT(),i=YT(n.step),r={type:e,timestamp:new Date().toISOString(),...i?{step:i}:{},metadata:n,sessionId:WT()},o=JT([...s,r]);GT(o)}catch{}}function WT(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(Nh);if(e)return e;const n=Sh();return sessionStorage.setItem(Nh,n),n}catch{return Sh()}}function Sh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function KT(){try{const e=localStorage.getItem(ug);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(QT):[]}catch{return[]}}function GT(e){try{localStorage.setItem(ug,JSON.stringify(e))}catch{}}function JT(e){const n=[...e];for(;n.length>qT;)n.splice(0,VT);return n}function YT(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function QT(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 XT={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"}}},mg={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:"..."}},ZT={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},Ch={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 Jc(e){if(Ch[e])return Ch[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 dc=["anthropic","openai","google","gemini","ollama"],e4=["anthropic","claude-cli","openai-codex","gemini","minimax","kimi","zai"],t4={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"},n4={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function Yc(e){return t4[e]??e}function Eh(e){const n=Yc(e),s=e4.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function _h(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=Eh(e.id),i=Eh(n.id);if(s!==i)return s-i;const r=Yc(e.id),o=Yc(n.id);if(r!==o)return r.localeCompare(o);const l=n4[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 s4(e,n){const s=n.trim();if(!s)return"API key is required";const i=mg[e]??ZT;return i.pattern.test(s)?null:`${Jc(e)} keys should follow this format: ${i.hint} (e.g. ${i.example})`}const hg={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"},i4={description:"AI provider — connect to start using AI models",apiKeyInfo:hg};function Qc(e){return XT[e]??i4}function a4(e){return Qc(e.id).apiKeyInfo??hg}function Ys({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(bn,{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 r4({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 o4({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=mg[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(Ys,{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(Ys,{summary:"Advanced setup details",children:f})]})}const l4=150;function c4({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:i,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const u=ys(),d=u?.currentStep,m=d==="complete"?"ai-setup":yi.includes(d)?d:"ai-setup",h=u?.completedSteps??[],g=u?.skippedSteps??UT(),[p,f]=a.useState(!0),[x,v]=a.useState(m),[b,y]=a.useState(h),[S,k]=a.useState(g),[A,w]=a.useState(!1),[E,C]=a.useState(""),[z,_]=a.useState(!1),[$,F]=a.useState(null),[V,D]=a.useState(null),[T,I]=a.useState([]),[U,Y]=a.useState(void 0),[ne,N]=a.useState(!0),[P,R]=a.useState(null),[j,W]=a.useState({}),[K,ke]=a.useState([]),[be,ce]=a.useState(""),[ve,O]=a.useState(!1),[oe,te]=a.useState({}),[pe,de]=a.useState({}),[ge,ie]=a.useState({}),Ee=a.useRef({}),Le=a.useRef(null),qe=a.useRef(null),et=a.useRef(null),[Xe,Ze]=a.useState({}),[it,Ie]=a.useState(()=>ys()?.stepData?.github?.skipped===!0),Ke=a.useRef(0),re=a.useRef(l),xe=a.useRef(!1),se=u?.currentStep,Ae=!!u&&u.currentStep!=="complete";ti(qe,p,"fusion:model-onboarding-modal-size"),a.useEffect(()=>{const J=Le.current;J&&(J.scrollTop=0)},[x]);const[ze,me]=a.useState(()=>ys()?.stepData?.["ai-setup"]?.skippedProviders??{}),_e=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],Fe=_e.findIndex(J=>J.key===x),nt=x==="complete"?_e.length:Fe;a.useEffect(()=>{x!=="complete"&&lo(x,{completedSteps:b,skippedSteps:S})},[x,b,S]),a.useEffect(()=>{xe.current||(xe.current=!0,_s("onboarding:wizard-opened",{source:Ae?"resume":"initial",resumedFromStep:se}))},[Ae,se]),a.useEffect(()=>{const J=re.current!=null,Pe=l!=null;!J&&Pe&&w(!0),Pe||w(!1),re.current=l},[l]);const we=a.useRef(m);a.useEffect(()=>{if(we.current==="ai-setup"&&x!=="ai-setup"&&!T.some(Pe=>Pe.id!=="github"&&Pe.authenticated)){const Pe={};for(const Qe of T)Qe.id!=="github"&&!Qe.authenticated&&!ze[Qe.id]&&(Pe[Qe.id]=!0);if(Object.keys(Pe).length>0){const Qe={...ze,...Pe};me(Qe),lo(x,{stepData:{"ai-setup":{skippedProviders:Qe}}})}}we.current=x},[x,T,ze]);const le=a.useCallback(async()=>{try{const{providers:J,ghCli:Pe}=await xr();I(J),Y(Pe),W(Qe=>{const tt={};for(const[mt,St]of Object.entries(Qe)){const zt=J.find(Sn=>Sn.id===mt);zt&&!zt.authenticated&&(tt[mt]=St)}return Object.keys(tt).length===Object.keys(Qe).length?Qe:tt}),me(Qe=>{const tt={...Qe};for(const mt of J)mt.authenticated&&tt[mt.id]&&delete tt[mt.id];return Object.keys(tt).length===Object.keys(Qe).length?Qe:tt})}catch{}},[]),Te=a.useRef(!1);a.useEffect(()=>{Te.current&&le(),Te.current=x!=="ai-setup"},[x,le]);const he=T.find(J=>J.id==="github"),Me=!!he,We=he?.authenticated??!1,Re=U?.authenticated??!1,ut=We||Re,Q=!We&&Re,ue=a.useCallback(J=>{if(J.authenticated)return"connected";const Pe=Xe?.[J.id];return Pe==="timeout"||Pe==="failed"?"retry":ze[J.id]?"skipped":"not-connected"},[Xe,ze]);function ye({status:J}){const Pe={connected:{text:"✓ Connected",className:"auth-status-badge connected"},"not-connected":{text:"Not connected",className:"auth-status-badge not-connected"},skipped:{text:"Skipped",className:"auth-status-badge skipped"},retry:{text:"Retry",className:"auth-status-badge retry"}},{text:Qe,className:tt}=Pe[J];return t.jsx("span",{"data-testid":"provider-status-badge",className:tt,"data-status":J,children:Qe})}const at=a.useCallback(()=>{if(ut)return"connected";const J=Xe.github;return J==="pending"?"pending":J==="failed"||J==="timeout"?"failed":it?"skipped":"not-connected"},[ut,Xe,it]);function X({status:J}){const Pe={connected:{text:"✓ Connected",className:"auth-status-badge connected"},pending:{text:"⏳ Connecting…",className:"auth-status-badge pending"},failed:{text:"✗ Connection failed",className:"auth-status-badge retry"},skipped:{text:"Skipped",className:"auth-status-badge skipped"},"not-connected":{text:"Not connected",className:"auth-status-badge not-connected"}},{text:Qe,className:tt}=Pe[J];return t.jsx("span",{"data-testid":"github-status-badge",className:tt,"data-status":J,children:Qe})}const Ye=a.useCallback(async()=>{try{const J=await ds();ke(J.models)}catch{}},[]),ot=a.useCallback(async()=>{try{const J=await Ki();if(J.defaultProvider&&J.defaultModelId){const Pe=`${J.defaultProvider}/${J.defaultModelId}`;ce(Pe)}}catch{}},[]);a.useEffect(()=>{Promise.all([le(),Ye(),ot()]).finally(()=>N(!1))},[le,Ye,ot]),a.useEffect(()=>{const J=BT("ai-setup");if(J?.loginOutcomes){const Pe=J.loginOutcomes,Qe={};for(const[tt,mt]of Object.entries(Pe))mt!=="pending"&&(Qe[tt]=mt);Object.keys(Qe).length>0&&Ze(Qe)}},[]);const ht=a.useCallback((J,Pe)=>{lo(x,{completedSteps:b,stepData:{"ai-setup":{loginOutcomes:{[J]:Pe}}}})},[x,b]);a.useEffect(()=>{const J=Object.entries(Xe).filter(([Pe,Qe])=>Qe!=="pending");for(const[Pe,Qe]of J)ht(Pe,Qe)},[Xe,ht]),a.useEffect(()=>()=>{et.current&&clearInterval(et.current),Object.values(Ee.current).forEach(clearTimeout),Ee.current={}},[]);const yt=a.useCallback(J=>{Ie(J),lo(x,{completedSteps:b,stepData:{github:{skipped:J}}})},[x,b]),vt=a.useCallback(J=>J==="complete"?-1:yi.indexOf(J),[]),pt=a.useCallback(()=>{y(Pe=>[...new Set([...Pe,x])]),k(Pe=>Pe.filter(Qe=>Qe!==x)),_s("onboarding:step-completed",{step:x}),x==="github"&&!We&&yt(!1);const J=vt(x);J>=0&&J<yi.length-1&&v(yi[J+1])},[x,We,yt,vt]),Et=a.useCallback(()=>{k(Pe=>[...new Set([...Pe,x])]),LT(x),_s("onboarding:step-skipped",{step:x}),x==="github"&&!We&&yt(!0);const J=vt(x);J>=0&&J<yi.length-1&&v(yi[J+1])},[x,We,yt,vt]),It=a.useCallback(()=>{const J=x;y(Qe=>Qe.filter(tt=>tt!==J)),k(Qe=>Qe.filter(tt=>tt!==J)),J==="github"&&!We&&yt(!1);const Pe=vt(x);Pe>0&&v(yi[Pe-1])},[x,We,yt,vt]),Bt=a.useCallback(()=>{Et()},[Et]),_t=a.useCallback(async J=>{Ze(Pe=>{const Qe=Pe[J];if(Qe&&Qe!=="pending"){const{[J]:tt,...mt}=Pe;return mt}return Pe}),W(Pe=>{if(!(J in Pe))return Pe;const Qe={...Pe};return delete Qe[J],Qe}),Ze(Pe=>({...Pe,[J]:"pending"})),R(J),Ke.current=0;try{const{url:Pe,instructions:Qe}=await ay(J);Qe?.trim()&&W(tt=>({...tt,[J]:Qe})),window.open(ei(Pe),"_blank"),et.current=setInterval(async()=>{if(Ke.current++,Ke.current>=l4){et.current&&(clearInterval(et.current),et.current=null),R(null),Ze(tt=>({...tt,[J]:"timeout"})),W(tt=>{if(!(J in tt))return tt;const mt={...tt};return delete mt[J],mt}),n("Login timed out. Please try again.","warning");return}try{const{providers:tt,ghCli:mt}=await xr();I(tt),Y(mt),tt.find(zt=>zt.id===J)?.authenticated&&(et.current&&(clearInterval(et.current),et.current=null),R(null),Ze(zt=>({...zt,[J]:"success"})),W(zt=>{if(!(J in zt))return zt;const Sn={...zt};return delete Sn[J],Sn}),J==="github"&&yt(!1),n("Login successful","success"))}catch{}},2e3)}catch(Pe){Pe instanceof Error&&Pe.message.includes("already in progress")||Pe&&typeof Pe=="object"&&"status"in Pe&&Pe.status===409?(n("Login already in progress. Please wait or cancel the current attempt.","warning"),Ze(tt=>({...tt,[J]:"failed"}))):(n(Pe instanceof Error?Pe.message:"Login failed","error"),Ze(tt=>({...tt,[J]:"failed"}))),R(null),W(tt=>{if(!(J in tt))return tt;const mt={...tt};return delete mt[J],mt})}},[n,yt]),Pt=a.useCallback(J=>{et.current&&(clearInterval(et.current),et.current=null),R(null),Ke.current=0,Ze(Pe=>({...Pe,[J]:"cancelled"})),W(Pe=>{if(!(J in Pe))return Pe;const Qe={...Pe};return delete Qe[J],Qe})},[]),$t=a.useCallback((J,Pe)=>{te(tt=>({...tt,[J]:Pe}));const Qe=Ee.current[J];Qe&&(clearTimeout(Qe),delete Ee.current[J]),de(tt=>{if(!tt[J])return tt;const mt={...tt};return delete mt[J],mt}),ie(tt=>{if(!tt[J])return tt;const mt={...tt};return delete mt[J],mt})},[]),Ht=a.useCallback(()=>{const J=Le.current;if(!J)return;const Pe=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof J.scrollTo=="function"){J.scrollTo({top:0,behavior:Pe?"auto":"smooth"});return}}catch{}J.scrollTop=0},[]),Gt=a.useCallback(async(J,Pe)=>{const Qe=(Pe??oe[J]??"").trim(),tt=s4(J,Qe);if(tt){de(St=>({...St,[J]:tt}));return}const mt=Ee.current[J];mt&&(clearTimeout(mt),delete Ee.current[J]),R(J),de(St=>{const zt={...St};return delete zt[J],zt}),ie(St=>{if(!St[J])return St;const zt={...St};return delete zt[J],zt});try{await oy(J,Qe),await le(),Ht(),te(St=>{const zt={...St};return delete zt[J],zt}),de(St=>{if(!St[J])return St;const zt={...St};return delete zt[J],zt}),ie(St=>({...St,[J]:"✓ Key saved"})),Ee.current[J]=setTimeout(()=>{ie(St=>{if(!St[J])return St;const zt={...St};return delete zt[J],zt}),delete Ee.current[J]},3e3),n("API key saved","success")}catch(St){const zt=St instanceof TypeError&&St.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":St instanceof Error?St.message:"Failed to save API key";de(Sn=>({...Sn,[J]:zt})),ie(Sn=>{if(!Sn[J])return Sn;const an={...Sn};return delete an[J],an}),n(zt,"error")}finally{R(null)}},[oe,n,le,Ht]),Dt=a.useCallback(async J=>{R(J);try{await ly(J),await le(),n("API key removed","success")}catch(Pe){n(Pe instanceof Error?Pe.message:"Failed to clear API key","error")}finally{R(null)}},[n,le]),Tt=a.useCallback(async J=>{R(J);try{await ry(J),await le(),n("Logged out","success")}catch(Pe){n(Pe instanceof Error?Pe.message:"Logout failed","error")}finally{R(null)}},[n,le]),jt=a.useCallback(J=>{ce(J)},[]),Mt=a.useCallback(async()=>{try{const J={modelOnboardingComplete:!0};if(be){const Pe=be.indexOf("/"),Qe=Pe!==-1?be.slice(0,Pe):void 0,tt=Pe!==-1?be.slice(Pe+1):be,mt=K.find(St=>St.id===tt);mt?(J.defaultProvider=mt.provider,J.defaultModelId=mt.id):Qe&&tt&&(J.defaultProvider=Qe,J.defaultModelId=tt)}await cn(J),wh()}catch{}},[be,K,cn,wh]),Zt=a.useCallback(async()=>{const J=[...new Set([...b,"first-task"])];O(!0);try{await Mt(),_s("onboarding:completed",{completedSteps:J,skippedSteps:S}),y(J),k(Pe=>Pe.filter(Qe=>Qe!=="first-task")),v("complete")}finally{O(!1)}},[Mt,b,S]),At=a.useCallback(async()=>{if(!s)return;const J=E.trim();if(!J){F("Please enter a task description.");return}F(null),_(!0);let Pe=!1;try{const Qe=await ap({description:J},s);D(Qe),w(!0),_s("onboarding:first-task-created",{taskId:Qe?.id}),n("Task created","success"),Pe=!0}catch(Qe){const tt=Qe instanceof Error?Qe.message:"Something went wrong creating your task. Please try again.";F(tt),n(tt,"error")}finally{_(!1)}Pe&&Mt()},[s,E,n,Mt]),H=a.useCallback(async()=>{O(!0);try{await Mt()}finally{O(!1)}_s("onboarding:open-new-task",{}),r?.()},[Mt,r]),fe=a.useCallback(async()=>{if(ut){O(!0);try{await Mt()}finally{O(!1)}f(!1),e(),_s("onboarding:open-github-import",{}),o?.()}},[Mt,ut,e,o]),$e=a.useCallback(async()=>{_s("onboarding:dismissed",{currentStep:x,completedSteps:b,skippedSteps:S}),O(!0);try{await cn({modelOnboardingComplete:!0})}catch{}f(!1),e()},[x,b,S,e]),M=a.useCallback(()=>{_s("onboarding:finished",{}),f(!1),e()},[e]),ee=a.useCallback(()=>{const J=l??V;J&&(Mt(),c?.(J),e())},[l,V,Mt,c,e]),Oe=a.useCallback(()=>{Mt(),e()},[Mt,e]);if(!p)return null;const dt=at(),Nt=T.filter(J=>J.id!=="github"),Ct=[...Nt].sort(_h),Rt=Ct.some(J=>!J.type||J.type==="oauth"),un=Ct.some(J=>J.type==="api_key"),mn=Nt.filter(J=>J.authenticated),Nn=mn.length>0,Qt=!!s,An=x==="github"&&!Nn,Ne=(()=>{if(!be)return"";const J=be.indexOf("/"),Pe=J===-1?void 0:be.slice(0,J),Qe=J===-1?be:be.slice(J+1),tt=K.find(mt=>mt.id===Qe&&(!Pe||mt.provider===Pe));return tt?.name?tt.name:Pe?`${Jc(Pe)} ${Qe}`:be})(),ae=[];if(Qt?ae.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):ae.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),Nn){const J=Jc(mn[0]?.id??"");ae.push({label:"AI Provider",status:"connected",detail:`${J} connected — AI agents can work on tasks`})}else Nt.length>0&&Nt.some(J=>ze[J.id])?ae.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):ae.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});ut?ae.push({label:"GitHub",status:"connected",detail:Q?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!Me||it?ae.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):ae.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),Ne&&ae.push({label:"Default Model",status:"connected",detail:Ne});const Ge=l??V,ct=Ge?.description?.split(`
|
|
656
|
-
`)[0]?.trim()||Ge?.title||"",Lt=new Set(dc),qt=Ct.filter(J=>Lt.has(J.id)).sort((J,Pe)=>{const Qe=dc.indexOf(J.id),tt=dc.indexOf(Pe.id);return Qe!==tt?Qe-tt:_h(J,Pe)}),En=Ct.filter(J=>J.authenticated&&!Lt.has(J.id)),hn=Ct.filter(J=>!J.authenticated&&!Lt.has(J.id)),Vt=J=>{if(J.id==="claude-cli"&&J.type==="cli")return t.jsx(RT,{authenticated:J.authenticated,onToggled:()=>{le()}},J.id);if(J.type==="api_key"){const Pe=Qc(J.id),Qe=a4(J);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${J.id}`,className:`onboarding-provider-card${J.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${J.id}`,"aria-hidden":"true",children:t.jsx(Dn,{provider:J.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(Qh,{size:14,className:"onboarding-provider-key-icon"}),J.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:Pe.description}),t.jsx(ye,{status:ue(J)}),J.authenticated&&J.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",J.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(o4,{provider:J,apiKeyInfo:Qe,inputValue:oe[J.id]??"",isSaving:P===J.id,error:pe[J.id],success:ge[J.id],isConnected:J.authenticated,onInputChange:$t,onSave:Gt,onClear:Dt})})]},J.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${J.id}`,className:`onboarding-provider-card${J.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${J.id}`,"aria-hidden":"true",children:t.jsx(Dn,{provider:J.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:J.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:Qc(J.id).description}),t.jsx(ye,{status:ue(J)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:P===J.id?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:J.authenticated?"Logging out…":"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Pt(J.id),children:"Cancel"})]}):J.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>Tt(J.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>_t(J.id),children:"Login"})}),P===J.id&&j[J.id]&&t.jsx(cc,{instructions:j[J.id],"data-testid":`onboarding-login-instructions-${J.id}`}),Xe[J.id]==="timeout"&&P!==J.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),Xe[J.id]==="failed"&&P!==J.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},J.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:qe,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(Fn,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(xs,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(zd,{size:24})," Set Up Your Project"]}),x==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(zd,{size:24})," Create Your First Task"]}),x==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(vn,{size:24})," All Set!"]})]}),x!=="complete"&&t.jsx("button",{className:"modal-close",onClick:$e,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(Kt,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:_e.map((J,Pe)=>{const Qe=nt>Pe,tt=b.includes(J.key)&&Qe,mt=S.includes(J.key)&&!b.includes(J.key)&&Qe,St=tt||mt;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[Pe>0&&t.jsx("div",{className:`model-onboarding-step-connector ${Pe<=nt?"done":""}`}),St?t.jsxs("button",{className:`model-onboarding-step-indicator ${x===J.key?"active":""} ${tt?"done":""} ${mt?"skipped":""}`,onClick:()=>v(J.key),"aria-label":`Go back to ${J.label}`,title:`Review ${J.label}`,children:[t.jsx("span",{className:"step-number",children:tt?t.jsx(vn,{size:14}):mt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Pe+1}),t.jsx("span",{className:"step-label",children:J.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${x===J.key?"active":""} ${tt?"done":""} ${mt?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:tt?t.jsx(vn,{size:14}):mt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Pe+1}),t.jsx("span",{className:"step-label",children:J.label})]})]},J.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:Le,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."}),!ne&&T.length>0&&(()=>{const J=T.filter(St=>St.id!=="github"&&St.authenticated).length,Pe=T.filter(St=>St.id!=="github").length,Qe=Object.keys(ze).filter(St=>!T.find(zt=>zt.id===St)?.authenticated).length;if(Pe===0)return null;let tt="onboarding-provider-summary",mt="";return J>0?(tt+=" onboarding-provider-summary--connected",mt=`✓ ${J} of ${Pe} provider${Pe!==1?"s":""} connected`):Qe>0?(tt+=" onboarding-provider-summary--skipped",mt=`${Qe} provider${Qe!==1?"s":""} skipped`):(tt+=" onboarding-provider-summary--none",mt="No providers connected yet"),t.jsx("div",{className:tt,"data-testid":"provider-summary",children:mt})})(),t.jsx(Ys,{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."})}),T.length>0&&!T.some(J=>J.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),ne?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(rt,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):T.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"}),qt.length>0?t.jsx("div",{className:"model-onboarding-providers",children:qt.map(J=>Vt(J))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),En.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:En.map(J=>Vt(J))})]}),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(Ys,{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."})}),K.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(Bn,{models:K,value:be,onChange:jt,placeholder:"Select a default model…",label:"Default model"})}),be&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",K.find(J=>J.id===be)?.name??be]})})]}),t.jsx(Ys,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsx("div",{"data-testid":"onboarding-advanced-provider-settings",children:hn.length>0?t.jsx("div",{className:"model-onboarding-providers",children:hn.map(J=>Vt(J))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."})})}),Rt&&t.jsx(Ys,{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(Ys,{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:[ut?t.jsx("p",{className:"model-onboarding-description",children:Q?"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."}),!ut&&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"})]})}),An&&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(Ys,{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."})}),Me?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(xs,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(X,{status:dt})})]}),We&&(P==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>Tt("github"),children:"Disconnect"}))]}),(dt==="not-connected"||dt==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[P==="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:()=>Pt("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>_t("github"),children:[t.jsx(xs,{size:16}),"Connect"]}),P==="github"&&j.github&&t.jsx(cc,{instructions:j.github,"data-testid":"onboarding-login-instructions-github"})]}),dt==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:Q?"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."}),dt==="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:()=>_t("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Bt,children:"Skip for now"})]})]}),dt==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),dt==="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:()=>_t("github"),children:"Connect anyway"})})]}),dt==="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(Dn,{provider:"github",size:"lg"})}),Q?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:Q?"Continue with gh CLI auth →":"Continue without GitHub →"}),Q&&(P==="github"?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(rt,{size:14,className:"onboarding-spinner"}),"Waiting for OAuth login…"]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>_t("github"),children:[t.jsx(Dn,{provider:"github",size:"sm"}),"Connect OAuth (optional)"]}))]}),Q&&P==="github"&&j.github&&t.jsx(cc,{instructions:j.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."}),Qt?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(Ys,{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."}),A&&Ge?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(vn,{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:Ge.id}),ct&&t.jsx("p",{className:"onboarding-task-created__description",children:ct}),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:ee,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:Oe,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[Qt?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:E,onChange:J=>{C(J.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:At,disabled:z,"data-testid":"onboarding-first-task-submit",children:z?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),$&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:$}),t.jsx("p",{className:"onboarding-helper-text",children:"Your text has been preserved — fix the issue and try again."})]})]}):t.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[t.jsx("p",{className:"onboarding-helper-text",children:"A project must be selected before you can create tasks or import from GitHub."}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:i,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"})]}),t.jsx(r4,{items:ae}),Qt&&t.jsxs(t.Fragment,{children:[t.jsx(Ys,{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:H,disabled:ve,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(sn,{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${ut?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:fe,disabled:ve||!ut,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(xs,{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"}),!ut&&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(vn,{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:$e,disabled:ve,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Et,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:pt,children:"Next →"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:It,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Et,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:pt,children:"Next →"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:It,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:pt,disabled:!Qt,children:"Next →"})]}),x==="first-task"&&!A&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:It,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:Zt,disabled:ve,children:ve?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),x==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:M,children:[t.jsx(vn,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function pg({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 d4=a.lazy(()=>ln(()=>import("./SetupWizardModal-DVoRhy_V.js"),__vite__mapDeps([6,1,7,8,9,0,2,10])).then(e=>({default:e.SetupWizardModal}))),u4=a.lazy(()=>ln(()=>import("./SettingsModal-2s-L1oWD.js"),__vite__mapDeps([11,1,12,13,14,15,0,2,16])).then(e=>({default:e.SettingsModal})));function m4(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{ln(()=>import("./SettingsModal-2s-L1oWD.js"),__vite__mapDeps([11,1,12,13,14,15,0,2,16]))},{timeout:1500})}function h4({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 E=n.find(C=>C.id===c.detailTask?.id);return E?"prompt"in c.detailTask?{...c.detailTask,...E,prompt:c.detailTask.prompt,log:c.detailTask.log}:E:c.detailTask})():null,y=p??c.closeSettings,S=a.useCallback(()=>{c.openNewTask()},[c]),k=a.useCallback(()=>{c.openGitHubImport()},[c]),A=a.useCallback(E=>{v(null),c.closeModelOnboarding(),c.openDetailTask(E)},[c]),w=a.useCallback(async E=>{const C=await d.handleModalCreate(E);return c.modelOnboardingOpen&&v(C),C},[d.handleModalCreate,c.modelOnboardingOpen]);return a.useEffect(()=>{!c.modelOnboardingOpen&&x&&v(null)},[c.modelOnboardingOpen,x]),a.useEffect(()=>{m4()},[]),t.jsxs(t.Fragment,{children:[b&&t.jsx(Pi,{children:t.jsx(uA,{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(Pi,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(u4,{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(hA,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:d.handleGitHubImport,tasks:n,projectId:e}),t.jsx(Pi,{children:t.jsx(xA,{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(Pi,{children:t.jsx(EA,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:d.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(GA,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(YA,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(xR,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),t.jsx(CR,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e,anchorRect:c.usageAnchorRect}),t.jsx(tT,{isOpen:c.systemStatsOpen,onClose:c.closeSystemStats,projectId:e}),c.schedulesOpen&&t.jsx(WR,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(Pi,{children:t.jsx(YR,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:w,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(rT,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:i,onOpenTaskDetail:E=>{const C=n.find(z=>z.id===E);C&&c.openDetailTask(C)}}),t.jsx(Pi,{children:t.jsx(lT,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(Pi,{children:t.jsx(yT,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(AT,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(a.Suspense,{fallback:null,children:t.jsx(d4,{onProjectRegistered:u.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(c4,{onComplete:u.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:u.handleAddProject,onOpenNewTask:S,onOpenGitHubImport:k,firstCreatedTask:x,onViewTask:A}),t.jsx(pg,{toasts:o,onRemove:l})]})}function p4({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 Xc=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function f4(e,n){if(n==="ready")return"done";const s=Xc.findIndex(r=>r.id===n),i=Xc.findIndex(r=>r.id===e);return i<s?"done":i===s?"active":"pending"}function g4({stage:e}){const[n]=a.useState(()=>cv());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:Xc.map(s=>{const i=f4(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(rt,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:s.label})]},s.id)})})]})})}const x4=5e3;function b4(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function v4(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++,ko(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 y4(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 Uj(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()},x4),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[g]);const p=v4(e,s,i),f=b4(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:f,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:u,refresh:g}}const j4={planning:Zs,subtask:Bi,mission_interview:cs,milestone_interview:cs,slice_interview:cs},k4={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function w4({sessions:e,generating:n,needsInput:s,onOpenSession:i,onDismissSession:r}){const{confirm:o}=Bs(),[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}=Ra(),f=a.useMemo(()=>Gi(),[]);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),A=[S.status,S.updatedAt,k?.tabId??S.lockedByTab??"",k?.stale?"stale":"fresh"].join("|"),w=h.current.get(S.id);w&&w!==A&&b.add(S.id),y.set(S.id,A)}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(rt,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(bc,{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=j4[b.type],S=b.status==="generating",k=b.status==="awaiting_input",A=b.status==="error",w=p.get(b.id),E=w?.tabId??b.lockedByTab??null,C=!!(E&&E!==f&&!w?.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:[A?t.jsx(ss,{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:[A?"Failed":k4[b.type],S&&" — generating...",k&&!C&&" — needs input",k&&C&&" — active in another tab"]})]}),S&&t.jsx(rt,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),k&&!C&&t.jsx(bc,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),k&&C&&t.jsx(Lo,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:_=>{_.stopPropagation(),r(b.id)},title:"Dismiss",children:t.jsx(Kt,{size:12})})]},b.id)})})]})]})}function N4(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 S4(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:wn};case"paused":return{label:"Paused",color:"var(--triage)",icon:Fs};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:Fn}}}function C4({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}=y4(e,n,s,u),[f,x]=a.useState(!1),v=a.useMemo(()=>S4(h.executorState),[h.executorState]),b=a.useMemo(()=>N4(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(nd,{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(w4,{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(Un,{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(wi,{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 E4={planning:Zs,subtask:Bi,mission_interview:cs,milestone_interview:cs,slice_interview:cs},_4={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},Di=new Set;function M4({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:i}){const[r,o]=a.useState(0),l=()=>o(f=>f+1);a.useEffect(()=>{if(Di.size===0)return;const f=new Map(e.map(v=>[v.id,v]));let x=!1;for(const v of Di){const b=f.get(v);b&&b.status!=="awaiting_input"&&b.status!=="error"&&(Di.delete(v),x=!0)}x&&l()},[e]);const c=a.useMemo(()=>e.filter(f=>(f.status==="awaiting_input"||f.status==="error")&&!Di.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=>{Di.add(f),l()},g=f=>{Di.delete(f.id),l(),n(f)},p=()=>{for(const f of c)Di.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(ss,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(Kt,{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=E4[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(ss,{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":_4[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(Kt,{size:14,"aria-hidden":"true"})})]})]},f.id)})})]})}function A4({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(Kt,{size:16,"aria-hidden":"true"})})]})}function R4({onResume:e}){const n=FT();if(!n)return null;const s=n.completedSteps.length,i=yi.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:()=>{_s("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(wn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function T4({onOpenSettings:e,onOpenModelOnboarding:n}){const s=Ea(),i=dg(),[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([xr(),Ki()]);if(b)return;const A=S.providers??[],w=A.find($=>$.id==="github"),C=!A.some($=>$.id!=="github"&&$.authenticated),z=!k.defaultProvider&&!k.defaultModelId,_=w?!w.authenticated:!1;h({needsAiProvider:C,needsDefaultModel:z,needsGitHub:_})}catch{b||c(!0)}finally{b||o(!1)}})(),()=>{b=!0}},[s,i]);const g=a.useCallback(()=>{zT(),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:Fn}),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:Qh}),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:xs}),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(Zs,{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(ss,{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(Kt,{size:16,"aria-hidden":!0})})]})}function P4({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 uc(e){return e>99?"99+":String(e)}function I4({view:e,onChangeView:n,footerVisible:s,modalOpen:i=!1,keyboardOpen:r=!1,onOpenSettings:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:u,mailboxUnreadCount:d=0,onOpenGitManager:m,onOpenWorkflowSteps:h,onOpenSchedules:g,onOpenScripts:p,onToggleTerminal:f,onOpenFiles:x,onOpenGitHubImport:v,onOpenPlanning:b,onResumePlanning:y,activePlanningSessionCount:S=0,onOpenUsage:k,onRunScript:A,projectId:w,onViewAllProjects:E,showSkillsTab:C,experimentalFeatures:z}){const _=Pr(),[$,F]=a.useState(!1),[V,D]=a.useState(!1),[T,I]=a.useState({}),[U,Y]=a.useState(!1),ne=a.useMemo(()=>Object.entries(T).sort(([O],[oe])=>O.localeCompare(oe)),[T]);a.useEffect(()=>{if(!V)return;let O=!1;return Y(!0),br(w).then(oe=>{O||I(oe)}).catch(()=>{O||I({})}).finally(()=>{O||Y(!1)}),()=>{O=!0}},[V,w]);const N=a.useCallback(()=>F(!1),[]),P=a.useCallback(O=>{N(),O?.()},[N]);if(a.useEffect(()=>{if(!$)return;const O=oe=>{oe.key==="Escape"&&F(!1)};return document.addEventListener("keydown",O),()=>document.removeEventListener("keydown",O)},[$]),_!=="mobile"||i||r)return null;const R=S>0&&y?y:b,j=!!z?.roadmap,W=!!C,K=!!z?.todoView,ke=j&&(!W||e==="roadmaps"),be=W&&(!j||e!=="roadmaps"),ce=W&&!be,ve=e==="documents"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||e==="todos"&&K||e==="roadmaps"&&!ke||e==="skills"&&!be;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(Hi,{}),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(kn,{}),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(cs,{}),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(ji,{}),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(xa,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),d>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:uc(d)})]}),be&&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(Fn,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),ke&&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(Nc,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Roadmaps"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${ve?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>F(O=>!O),children:[t.jsx(vc,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),$&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:N}),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:()=>P(u),children:[t.jsx(xa,{}),t.jsx("span",{children:"Mailbox"}),d>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:uc(d)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>P(l),children:[t.jsx(Rs,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>P(c),children:[t.jsx(hr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>P(m),children:[t.jsx(Xs,{}),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:()=>P(f),children:[t.jsx(ci,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>D(O=>!O),"aria-expanded":V,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(bn,{size:14,className:`mobile-more-chevron${V?" mobile-more-chevron--open":""}`})})]}),V&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:U?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(rt,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):ne.length>0?t.jsxs(t.Fragment,{children:[ne.map(([O,oe])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${O}`,onClick:()=>{A&&A(O,oe),N(),D(!1)},children:[t.jsx(wn,{size:14}),t.jsx("span",{children:O})]},O)),p&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{N(),D(!1),p()},children:[t.jsx(Os,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):p&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":"mobile-more-scripts-manage",onClick:()=>{N(),D(!1),p()},children:[t.jsx(Os,{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:()=>P(x),children:[t.jsx(Un,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>P(R),children:[t.jsx(Zs,{}),t.jsx("span",{children:"Planning"}),S>0&&t.jsx("span",{className:"mobile-more-item-badge",children:uc(S)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>P(h),children:[t.jsx(Cc,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>P(g),children:[t.jsx(wi,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>P(v),children:[t.jsx(P4,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>P(k),children:[t.jsx(Rs,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>P(E),children:[t.jsx(Yh,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>P(()=>n("documents")),children:[t.jsx(Ui,{}),t.jsx("span",{children:"Documents"})]}),ce&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>P(()=>n("skills")),children:[t.jsx(Fn,{}),t.jsx("span",{children:"Skills"})]}),j&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-roadmaps",onClick:()=>P(()=>n("roadmaps")),children:[t.jsx(Nc,{}),t.jsx("span",{children:"Roadmaps"})]}),z?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>P(()=>n("insights")),children:[t.jsx(Qn,{}),t.jsx("span",{children:"Insights"})]}),z?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>P(()=>n("memory")),children:[t.jsx(fo,{}),t.jsx("span",{children:"Memory"})]}),z?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{P(()=>n("dev-server"))},children:[t.jsx(hr,{size:14}),t.jsx("span",{children:"Dev Server"})]}),K&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>P(()=>n("todos")),children:[t.jsx(tp,{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:()=>P(o),children:[t.jsx(or,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function $4({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(kn,{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 Id="__fn_agent__";function fg(e,n){const s=typeof e=="string"?e.trim():"",i=typeof n=="string"?n.trim():"";return!s||!i?{}:{modelProvider:s,modelId:i}}function Mh(e,n,s){const i=typeof e=="string"?e.trim():"",r=fg(n,s),o=i||(r.modelProvider&&r.modelId?Id:"");return o?{agentId:o,...r}:null}function mc(e,n,s){const i=fg(n,s),r=i.modelProvider??"",o=i.modelId??"";return`${e}::${r}/${o}`}function D4(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 Ah(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:D4(e.metadata),createdAt:e.createdAt}}function L4(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),A=a.useRef(!1),w=a.useRef(""),E=a.useRef(null),C=a.useRef(""),z=a.useRef(null);a.useEffect(()=>{w.current=y},[y]);const _=a.useCallback(async N=>{const P={agentId:N.agentId};return N.modelProvider&&N.modelId&&(P.modelProvider=N.modelProvider,P.modelId=N.modelId),(await tw(P,e)).session},[e]),$=a.useCallback(async(N,P,R)=>{const j=Mh(N,P,R);if(!j)return;const W=mc(j.agentId,j.modelProvider,j.modelId);o(!0);try{const{session:K}=await ew({agentId:j.agentId,modelProvider:j.modelProvider,modelId:j.modelId},e);if(K)i(K),C.current=W;else{const ke=await _(j);i(ke),C.current=W}}catch(K){console.error("[useQuickChat] Failed to initialize session:",K),n?.("Failed to initialize chat","error")}finally{o(!1)}},[e,n,_]),F=a.useCallback(async()=>{if(s){d(!0);try{const N=await cu(s.id,{limit:50},e);c(N.messages.map(Ah))}catch(N){console.error("[useQuickChat] Failed to load messages:",N)}finally{d(!1)}}},[s,e]);a.useEffect(()=>{s?F():c([])},[s,F]);const V=a.useCallback(async()=>{if(s){d(!0);try{const N=await cu(s.id,{limit:50},e);c(N.messages.map(Ah))}catch(N){console.error("[useQuickChat] Failed to reload messages:",N)}finally{d(!1)}}},[s,e]),D=a.useCallback(async(N,P,R)=>{const j=Mh(N,P,R);if(!j)return;const W=mc(j.agentId,j.modelProvider,j.modelId);z.current=j;const K=W===C.current&&s;if(K||(k.current&&(k.current.close(),k.current=null),p(""),x(""),b([]),h(!1)),K){await V();return}i(null),c([]),C.current=W,await $(j.agentId,j.modelProvider,j.modelId)},[$,V,s]),T=a.useCallback(async(N,P)=>{await D(Id,N,P)},[D]),I=a.useCallback(async()=>{const N=z.current;if(!N)return;const P=mc(N.agentId,N.modelProvider,N.modelId);k.current&&(k.current.close(),k.current=null),p(""),x(""),b([]),h(!1),c([]),i(null),o(!0);try{const R=await _(N);i(R),C.current=P}catch(R){console.error("[useQuickChat] Failed to start a fresh session:",R),n?.("Failed to start a new chat","error")}finally{o(!1)}},[n,_]),U=a.useCallback(()=>{s&&(A.current=!0,k.current?.close(),k.current=null,nw(s.id,e).catch(()=>{}),h(!1),p(""),x(""),b([]))},[s,e]),Y=a.useCallback(()=>{w.current="",S("")},[]),ne=a.useCallback((N,P)=>{if(!s||!N.trim()&&(!P||P.length===0))return Promise.resolve();if(m)return P&&P.length>0?Promise.reject(new Error("Cannot send attachments while a response is streaming")):(w.current=N,S(N),Promise.resolve());const R=new Promise((j,W)=>{E.current={resolve:j,reject:W},A.current=!1,k.current&&(k.current.close(),k.current=null);const ke={id:`temp-${Date.now()}`,sessionId:s.id,role:"user",content:N,createdAt:new Date().toISOString()};c(oe=>[...oe,ke]),p(""),x(""),b([]),h(!0);let be="",ce="",ve=[];const O={onThinking:oe=>{ce+=oe,x(ce)},onText:oe=>{be+=oe,p(be)},onToolStart:oe=>{ve=[...ve,{toolName:oe.toolName,args:oe.args,isError:!1,status:"running"}],b(ve)},onToolEnd:oe=>{const te=[...ve];for(let pe=te.length-1;pe>=0;pe--){const de=te[pe];if(de?.toolName===oe.toolName&&de.status==="running"){te[pe]={...de,status:"completed",isError:oe.isError,result:oe.result},ve=te,b(te);return}}ve=[...te,{toolName:oe.toolName,isError:oe.isError,result:oe.result,status:"completed"}],b(ve)},onDone:oe=>{const te={id:oe.messageId||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:be,thinkingOutput:ce||void 0,toolCalls:ve.length>0?ve:void 0,createdAt:new Date().toISOString()};c(de=>[...de,te]),p(""),x(""),b([]),h(!1),k.current=null,E.current?.resolve(),E.current=null;const pe=w.current.trim();pe&&(w.current="",S(""),ne(pe))},onError:oe=>{if(p(""),x(""),b([]),h(!1),k.current=null,console.error("[useQuickChat] Stream error:",oe),n?.("Failed to get response","error"),E.current?.reject(new Error(typeof oe=="string"?oe:"Failed to get response")),E.current=null,!A.current){const te=w.current.trim();te&&(w.current="",S(""),ne(te))}V()}};k.current=sw(s.id,N,O,P,e)});return R.catch(()=>{}),R},[s,m,e,n,V]);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:ne,stopStreaming:U,clearPendingMessage:Y,switchSession:D,startModelChat:T,startFreshSession:I,loadMessages:F,reloadMessages:V}),[s,r,l,u,m,g,f,v,y,ne,U,Y,D,T,I,F,V])}function z4(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 Ma({...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 $j(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 Hs(`/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||!Nw(g));return{agents:s,activeAgents:h,stats:r,isLoading:l,loadAgents:u,loadStats:d}}function O4({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=cw(l.path),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(Gh,{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 F4=200;function U4(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((w,E)=>{if(E<0||E>w.length){r(!1);return}const C=z=>/[a-zA-Z0-9/_.-]/.test(z);for(let z=E-1;z>=0;z--){if(w[z]==="#")if(z===0){const _=w.slice(z+1,E);u(z),l(_),f(0),r(!0);return}else{const _=w[z-1];if(/[\s,.;:!?'"()[\]{}]/.test(_)){const $=w.slice(z+1,E);u(z),l($),f(0),r(!0);return}r(!1);return}if(!C(w[z])){r(!1);return}}r(!1)},[]),y=a.useCallback(()=>{r(!1),l(""),u(-1),m([]),f(0),g(!1)},[]),S=a.useCallback(async w=>{if(!w.trim()){m([]),g(!1);return}v.current?.abort(),v.current=new AbortController;try{g(!0);const E=await Hy(w,s,n);m(E.files),f(0)}catch(E){E.name!=="AbortError"&&m([])}finally{g(!1)}},[s,n]);a.useEffect(()=>{if(i)return x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{S(o)},F4),()=>{x.current&&clearTimeout(x.current)}},[o,i,S]);const k=a.useCallback((w,E)=>{if(!i||c<0)return E;const C=E.slice(0,c),z=E.slice(c+1),_=z.match(/[\s]|$/),$=_?_.index:z.length,F=z.slice($);return`${C}#${w.path}${F}`},[i,c]),A=a.useCallback((w,E)=>{if(!i||d.length===0)return!1;switch(w.key){case"ArrowDown":return w.preventDefault(),f(C=>Math.min(C+1,d.length-1)),!0;case"ArrowUp":return w.preventDefault(),f(C=>Math.max(C-1,0)),!0;case"Enter":case"Tab":return d[p]?(w.preventDefault(),!0):!1;case"Escape":return w.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:A}}function B4(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let hc=null;function H4(){return hc===null&&(hc=window.innerHeight),hc}function q4(){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=H4()-e.offsetTop-e.height;return i>=30&&i>80?i:0}function gg({enabled:e=!0}={}){const[n,s]=a.useState(0),[i,r]=a.useState(null);return a.useEffect(()=>{if(!e||!B4()){s(0),r(null);return}const o=window.visualViewport;if(!o){s(0),r(null);return}const l=()=>{const c=q4();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 V4(e){return`${e.name?.trim()||e.id} (${e.role})`}function W4(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 K4(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 ho(e,n){return e.length<=n?e:`${e.slice(0,n)}…`}function G4(e){if(!e)return null;const n=Object.entries(e);return n.length===0?null:n.map(([s,i])=>{const r=typeof i=="string"?i:(()=>{try{return JSON.stringify(i)}catch{return String(i)}})();return`${s}=${ho(r,50)}`}).join(", ")}function J4(e){if(e===void 0)return null;if(typeof e=="string")return ho(e,200);try{return ho(JSON.stringify(e),200)}catch{return ho(String(e),200)}}function Rh(e,n=!1){if(!e||e.length===0)return null;const s=(g,p)=>{const f=g.status==="running",x=g.status==="completed"&&g.isError,v=G4(g.args),b=J4(g.result),y=f?v:b?`result: ${b}`:v?`args: ${v}`:null,S=f?"running":x?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${f?" chat-tool-call--running":""}${x?" chat-tool-call--error":""}`,open:f,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:g.toolName}),y&&t.jsx("span",{className:"chat-tool-call-preview",title:y,children:y}),t.jsx("span",{className:"chat-tool-call-status-text",children:S})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[v&&t.jsxs("div",{className:"chat-tool-call-row",children:[t.jsx("span",{className:"chat-tool-call-label",children:"args"}),t.jsx("span",{className:"chat-tool-call-value",children:v})]}),b&&t.jsxs("div",{className:`chat-tool-call-row${x?" chat-tool-call-row--error":""}`,children:[t.jsx("span",{className:"chat-tool-call-label",children:"result"}),t.jsx("span",{className:"chat-tool-call-value",children:b})]})]})]},`${g.toolName}-${p}`)},i=`chat-tool-calls${n?" chat-tool-calls--compact":""}`;if(e.length===1)return t.jsxs("div",{className:i,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(Fd,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:"Tool calls"})]}),s(e[0],0)]});const r=e.filter(g=>g.status==="running").length,o=e.filter(g=>g.status==="completed"&&g.isError).length,l=r>0,c=Array.from(new Set(e.map(g=>g.toolName))),u=c.slice(0,5),d=Math.max(0,c.length-u.length),m=d>0?`${u.join(", ")}, +${d} more`:u.join(", "),h=l?`(${r} running)`:o>0?`(${o} ${o===1?"error":"errors"})`:null;return t.jsx("div",{className:i,"data-testid":"chat-tool-calls",children:t.jsxs("details",{className:`chat-tool-calls-group${n?" chat-tool-calls-group--compact":""}`,"data-testid":"chat-tool-calls-group",open:l,children:[t.jsxs("summary",{className:"chat-tool-calls-group-summary",children:[t.jsx(Fd,{size:12,"aria-hidden":"true"}),t.jsxs("span",{children:[e.length," tool calls"]}),t.jsx("span",{className:"chat-tool-calls-names",title:m,children:m}),h&&t.jsx("span",{className:"chat-tool-calls-group-status",children:h})]}),e.map((g,p)=>s(g,p))]})})}const Y4={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 Q4(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 co={width:320,height:400},X4=new Set(["image/png","image/jpeg","image/gif","image/webp","text/plain","application/json","text/yaml","text/x-log","text/csv","application/xml","text/markdown"]),Z4=[".png",".jpg",".jpeg",".gif",".webp",".txt",".json",".yaml",".yml",".log",".csv",".xml",".md"];function eP(e){return e.type.startsWith("image/")}function tP(e){if(X4.has(e.type))return!0;const n=e.name.toLowerCase();return Z4.some(s=>n.endsWith(s))}const la={width:280,height:260},Zc=768,ca=8;function nP(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,A=window.innerHeight-v-b-y-S;return{x:Math.max(b,Math.min(k,x.x)),y:Math.max(b,Math.min(A,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 sP(e,n,s){const i=`fusion:quick-chat-size-${e||"default"}`,r=a.useCallback(()=>typeof window<"u"&&window.innerWidth>Zc,[]),o=a.useCallback((g,p,f)=>{if(typeof window>"u")return g;const x=Math.max(la.width,window.innerWidth-p-ca),v=Math.max(la.height,window.innerHeight-f-ca);return{width:Math.max(la.width,Math.min(x,g.width)),height:Math.max(la.height,Math.min(v,g.height))}},[]),l=a.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=Zc)return co;try{const g=localStorage.getItem(i);if(!g)return co;const p=JSON.parse(g);return typeof p.width!="number"||typeof p.height!="number"?co:{width:p.width,height:p.height}}catch{return co}},[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 A=x.width,w=x.height,E=x.anchorRight,C=x.anchorBottom;if(p.includes("w")&&(A=x.width-S),p.includes("e")){const D=S;A=x.width+D,E=x.anchorRight-D}if(p.includes("n")&&(w=x.height-k),p.includes("s")){const D=k;w=x.height+D,C=x.anchorBottom-D}const z=n+E,_=s+C,$=o({width:A,height:w},z,_),F=Math.max(ca-n,Math.min(window.innerWidth-n-la.width-ca,E)),V=Math.max(ca-s,Math.min(window.innerHeight-s-la.height-ca,C));u($),m({right:F,bottom:V})},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 iP({projectId:e,addToast:n,showFAB:s=!0,open:i,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:u}){const{agents:d}=z4(e),[m,h]=a.useState(!1),g=i!==void 0,p=g?i:m,f=g?ae=>{r?.(typeof ae=="function"?ae(p):ae)}:h,{keyboardOverlap:x,viewportHeight:v}=gg({enabled:p}),b=x>0?{"--keyboard-overlap":`${x}px`,...v!==null?{"--vv-height":`${v}px`}:{}}:{},[y,S]=a.useState("agent"),[k,A]=a.useState(""),[w,E]=a.useState([]),[C,z]=a.useState(!1),[_,$]=a.useState(""),[F,V]=a.useState(""),[D,T]=a.useState(""),[I,U]=a.useState(!1),[Y,ne]=a.useState(0),[N,P]=a.useState(-1),[R,j]=a.useState(()=>new Set),[W,K]=a.useState([]),[ke,be]=a.useState(!1),[,ce]=a.useState(!1),[ve,O]=a.useState({top:0,left:0}),oe=U4({projectId:e}),te=a.useCallback(ae=>{if(!ae||!oe.mentionActive)return;const Ge=ae.getBoundingClientRect();O({top:Ge.top-260,left:Ge.left+8})},[oe.mentionActive]),pe=a.useRef(!1),de=a.useRef(!1),ge=a.useRef(""),ie=a.useRef(0),Ee=a.useRef(null),Le=a.useRef(0),{position:qe,isDragging:et,handlePointerDown:Xe,handlePointerMove:Ze,handlePointerUp:it}=nP(e,pe),Ie=qe.y+60,{panelSize:Ke,anchorOffset:re,handleResizeStart:xe}=sP(e,qe.x,Ie),se=typeof window<"u"&&window.innerWidth>Zc,{activeSession:Ae,messages:ze,isStreaming:me,streamingText:_e,streamingThinking:Fe,streamingToolCalls:nt,sessionsLoading:we,messagesLoading:le,sendMessage:Te,stopStreaming:he,pendingMessage:Me,clearPendingMessage:We,switchSession:Re,startModelChat:ut,startFreshSession:Q}=L4(e,n),ue=a.useRef(null),ye=a.useRef(null),at=a.useRef(null),X=a.useRef(null),Ye=a.useRef(null),ot=a.useRef([]),ht=a.useMemo(()=>W4(_),[_]),yt=a.useMemo(()=>w.find(ae=>`${ae.provider}/${ae.id}`===_)??null,[w,_]),vt=a.useMemo(()=>K4(yt,ht),[yt,ht]),pt=a.useMemo(()=>y==="model"?ht?`${Id}::${ht.modelProvider}/${ht.modelId}`:"":k?`${k}::`:"",[y,ht,k]),Et=y==="agent"?!!k:!!ht;a.useEffect(()=>{if(d.length===0){A(""),S("model");return}d.some(Ge=>Ge.id===k)||A(d[0]?.id??"")},[d,k]),a.useEffect(()=>{!p||de.current||(de.current=!0,z(!0),ds().then(ae=>{const Ge=ae.models??[];if(E(Ge),_||Ge.length===0)return;const ct=ae.defaultProvider,Lt=ae.defaultModelId;if(ct&&Lt){const qt=`${ct}/${Lt}`;if(Ge.some(hn=>`${hn.provider}/${hn.id}`===qt)){$(qt),S("model");return}}if(d.length===0){const qt=Ge[0];qt&&$(`${qt.provider}/${qt.id}`)}}).catch(ae=>{console.error("[QuickChatFAB] Failed to load models:",ae),E([])}).finally(()=>{z(!1)}))},[p,d.length,_]),a.useEffect(()=>{if(!p){ge.current="";return}if(!pt){ge.current="";return}const ae=pt===ge.current&&!Ae&&!we;if(!(pt===ge.current&&!ae)){if(ge.current=pt,y==="model"&&ht){ut(ht.modelProvider,ht.modelId);return}y==="agent"&&k&&Re(k)}},[p,y,ht,k,pt,Ae,we,ut,Re]),a.useEffect(()=>{p||(U(!1),T(""),P(-1),ot.current.forEach(ae=>{ae.previewUrl&&URL.revokeObjectURL(ae.previewUrl)}),K([]))},[p]),a.useEffect(()=>{ot.current=W},[W]),a.useEffect(()=>()=>{ot.current.forEach(ae=>{ae.previewUrl&&URL.revokeObjectURL(ae.previewUrl)})},[]);const It=a.useCallback(ae=>{A(ae)},[]),Bt=a.useCallback(ae=>{$(ae)},[]),_t=a.useCallback(()=>{!Et||we||Q()},[Et,we,Q]),Pt=a.useMemo(()=>d.find(ae=>ae.id===k)??null,[d,k]),$t=a.useMemo(()=>{const ae=D.trim().toLowerCase();return ae?d.filter(Ge=>Ge.name.toLowerCase().includes(ae)):d},[d,D]),Ht=a.useMemo(()=>{const ae=new Map;for(const Ge of d)ae.set(Ge.name.toLowerCase(),Ge);return ae},[d]);a.useEffect(()=>{ne(0)},[D,I]),a.useEffect(()=>()=>{Ee.current!==null&&(window.clearTimeout(Ee.current),Ee.current=null)},[]),a.useEffect(()=>{if(!p)return;const ae=ct=>{const Lt=ct.target;ue.current?.contains(Lt)||ye.current?.contains(Lt)||Lt.closest(".model-combobox-dropdown--portal")||f(!1)},Ge=ct=>{ct.key==="Escape"&&f(!1)};return document.addEventListener("mousedown",ae),document.addEventListener("keydown",Ge),()=>{document.removeEventListener("mousedown",ae),document.removeEventListener("keydown",Ge)}},[p,f]),a.useEffect(()=>{if(!p)return;const ae=at.current;ae&&(ae.scrollTop=ae.scrollHeight)},[ze,_e,Fe,p]);const Gt=a.useMemo(()=>y==="agent"?Pt?`Message ${Pt.name||Pt.id}`:"Select an agent to start chatting":vt?`Message ${vt}`:"Select a model to start chatting",[y,Pt,vt]),Dt=!Et||!Ae,Tt=Me.length>50?`${Me.slice(0,50)}…`:Me,jt=a.useCallback(ae=>{if(!ae||ae.length===0)return;const Ge=[];for(let ct=0;ct<ae.length;ct+=1){const Lt=ae[ct];tP(Lt)&&Ge.push({file:Lt,previewUrl:eP(Lt)?URL.createObjectURL(Lt):""})}Ge.length>0&&K(ct=>[...ct,...Ge])},[]),Mt=a.useCallback(ae=>{K(Ge=>{const ct=Ge[ae];return ct?.previewUrl&&URL.revokeObjectURL(ct.previewUrl),Ge.filter((Lt,qt)=>qt!==ae)})},[]),Zt=a.useCallback(ae=>{jt(ae.clipboardData?.files)},[jt]),At=a.useCallback(async()=>{const ae=F.trim(),Ge=ot.current;if(!(!ae&&Ge.length===0)&&!Dt){V(""),U(!1),T(""),P(-1);try{await Te(ae,Ge.map(ct=>ct.file)),Ge.forEach(ct=>{ct.previewUrl&&URL.revokeObjectURL(ct.previewUrl)}),K(ct=>ct.filter(Lt=>!Ge.includes(Lt)))}catch{}}},[Te,Dt,F]),H=a.useCallback(ae=>{ae.preventDefault(),Le.current+=1,be(!0)},[]),fe=a.useCallback(ae=>{ae.preventDefault(),ae.dataTransfer.dropEffect="copy",be(!0)},[]),$e=a.useCallback(ae=>{ae.preventDefault(),Le.current=Math.max(0,Le.current-1),Le.current===0&&be(!1)},[]),M=a.useCallback(ae=>{ae.preventDefault(),Le.current=0,be(!1),jt(ae.dataTransfer?.files)},[jt]),ee=a.useCallback((ae,Ge)=>{const ct=Q4(ae,Ge);if(ct){U(!0),T(ct.filter),P(ct.start);return}U(!1),T(""),P(-1)},[]),Oe=a.useCallback(ae=>{const Ge=X.current;if(!Ge||N<0)return;const ct=Ge.selectionStart??ie.current,Lt=Ge.selectionEnd??ct,qt=Math.max(ct,Lt),En=Math.min(N,qt),Vt=`${`@${ae.name.replace(/\s+/g,"_")}`} `,J=F.slice(0,En)+Vt+F.slice(qt),Pe=En+Vt.length;V(J),U(!1),T(""),ne(0),P(-1),window.requestAnimationFrame(()=>{X.current&&(X.current.focus(),X.current.setSelectionRange(Pe,Pe))})},[N,F]),dt=a.useCallback(ae=>{const Ge=ae.target.value,ct=ae.target.selectionStart??Ge.length;ie.current=ct,V(Ge),ee(Ge,ct),oe.detectMention(Ge,ct),ce(oe.mentionActive),oe.mentionActive&&te(ae.target)},[ee,oe,te]),Nt=a.useCallback(()=>{Ee.current!==null&&window.clearTimeout(Ee.current),Ee.current=window.setTimeout(()=>{U(!1),T(""),P(-1),ce(!1),oe.dismissMention(),Ee.current=null},120)},[oe]),Ct=a.useCallback(()=>{Ee.current!==null&&(window.clearTimeout(Ee.current),Ee.current=null)},[]),Rt=a.useCallback(ae=>{const Ge=ae.currentTarget,ct=Ge.selectionStart??Ge.value.length;ie.current=ct,ee(Ge.value,ct),oe.detectMention(Ge.value,ct),ce(oe.mentionActive),oe.mentionActive&&te(Ge)},[ee,oe,te]),un=a.useCallback(ae=>{ae.key!=="Escape"&&Rt(ae)},[Rt]),mn=a.useCallback(ae=>{const Ge=/@([\w-]+)/g,ct=[];let Lt=0,qt=Ge.exec(ae);for(;qt;){const[En,hn=""]=qt,Vt=qt.index;Vt>Lt&&ct.push(ae.slice(Lt,Vt));const J=hn.replace(/_/g," ").toLowerCase(),Pe=Ht.get(J);Pe?ct.push(t.jsxs("span",{className:"chat-mention-chip",children:["@",Pe.name.replace(/\s+/g,"_")]},`${Pe.id}-${Vt}`)):ct.push(En),Lt=Vt+En.length,qt=Ge.exec(ae)}return Lt<ae.length&&ct.push(ae.slice(Lt)),ct.length===0?ae:ct},[Ht]),Nn=a.useCallback(ae=>{j(Ge=>{const ct=new Set(Ge);return ct.has(ae)?ct.delete(ae):ct.add(ae),ct})},[]),Qt=a.useCallback((ae,Ge=!1)=>Ge?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:ae}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(hi,{remarkPlugins:[pi],components:Y4,children:ae})}),[]),An=a.useCallback(ae=>{if(ie.current=ae.currentTarget.selectionStart??ie.current,oe.mentionActive&&oe.files.length>0){if(oe.handleKeyDown(ae,F),ae.key==="Enter"||ae.key==="Tab"){const Ge=oe.files[oe.selectedIndex];if(Ge){const ct=oe.selectFile(Ge,F);V(ct),oe.dismissMention(),ce(!1)}}return}if(I&&ae.key==="ArrowDown"){ae.preventDefault(),$t.length>0&&ne(Ge=>(Ge+1)%$t.length);return}if(I&&ae.key==="ArrowUp"){ae.preventDefault(),$t.length>0&&ne(Ge=>Ge===0?$t.length-1:Ge-1);return}if(I&&ae.key==="Enter"){ae.preventDefault();const Ge=$t[Y]??$t[0];Ge&&Oe(Ge);return}if(I&&ae.key==="Escape"){ae.preventDefault(),ae.stopPropagation(),U(!1),T(""),P(-1);return}ae.key!=="Enter"||ae.shiftKey||(ae.preventDefault(),At())},[I,$t,Y,Oe,At,oe,F]),Ne=a.useCallback(()=>{if(pe.current){pe.current=!1;return}f(ae=>!ae)},[f]);return t.jsxs(t.Fragment,{children:[s&&t.jsx("button",{ref:ye,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":et?"true":"false",style:{right:qe.x,bottom:qe.y},onPointerDown:Xe,onPointerMove:Ze,onPointerUp:it,onClick:Ne,children:t.jsx(ji,{size:24})}),p&&t.jsxs("div",{className:"quick-chat-panel",ref:ue,"data-testid":"quick-chat-panel",style:{right:qe.x+re.right,bottom:Ie+re.bottom,...se?{width:Ke.width,height:Ke.height}:{},...b},children:[se&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:xe,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:xe,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:xe,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:xe,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:xe,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:xe,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:xe,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:xe,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"}),vt&&t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:vt,children:vt})]}),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:_t,disabled:!Et||we,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(Kt,{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"),$("")},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"),A("")},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:ae=>It(ae.target.value),"data-testid":"quick-chat-agent-select",children:d.map(ae=>t.jsx("option",{value:ae.id,children:V4(ae)},ae.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(Bn,{id:"quick-chat-model-override",models:w,value:_,onChange:Bt,label:"Select model override",placeholder:C?"Loading models…":"Select a model",disabled:C||w.length===0,favoriteProviders:o,favoriteModels:l,onToggleFavorite:c,onToggleModelFavorite:u})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:at,"data-testid":"quick-chat-messages",children:we||le?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):ze.length===0&&!_e&&!Fe&&!me?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[ze.map(ae=>{const Ge=ae.role==="user",ct=!Ge&&R.has(ae.id);return t.jsxs("div",{className:`quick-chat-panel-message ${Ge?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${ae.id}`,children:[Ge?t.jsx("p",{children:mn(ae.content)}):t.jsxs(t.Fragment,{children:[Qt(ae.content,ct),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${ct?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":ct?"Show rendered markdown":"Show plain text",onClick:()=>Nn(ae.id),children:ct?t.jsx(yc,{size:14}):t.jsx(fa,{size:14})})]}),Rh(ae.toolCalls,!0)]},ae.id)}),me&&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:[_e?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:Qt(_e,R.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${R.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":R.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>Nn("__streaming__"),children:R.has("__streaming__")?t.jsx(yc,{size:14}):t.jsx(fa,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:"Thinking…"}),Rh(nt,!0),Fe&&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:Fe})]})]})]})}),W.length>0&&t.jsx("div",{className:"quick-chat-attachment-previews","data-testid":"quick-chat-attachment-previews",children:W.map((ae,Ge)=>t.jsxs("div",{className:"quick-chat-attachment-preview","data-testid":`quick-chat-attachment-preview-${Ge}`,children:[ae.previewUrl?t.jsx("img",{src:ae.previewUrl,alt:ae.file.name}):t.jsx("span",{className:"quick-chat-attachment-preview-name",children:ae.file.name}),t.jsx("button",{type:"button",className:"quick-chat-attachment-remove","data-testid":`quick-chat-attachment-remove-${Ge}`,"aria-label":`Remove ${ae.file.name}`,onClick:()=>Mt(Ge),children:"×"})]},`${ae.file.name}-${Ge}`))}),t.jsxs("div",{className:"quick-chat-panel-input",children:[t.jsxs("div",{className:`quick-chat-input-wrapper${ke?" quick-chat-input-wrapper--dragover":""}`,onDragEnter:H,onDragOver:fe,onDragLeave:$e,onDrop:M,children:[t.jsx("input",{ref:Ye,type:"file",accept:"image/*,.txt,.json,.yaml,.yml,.log,.csv,.xml,.md",multiple:!0,tabIndex:-1,"aria-hidden":"true",className:"quick-chat-attachment-input",onChange:ae=>{jt(ae.target.files),ae.target.value=""}}),t.jsx("button",{type:"button",className:"btn-icon","data-testid":"quick-chat-attach-btn","aria-label":"Attach files",onClick:()=>Ye.current?.click(),children:t.jsx(Xh,{size:16})}),t.jsx("input",{ref:X,type:"text",value:F,onChange:dt,onKeyDown:An,onKeyUp:un,onClick:Rt,onBlur:Nt,onFocus:Ct,onPaste:Zt,placeholder:Gt,disabled:Dt,"data-testid":"quick-chat-input"}),t.jsx($4,{agents:d,filter:D,highlightedIndex:Y,visible:I,onSelect:Oe,position:"above"}),t.jsx(O4,{visible:oe.mentionActive&&!I,position:ve,files:oe.files,selectedIndex:oe.selectedIndex,onSelect:ae=>{const Ge=oe.selectFile(ae,F);V(Ge),oe.dismissMention(),ce(!1),X.current?.focus()},loading:oe.loading}),Me&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${Tt}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:We,children:"×"})]})]}),me?t.jsx("button",{type:"button",className:"chat-input-stop",onClick:he,"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(gs,{size:14})}):t.jsx("button",{type:"button",onClick:()=>{At()},disabled:Dt||F.trim().length===0&&W.length===0,"data-testid":"quick-chat-send",children:t.jsx(Li,{size:16})})]})]})]})}function tr(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Th(e){return e.status==="generating"||e.status==="awaiting_input"}function nr(e){return e==="complete"||e==="error"}function aP(e){const[n,s]=a.useState([]),i=a.useRef(new Map),r=a.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:u}=Ra(),d=a.useCallback(()=>{ad(e).then(p=>{const f=p.filter(v=>{const b=tr(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,tr(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&&!nr(v.status)&&r.current.delete(v.sessionId),nr(v.status)){x.delete(v.sessionId)&&(f=!0),i.current.set(v.sessionId,b);continue}const k=x.get(v.sessionId),A=v.type??k?.type,w=v.title??k?.title;if(!k&&(!A||!w))continue;const E={id:v.sessionId,type:A??"planning",status:v.status,title:w??"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!==E.status||C.title!==E.title||C.type!==E.type||C.projectId!==E.projectId||C.lockedByTab!==E.lockedByTab||C.updatedAt!==E.updatedAt)&&(x.set(v.sessionId,E),i.current.set(v.sessionId,b),f=!0)}return f?[...x.values()].sort((v,b)=>tr(b.updatedAt)-tr(v.updatedAt)):p})},[e,o]),a.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",f=v=>{try{const b=JSON.parse(v.data),y=tr(b.updatedAt)||Date.now();s(S=>{const k=i.current.get(b.id)??0;if(y<k)return S;const A=r.current.get(b.id);if(A!==void 0&&y<=A)return S;if(A!==void 0&&y>A&&!nr(b.status)&&r.current.delete(b.id),i.current.set(b.id,y),nr(b.status))return S.filter(E=>E.id!==b.id);const w=S.findIndex(E=>E.id===b.id);if(w>=0){const E=[...S];return E[w]=b,E}return Th(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}),nr(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 Hs(`/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=Gi();let b=!1;if(x==="planning")try{await cp(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 mp(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 xp(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 bp(p)}catch{}s(S=>S.filter(k=>k.id!==p))},[c,e,n]),h=a.useMemo(()=>n.filter(p=>Th(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 Jn(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 Ph(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function pc(e,n){if(Ph(n.updatedAt,e.updatedAt)<0)return e;if(e.column===n.column)return n;const i=Ph(e.columnMovedAt,n.columnMovedAt);return e.columnMovedAt&&!n.columnMovedAt?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:i>0?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:n}function rP(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 I=>{const U=++m.current,Y=n,ne=I?.searchQueryOverride??s,N=I?.includeArchivedOverride??u.current;try{const P=await Rv(void 0,void 0,Y,ne,N);if(m.current!==U||n!==Y)return;o(P.map(Jn)),f.current=Date.now()}catch{if(m.current!==U||n!==Y)return;if(I?.clearOnError){o([]);return}o(P=>P)}},[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 I=setTimeout(()=>{y({searchQueryOverride:s})},300);return()=>clearTimeout(I)},[s]),a.useEffect(()=>{y({clearOnError:!0});const I=()=>{if(document.visibilityState!=="visible")return;const U=Date.now();U-h.current<b||(h.current=U,y())};return document.addEventListener("visibilitychange",I),()=>{document.removeEventListener("visibilitychange",I)}},[y]),a.useEffect(()=>{if(i===!1)return;const I=x.current,U=n?`?projectId=${encodeURIComponent(n)}`:"",Y=()=>x.current!==I;let ne=!0;const N=ke=>{if(Y())return;const be=Jn(JSON.parse(ke.data));if(g.current){p.current({searchQueryOverride:g.current});return}o(ce=>{const ve=ce.findIndex(pe=>pe.id===be.id);if(ve===-1)return[...ce,be];const O=ce[ve],oe=pc(O,be);if(oe===O)return ce;const te=[...ce];return te[ve]=oe,te}),f.current=Date.now()},P=ke=>{if(Y())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:be,to:ce}=JSON.parse(ke.data),ve=Jn(be);o(O=>O.map(oe=>oe.id===ve.id?{...ve,column:ce}:oe)),f.current=Date.now()},R=ke=>{if(Y())return;if(g.current){p.current({searchQueryOverride:g.current});return}const be=Jn(JSON.parse(ke.data));o(ce=>ce.map(ve=>ve.id!==be.id?ve:pc(ve,be))),f.current=Date.now()},j=ke=>{if(Y())return;if(g.current){p.current({searchQueryOverride:g.current});return}const be=Jn(JSON.parse(ke.data));o(ce=>ce.filter(ve=>ve.id!==be.id))},W=ke=>{if(Y())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:be}=JSON.parse(ke.data),ce=Jn(be);o(ve=>ve.map(O=>O.id===ce.id?{...ce,column:"done"}:O))},K=Hs(`/api/events${U}`,{events:{"task:created":N,"task:moved":P,"task:updated":R,"task:deleted":j,"task:merged":W},onReconnect:()=>{ne&&(Y()||p.current())}});return()=>{ne=!1,K()}},[n,i]);const k=a.useCallback(async I=>{const U=Jn(await ap(I,n));return o(Y=>Y.some(ne=>ne.id===U.id)?Y:[...Y,U]),U},[n]),A=a.useCallback(async(I,U)=>Jn(await Pv(I,U,n)),[n]),w=a.useCallback(async I=>Jn(await rp(I,n)),[n]),E=a.useCallback(async I=>Jn(await Iv(I,n)),[n]),C=a.useCallback(async I=>$v(I,n),[n]),z=a.useCallback(async I=>Jn(await Dv(I,n)),[n]),_=a.useCallback(async I=>{const U=Jn(await Lv(I,n));return o(Y=>Y.some(ne=>ne.id===U.id)?Y:[...Y,U]),U},[n]),$=a.useCallback(async(I,U)=>{const Y=d.current.find(N=>N.id===I),ne=Y?{...Y,...U,updatedAt:new Date().toISOString()}:void 0;ne&&o(N=>N.map(P=>P.id===I?ne:P));try{const N=Jn(await Qs(I,U,n));return o(P=>P.map(R=>R.id===I?N:R)),N}catch(N){throw Y&&o(P=>P.map(R=>R.id===I?Y:R)),N}},[n]),F=a.useCallback(async I=>{const U=Jn(await Ov(I,n));return o(Y=>Y.map(ne=>ne.id===I?U:ne)),U},[n]),V=a.useCallback(async I=>{const U=Jn(await Fv(I,n));return o(Y=>Y.map(ne=>ne.id===I?U:ne)),U},[n]),D=a.useCallback(async()=>{const U=(await Uv(n)).map(Jn);return o(Y=>Y.map(ne=>U.find(P=>P.id===ne.id)||ne)),U},[n]),T=a.useCallback(I=>{if(I.length===0)return;if(g.current){p.current({searchQueryOverride:g.current});return}const U=I.map(Jn);o(Y=>{let ne=Y;for(const N of U){const P=ne.findIndex(W=>W.id===N.id);if(P===-1){ne===Y&&(ne=[...Y]),ne.push(N);continue}const R=ne[P],j=pc(R,N);j!==R&&(ne===Y&&(ne=[...Y]),ne[P]=j)}return ne}),f.current=Date.now()},[]);return{tasks:r,createTask:k,moveTask:A,pauseTask:w,deleteTask:E,mergeTask:C,retryTask:z,duplicateTask:_,updateTask:$,archiveTask:F,unarchiveTask:V,archiveAllDone:D,loadArchivedTasks:S,includeArchived:l,ingestCreatedTasks:T,lastFetchTimeMs:f.current}}const oP=5e3,lP=1e3;function cP(){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 iu();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 iu(),y=`initial fetchProjectsAcrossNodes took ${Math.round(performance.now()-x)}ms (${v.length} projects)`;console.log(`[useProjects] ${y}`),lr("[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}`),lr("[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<lP||(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()},oP),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async g=>{const p=await Fj(g);return n(f=>[...f,p]),p},[]),m=a.useCallback(async(g,p)=>{const f=await Wj(g,p);return n(x=>x.map(v=>v.id===g?f:v)),f},[]),h=a.useCallback(async g=>{await pp(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 dP="kb-dashboard-current-project";function uP(e){return e??"local"}function mP(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=uP(s);a.useEffect(()=>{let p=!1;async function f(){try{const x=await Ki();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(dP);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 cn({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,cn({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,cn({dashboardCurrentProjectIdByNode:f}).catch(()=>{})}},[m]),g=a.useCallback(()=>{u.current=!0,r(null);const p={...d.current};delete p[m],d.current=p,cn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:i,setCurrentProject:h,clearCurrentProject:g,loading:o}}const xg=a.createContext(null);function hP({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()},[]),po.createElement(xg.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function pP(){const e=a.useContext(xg);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const bg="kb-dashboard-theme-mode",vg="kb-dashboard-color-theme",yg=[...kw],ed="theme-data",fc="theme-data.css";function fP(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.endsWith("/")?e.slice(0,-1)+`/${fc}`:e.replace(/\/[^/]+$/,`/${fc}`):`/${fc}`}const As=typeof window<"u",gP=As?a.useLayoutEffect:a.useEffect;function jg(e){return e==="dark"||e==="light"||e==="system"}function Ih(){if(!As)return"dark";try{const e=localStorage.getItem(bg);if(jg(e))return e}catch{}return"dark"}function $h(){if(!As)return"default";try{const e=localStorage.getItem(vg);if(e&&yg.includes(e))return e}catch{}return"default"}function Dh(e){if(As)try{localStorage.setItem(bg,e)}catch{}}function Lh(e){if(As)try{localStorage.setItem(vg,e)}catch{}}function xP(e,n){return e==="system"?n?"dark":"light":e}function bP(e,n,s){if(!As)return;const i=xP(e,s);document.documentElement.setAttribute("data-theme",i),document.documentElement.setAttribute("data-color-theme",n)}function zh(){if(!As)return;const e=fP(),n=document.getElementById(ed);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=ed,document.head.appendChild(s)}function Oh(){if(!As)return;const e=document.getElementById(ed);e&&e.remove()}function vP(){const[e,n]=a.useState(()=>Ih()),[s,i]=a.useState(()=>$h()),[r,o]=a.useState(!0),[l,c]=a.useState(()=>As?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(!As||!r)return;let f=!1;return Ki().then(x=>{f||(jg(x.themeMode)&&!m.current&&(u.current!==x.themeMode&&(u.current=x.themeMode,n(x.themeMode)),Ih()!==x.themeMode&&Dh(x.themeMode)),x.colorTheme&&yg.includes(x.colorTheme)&&!h.current&&(d.current!==x.colorTheme&&(d.current=x.colorTheme,i(x.colorTheme)),$h()!==x.colorTheme&&Lh(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(!As)return;const f=window.matchMedia("(prefers-color-scheme: dark)"),x=v=>{c(v.matches)};return f.addEventListener("change",x),()=>f.removeEventListener("change",x)},[]),gP(()=>{bP(e,s,l)},[e,s,l]),a.useEffect(()=>{!As||r||(s!=="default"?zh():Oh())},[s,r]);const g=a.useCallback(f=>{m.current=!0,u.current=f,n(f),Dh(f),cn({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),Lh(f),f!=="default"?zh():Oh(),cn({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 yP(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,A]=a.useState(!1),[w,E]=a.useState(void 0),[C,z]=a.useState(!1),[_,$]=a.useState(!1),[F,V]=a.useState(!1),[D,T]=a.useState(null),[I,U]=a.useState(!1),[Y,ne]=a.useState(!1),[N,P]=a.useState(void 0),[R,j]=a.useState(!1),[W,K]=a.useState("project"),[ke,be]=a.useState(!1),[ce,ve]=a.useState(!1),[O,oe]=a.useState(!1),[te,pe]=a.useState(!1),[de,ge]=a.useState(!1),[ie,Ee]=a.useState(!1),[Le,qe]=a.useState(!1),et=!!(v||k||s||r||m||Y||R||ke||ce||O||de||te||F||I||C||_||ie||Le),Xe=a.useCallback(()=>i(!0),[]),Ze=a.useCallback(()=>i(!1),[]),it=a.useCallback(()=>o(!0),[]),Ie=a.useCallback(H=>{c(H),o(!0)},[]),Ke=a.useCallback(()=>{const H=n[0];H&&(d(H.id),o(!0))},[n]),re=a.useCallback(H=>{d(H),o(!0)},[]),xe=a.useCallback(()=>{o(!1),c(null),d(void 0)},[]),se=a.useCallback(H=>{p(H),h(!0)},[]),Ae=a.useCallback(H=>{x(H),h(!0)},[]),ze=a.useCallback(()=>{h(!1),p(null),x(void 0)},[]),me=a.useCallback((H,fe="definition")=>{b(H),S(fe)},[]),_e=a.useCallback(H=>{b(H),S("changes")},[]),Fe=a.useCallback(H=>{b(fe=>fe&&{...fe,...H})},[]),nt=a.useCallback(()=>{b(null)},[]),we=a.useCallback(H=>{E(H),A(!0)},[]),le=a.useCallback(()=>{A(!1),E(void 0)},[]),Te=a.useCallback(()=>z(!0),[]),he=a.useCallback(()=>z(!1),[]),Me=a.useCallback(()=>$(!0),[]),We=a.useCallback(()=>$(!1),[]),Re=a.useCallback(H=>{T(H??null),V(!0)},[]),ut=a.useCallback(()=>{V(!1),T(null)},[]),Q=a.useCallback(()=>U(!0),[]),ue=a.useCallback(()=>U(!1),[]),ye=a.useCallback(()=>{ne(H=>!H)},[]),at=a.useCallback(()=>{ne(!1),P(void 0)},[]),X=a.useCallback(()=>j(!0),[]),Ye=a.useCallback(()=>j(!1),[]),ot=a.useCallback(H=>{K(H)},[]),ht=a.useCallback(()=>be(!0),[]),yt=a.useCallback(()=>be(!1),[]),vt=a.useCallback(()=>ve(!0),[]),pt=a.useCallback(()=>ve(!1),[]),Et=a.useCallback(()=>oe(!0),[]),It=a.useCallback(()=>oe(!1),[]),Bt=a.useCallback(()=>pe(!0),[]),_t=a.useCallback(()=>pe(!1),[]),Pt=a.useCallback(()=>ge(!0),[]),$t=a.useCallback(()=>ge(!1),[]),Ht=a.useCallback(async(H,fe)=>{ge(!1),P(fe),ne(!0)},[]),Gt=a.useCallback(()=>Ee(!0),[]),Dt=a.useCallback(()=>Ee(!1),[]),Tt=a.useCallback(()=>qe(!0),[]),jt=a.useCallback(()=>qe(!1),[]),Mt=a.useCallback((H,fe)=>{fe(`Created ${H.id} from planning mode`,"success"),o(!1),c(null)},[]),Zt=a.useCallback((H,fe)=>{const $e=H.map(M=>M.id).join(", ");fe(`Created ${$e} from planning mode`,"success"),o(!1),c(null)},[]),At=a.useCallback((H,fe)=>{const $e=H.map(M=>M.id).join(", ");fe(`Created ${$e} 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:w,schedulesOpen:C,githubImportOpen:_,usageOpen:F,usageAnchorRect:D,systemStatsOpen:I,terminalOpen:Y,terminalInitialCommand:N,filesOpen:R,fileBrowserWorkspace:W,activityLogOpen:ke,gitManagerOpen:ce,workflowStepsOpen:O,agentsOpen:te,scriptsOpen:de,setupWizardOpen:ie,modelOnboardingOpen:Le,anyModalOpen:et,openNewTask:Xe,closeNewTask:Ze,openPlanning:it,openPlanningWithInitialPlan:Ie,resumePlanning:Ke,openPlanningWithSession:re,closePlanning:xe,openSubtaskBreakdown:se,openSubtaskWithSession:Ae,closeSubtask:ze,openDetailTask:me,openDetailWithChangesTab:_e,updateDetailTask:Fe,closeDetailTask:nt,openSettings:we,closeSettings:le,openSchedules:Te,closeSchedules:he,openGitHubImport:Me,closeGitHubImport:We,openUsage:Re,closeUsage:ut,openSystemStats:Q,closeSystemStats:ue,toggleTerminal:ye,closeTerminal:at,openFiles:X,closeFiles:Ye,setFileWorkspace:ot,openActivityLog:ht,closeActivityLog:yt,openGitManager:vt,closeGitManager:pt,openWorkflowSteps:Et,closeWorkflowSteps:It,openAgents:Bt,closeAgents:_t,openScripts:Pt,closeScripts:$t,runScript:Ht,openSetupWizard:Gt,closeSetupWizard:Dt,openModelOnboarding:Tt,closeModelOnboarding:jt,onPlanningTaskCreated:Mt,onPlanningTasksCreated:Zt,onSubtaskTasksCreated:At}}function jP(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(!1),[S,k]=a.useState({}),[A,w]=a.useState(!1),[E,C]=a.useState(!1),[z,_]=a.useState(!1),[$,F]=a.useState(!1),[V,D]=a.useState(!1),T=a.useCallback(async()=>{const[N,P]=await Promise.allSettled([qv(e),Fo(e)]);if(N.status==="fulfilled"&&(s(N.value.maxConcurrent),r(N.value.rootDir)),P.status==="fulfilled"){const R=P.value;l(!!R.autoMerge),u(!!R.globalPause),m(!!R.enginePaused),v(!!R.prAuthAvailable),g(R.taskStuckTimeoutMs),f(R.showQuickChatFAB===!0),k(R.experimentalFeatures??{});const j=R.experimentalFeatures??{};w(j.insights===!0),C(j.roadmap===!0),_(j.memoryView===!0),F(j.devServerView===!0||j.devServer===!0),D(j.todoView===!0)}y(!0)},[e]);a.useEffect(()=>{y(!1),k({}),w(!1),C(!1),_(!1),F(!1),D(!1),T()},[T]);const I=a.useCallback(async()=>{const N=!o;l(N);try{await Br({autoMerge:N},e)}catch{l(!N)}},[o,e]),U=a.useCallback(async()=>{const N=!c;u(N);try{await Br({globalPause:N,globalPauseReason:N?"manual":void 0},e)}catch{u(!N)}},[c,e]),Y=a.useCallback(async()=>{const N=!d;m(N);try{await Br({enginePaused:N},e)}catch{m(!N)}},[d,e]),ne=a.useCallback(async()=>{const N=!p;f(N);try{await Br({showQuickChatFAB:N},e)}catch{f(!N)}},[p,e]);return{maxConcurrent:n,rootDir:i,autoMerge:o,globalPaused:c,enginePaused:d,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:x,settingsLoaded:b,experimentalFeatures:S,insightsEnabled:A,roadmapEnabled:E,memoryEnabled:z,devServerEnabled:$,todosEnabled:V,toggleAutoMerge:I,toggleGlobalPause:U,toggleEnginePause:Y,toggleShowQuickChatFAB:ne,refresh:T}}function kP(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,fr(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 wP(){const[e,n]=a.useState([]),[s,i]=a.useState([]),[r,o]=a.useState([]),l=a.useRef(s),c=a.useRef(r);a.useEffect(()=>{ds().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 cn({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 cn({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 NP({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;xr().then(({providers:u})=>{const d=u.some(h=>h.authenticated);if(u.length>0&&!d||u.length>0&&d)return Ki().then(h=>{const g=!!(h.defaultProvider&&h.defaultModelId);(h.modelOnboardingComplete===!1||h.modelOnboardingComplete===void 0)&&(!d||!g)&&!Ea()?l=!0:!d&&!Ea()&&(c=!0)})}).then(()=>{if(o.current){r.current=!1;return}l?(_s("onboarding:auto-triggered",{trigger:"first-run"}),s()):c&&(_s("onboarding:auto-triggered",{trigger:"missing-provider"}),i("authentication"))}).catch(()=>{})},[e,n,s,i])}const Fh="kb-update-banner-dismissed";function SP(){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(Fh)==="true";d(h);let g=!1;return Vv().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(Fh,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:u,dismiss:m}}const CP=["board","list","agents","missions","chat","documents","roadmaps","skills","mailbox","insights","memory","devserver","dev-server","todos"];function Uh(e){return e!==null&&CP.includes(e)}function EP(e){return e==="devserver"?"dev-server":e}function _P(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=Hn("kb-dashboard-task-view");return Uh(b)?b:"board"}),f=a.useRef(!1);a.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),a.useEffect(()=>{const b=Hn("kb-dashboard-task-view",r?.id);if(Uh(b)){const y=!f.current&&b==="devserver";p(y?"devserver":EP(b))}else p("board");r?.id&&(f.current=!0)},[r?.id]),a.useEffect(()=>{ls("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 MP(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 qj(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 Vj(C.id),u(`Project ${C.name} resumed`,"success"),await o()}catch{u(`Failed to resume project ${C.name}`,"error")}},[u,o]),A=a.useCallback(async C=>{try{await pp(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]),w=a.useCallback(async C=>{try{await l(C)}catch{u("Failed to update favorites","error")}},[l,u]),E=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:A,handleToggleFavorite:w,handleToggleModelFavorite:E}}function AP(e){const{createTask:n,ingestCreatedTasks:s,onPlanningTaskCreated:i,onPlanningTasksCreated:r,onSubtaskTasksCreated:o,addToast:l}=e,c=a.useCallback(async p=>n({...p,column:"triage"}),[n]),u=a.useCallback(async p=>await n({...p,column:"triage"}),[n]),d=a.useCallback(p=>{s([p]),i(p,l)},[l,s,i]),m=a.useCallback(p=>{s(p),r(p,l)},[l,s,r]),h=a.useCallback(p=>{s(p),o(p,l)},[l,s,o]),g=a.useCallback(p=>{l(`Imported ${p.id} from GitHub`,"success")},[l]);return{handleBoardQuickCreate:c,handleModalCreate:u,handlePlanningTaskCreated:d,handlePlanningTasksCreated:m,handleSubtaskTasksCreated:h,handleGitHubImport:g}}async function RP(e){return Bo("/health",{nodeId:e})}async function TP(e){return Bo("/projects",{nodeId:e})}async function PP(e,n,s){const i=new URLSearchParams({projectId:n});return s&&s.trim()&&i.set("q",s.trim()),Bo(`/tasks?${i.toString()}`,{nodeId:e})}async function IP(e,n){return Bo(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function UD(e){return L(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function BD(e){return L(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function HD(e){return L(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function qD(e){return L(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}function $P(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=[RP(e),TP(e)];s&&(y.push(PP(e,s,i)),y.push(IP(e,s)));const S=await Promise.allSettled(y);if(b.signal.aborted)return;const k=S[0],A=S[1];if(k.status==="rejected"){p(`Failed to fetch node health: ${k.reason}`),h(!1);return}if(d(k.value),A.status==="rejected"){p(`Failed to fetch projects: ${A.reason}`),h(!1);return}if(o(A.value),s&&S[2]){const w=S[2];if(w.status==="rejected"){p(`Failed to fetch tasks: ${w.reason}`),h(!1);return}w.status==="fulfilled"&&c(w.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 DP(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 Hs(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 LP="fusion-dashboard-current-node",kg=a.createContext(null);function zP({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 Ki();if(m)return;l.current=g.dashboardCurrentNodeId;const p=g.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const f=localStorage.getItem(LP);if(f){const x=JSON.parse(f);x?.id&&x?.type==="remote"&&(l.current=x.id,await cn({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,cn({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,cn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,i]);const c=a.useCallback(m=>{s(m)},[]),u=a.useCallback(()=>{s(null),l.current=void 0,cn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),d={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:u};return t.jsx(kg.Provider,{value:d,children:e})}function OP(){const e=a.useContext(kg);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}function FP({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&&(yv(l),window.location.reload())},[n]),o=a.useCallback(()=>{jv(),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 UP=200,BP=a.lazy(()=>ln(()=>import("./AgentsView-DvN5EsoE.js").then(e=>e.A),__vite__mapDeps([17,1,18,8,19])).then(e=>({default:e.AgentsView}))),HP=a.lazy(()=>ln(()=>import("./DocumentsView-OuVpmTPp.js"),__vite__mapDeps([20,1,0,2,21])).then(e=>({default:e.DocumentsView}))),qP=a.lazy(()=>ln(()=>import("./InsightsView-DMC_bLUc.js"),__vite__mapDeps([22,1,14,0,2,23])).then(e=>({default:e.InsightsView}))),VP=a.lazy(()=>ln(()=>import("./NodesView-C_LWLFNr.js"),__vite__mapDeps([24,1,18,0,2,25])).then(e=>({default:e.NodesView}))),WP=a.lazy(()=>ln(()=>import("./ChatView-DsETFRQp.js"),__vite__mapDeps([26,1,0,2])).then(e=>({default:e.ChatView}))),KP=a.lazy(()=>ln(()=>import("./RoadmapsView-BHTePn2u.js"),__vite__mapDeps([27,1,0,2,28])).then(e=>({default:e.RoadmapsView}))),GP=a.lazy(()=>ln(()=>import("./SkillsView-CK52SRz5.js"),__vite__mapDeps([29,1,0,2,30])).then(e=>({default:e.SkillsView}))),JP=a.lazy(()=>ln(()=>import("./MemoryView-cI4IK-lz.js"),__vite__mapDeps([31,1,12,13,0,2,32])).then(e=>({default:e.MemoryView}))),YP=a.lazy(()=>ln(()=>import("./DevServerView-D1_7SL1h.js"),__vite__mapDeps([33,1,0,2,34])).then(e=>({default:e.DevServerView}))),QP=a.lazy(()=>ln(()=>import("./TodoView-BKqIV8P6.js"),__vite__mapDeps([35,1,36,0,2,37])).then(e=>({default:e.TodoView})));function XP(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{ln(()=>import("./AgentsView-DvN5EsoE.js").then(n=>n.A),__vite__mapDeps([17,1,18,8,19])),ln(()=>import("./DocumentsView-OuVpmTPp.js"),__vite__mapDeps([20,1,0,2,21])),ln(()=>import("./InsightsView-DMC_bLUc.js"),__vite__mapDeps([22,1,14,0,2,23])),ln(()=>import("./NodesView-C_LWLFNr.js"),__vite__mapDeps([24,1,18,0,2,25])),ln(()=>import("./ChatView-DsETFRQp.js"),__vite__mapDeps([26,1,0,2])),ln(()=>import("./RoadmapsView-BHTePn2u.js"),__vite__mapDeps([27,1,0,2,28])),ln(()=>import("./SkillsView-CK52SRz5.js"),__vite__mapDeps([29,1,0,2,30])),ln(()=>import("./MemoryView-cI4IK-lz.js"),__vite__mapDeps([31,1,12,13,0,2,32])),ln(()=>import("./DevServerView-D1_7SL1h.js"),__vite__mapDeps([33,1,0,2,34])),ln(()=>import("./TodoView-BKqIV8P6.js"),__vite__mapDeps([35,1,36,0,2,37]))})}const gc="kb-setup-warning-dismissed";function ZP(){const{toasts:e,addToast:n,removeToast:s}=pP(),i=typeof window<"u"&&!!window.electronAPI;a.useEffect(()=>{XP()},[]);const{projects:r,loading:o,error:l,refresh:c}=cP(),{nodes:u}=Vo(),{currentNode:d,currentNodeId:m,isRemote:h,setCurrentNode:g,clearCurrentNode:p}=OP(),{currentProject:f,setCurrentProject:x,clearCurrentProject:v,loading:b}=mP(r,{nodeId:m}),{hasAiProvider:y,hasGithub:S,loading:k,hasWarnings:A}=lg(f?.id),{updateAvailable:w,latestVersion:E,currentVersion:C,dismissed:z,dismiss:_}=SP();a.useEffect(()=>{if(m&&!d&&u.length>0){const q=u.find(je=>je.id===m);if(q){g(q);return}}m&&u.length>0&&(u.some(je=>je.id===m)||p())},[m,d,u,g,p]);const[$,F]=a.useState(""),V=$P(m,{projectId:f?.id,searchQuery:$||void 0});DP(m);const D=h&&V.projects.length>0?V.projects:r,{themeMode:T,colorTheme:I,setThemeMode:U,setColorTheme:Y}=vP(),{sessions:ne,generating:N,needsInput:P,planningSessions:R,dismissSession:j}=aP(f?.id),W=ne.filter(q=>q.status==="awaiting_input"||q.status==="error"),K=yP({projectId:f?.id,planningSessions:R}),{viewMode:ke,setViewMode:be,taskView:ce,handleChangeTaskView:ve}=_P({projectsLoading:o,projectsError:l,currentProjectLoading:b,currentProject:f,projectsLength:r.length,setupWizardOpen:K.setupWizardOpen,openSetupWizard:K.openSetupWizard,themeMode:T,setThemeMode:U}),O=a.useCallback(q=>{q==="missions"&&(ye(void 0),X(void 0),ot(void 0)),ve(q)},[ve]),oe=ce==="board"||ce==="list",{tasks:te,createTask:pe,moveTask:de,pauseTask:ge,deleteTask:ie,mergeTask:Ee,retryTask:Le,updateTask:qe,duplicateTask:et,archiveTask:Xe,unarchiveTask:Ze,archiveAllDone:it,loadArchivedTasks:Ie,ingestCreatedTasks:Ke,lastFetchTimeMs:re}=rP({...f?{projectId:f.id}:{},searchQuery:$||void 0,sseEnabled:oe}),[xe,se]=a.useState(!1),Ae=a.useRef(performance.now()),ze=a.useRef(!1),me=a.useRef(!1),_e=a.useMemo(()=>o?"projects":b?"project":"tasks",[o,b]);a.useEffect(()=>{if(!o&&!ze.current){ze.current=!0;const q=`projects loaded at ${Math.round(performance.now()-Ae.current)}ms from mount`;console.log(`[App] ${q}`),lr("[App]",q)}if(!b&&!me.current){me.current=!0;const q=`current-project resolved at ${Math.round(performance.now()-Ae.current)}ms from mount`;console.log(`[App] ${q}`),lr("[App]",q)}},[o,b]),a.useEffect(()=>{if(xe||o||b)return;const q=performance.now(),je=window.setTimeout(()=>{const Je=`dashboard ready at ${Math.round(performance.now()-Ae.current)}ms from mount (settle delay=${Math.round(performance.now()-q)}ms)`;console.log(`[App] ${Je}`),lr("[App]",Je),se(!0)},UP);return()=>{window.clearTimeout(je)}},[xe,o,b]);const nt=Pr()==="mobile",{keyboardOverlap:we}=gg({enabled:nt}),le=nt&&we>0,[Te,he]=a.useState(0),Me=a.useCallback(()=>{vp(f?.id).then(q=>{he(q.unreadCount)}).catch(q=>{console.warn("[App] Failed to fetch mailbox unread count:",q)})},[f?.id]);a.useEffect(()=>{Me();const q=new URLSearchParams;f?.id&&q.set("projectId",f.id);const je=q.size>0?`?${q.toString()}`:"";return Hs(`/api/events${je}`,{events:{"message:sent":Me,"message:received":Me,"message:read":Me,"message:deleted":Me}})},[f?.id,Me]);const[We,Re]=a.useState(!1),[ut,Q]=a.useState(!1),[ue,ye]=a.useState(void 0),[at,X]=a.useState(void 0),[Ye,ot]=a.useState(void 0),[ht,yt]=a.useState(!1),[vt,pt]=a.useState(!1),[Et,It]=a.useState(()=>Hn(gc,f?.id)==="true");a.useEffect(()=>{It(Hn(gc,f?.id)==="true")},[f?.id]),a.useEffect(()=>{const q=()=>{pt(!0)};return window.addEventListener(Mc,q),()=>{window.removeEventListener(Mc,q)}},[]);const Bt=a.useCallback(()=>{ls(gc,"true",f?.id),It(!0)},[f?.id]),{maxConcurrent:_t,autoMerge:Pt,globalPaused:$t,enginePaused:Ht,taskStuckTimeoutMs:Gt,showQuickChatFAB:Dt,prAuthAvailable:Tt,settingsLoaded:jt,experimentalFeatures:Mt,insightsEnabled:Zt,roadmapEnabled:At,memoryEnabled:H,devServerEnabled:fe,todosEnabled:$e,toggleAutoMerge:M,toggleGlobalPause:ee,toggleEnginePause:Oe,refresh:dt}=jP(f?.id),Nt=Mt.skillsView===!0,Ct=Mt.nodesView===!0,Rt=!0;a.useEffect(()=>{jt&&(ce==="skills"&&!Nt&&ve("board"),ce==="insights"&&!Zt&&ve("board"),ce==="roadmaps"&&!At&&ve("board"),ce==="memory"&&!H&&ve("board"),(ce==="devserver"||ce==="dev-server")&&!fe&&ve("board"),ce==="todos"&&!$e&&ve("board"))},[ce,jt,Nt,Zt,At,ve,Rt,H,fe,$e]),a.useEffect(()=>{We&&!Ct&&Re(!1)},[We,Ct]);const{availableModels:un,favoriteProviders:mn,favoriteModels:Nn,toggleFavoriteProvider:Qt,toggleFavoriteModel:An}=wP();NP({projectId:f?.id,setupWizardOpen:K.setupWizardOpen,openModelOnboarding:K.openModelOnboarding,openSettings:K.openSettings});const{handleSelectProject:Ne,handleViewAllProjects:ae,handleOpenSettings:Ge,handleAddProject:ct,handleSetupComplete:Lt,handleModelOnboardingComplete:qt,handlePauseProject:En,handleResumeProject:hn,handleRemoveProject:Vt,handleToggleFavorite:J,handleToggleModelFavorite:Pe}=MP({setCurrentProject:x,clearCurrentProject:v,setViewMode:be,currentProject:f,refreshProjects:c,toggleFavoriteProvider:Qt,toggleFavoriteModel:An,addToast:n,openSettings:K.openSettings,openSetupWizard:K.openSetupWizard,closeSetupWizard:K.closeSetupWizard,closeModelOnboarding:K.closeModelOnboarding}),{handleDetailClose:Qe}=kP({projectId:f?.id,projects:r,projectsLoading:o,currentProject:f,setCurrentProject:x,addToast:n,openTaskDetail:K.openDetailTask,closeTaskDetail:K.closeDetailTask}),{handleBoardQuickCreate:tt,handleModalCreate:mt,handlePlanningTaskCreated:St,handlePlanningTasksCreated:zt,handleSubtaskTasksCreated:Sn,handleGitHubImport:an}=AP({createTask:pe,ingestCreatedTasks:Ke,onPlanningTaskCreated:K.onPlanningTaskCreated,onPlanningTasksCreated:K.onPlanningTasksCreated,onSubtaskTasksCreated:K.onSubtaskTasksCreated,addToast:n}),kt=a.useCallback((q,je)=>{if(je==="changes"){K.openDetailWithChangesTab(q);return}K.openDetailTask(q,je)},[K]),as=a.useCallback(async q=>{try{const je=await fr(q,f?.id);K.openDetailTask(je,"logs")}catch(je){n(`Failed to open task logs: ${je.message}`,"error")}},[K,f?.id,n]),js=a.useCallback(()=>{Ct&&Re(q=>!q)},[Ct]),Ps=a.useCallback(()=>{K.setFileWorkspace("project"),K.openFiles()},[K]),Is=a.useCallback(async()=>{Q(!0);try{await c()}finally{Q(!1)}},[c]),si=a.useCallback(q=>{X(q),ye(void 0),ve("missions")},[ve]),ks=a.useCallback(q=>{q.type==="planning"?K.openPlanningWithSession(q.id):q.type==="subtask"?K.openSubtaskWithSession(q.id):q.type==="mission_interview"?(X(void 0),ye(q.id),ot(void 0),ve("missions")):(q.type==="milestone_interview"||q.type==="slice_interview")&&(ye(void 0),X(void 0),ot(q.id),ve("missions"))},[ve,K]),$s=a.useCallback(()=>{},[]),Yi=a.useCallback(()=>{},[]),gi=!o&&!b&&r.length===0&&!f&&!!l,ii=()=>gi?t.jsx(p4,{errorMessage:l??"Failed to fetch projects",isRetrying:ut,onRetry:Is}):We?t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(es,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(VP,{addToast:n,onClose:()=>Re(!1)})})})}):ke==="overview"?t.jsx(es,{children:t.jsx(XN,{projects:r,loading:o,onSelectProject:Ne,onAddProject:ct,onPauseProject:En,onResumeProject:hn,onRemoveProject:Vt,nodes:u})}):ce==="skills"?!jt||!Nt?null:t.jsx(es,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(GP,{addToast:n,projectId:f?.id,onClose:()=>ve("board")})})}):ce==="chat"?t.jsx(es,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(WP,{addToast:n,projectId:f?.id})})}):ce==="mailbox"?t.jsx(es,{children:t.jsx(q1,{projectId:f?.id,addToast:n,onUnreadCountChange:he})}):ce==="roadmaps"?!jt||!At?null:t.jsx(es,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(KP,{addToast:n,projectId:f?.id})})}):ce==="missions"?t.jsx(es,{children:t.jsx(F1,{isInline:!0,isOpen:!0,onClose:()=>{X(void 0),ye(void 0),ot(void 0),ve("board")},addToast:n,projectId:f?.id,onSelectTask:q=>{const je=te.find(Je=>Je.id===q);je&&K.openDetailTask(je)},availableTasks:te.map(q=>({id:q.id,title:q.title})),resumeSessionId:ue,targetMissionId:at,milestoneSliceResumeSessionId:Ye,onMilestoneSliceResumeFetchError:()=>ot(void 0)})}):ce==="agents"&&Rt?t.jsx(es,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(BP,{addToast:n,projectId:f?.id,onOpenTaskLogs:as})})}):ce==="documents"?t.jsx(es,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(HP,{projectId:f?.id,addToast:n,onOpenDetail:K.openDetailTask})})}):ce==="insights"?!jt||!Zt?null:t.jsx(es,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(qP,{projectId:f?.id,addToast:n,onClose:()=>ve("board")})})}):ce==="memory"?!jt||!H?null:t.jsx(es,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(JP,{addToast:n,projectId:f?.id})})}):ce==="todos"?!jt||!$e?null:t.jsx(es,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(QP,{addToast:n,projectId:f?.id})})}):ce==="devserver"||ce==="dev-server"?!jt||!fe?null:t.jsx(es,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(YP,{addToast:n,projectId:f?.id})})}):ce==="board"?t.jsx(es,{children:t.jsx(zN,{tasks:h&&V.tasks.length>0?V.tasks:te,projectId:f?.id,maxConcurrent:_t,onMoveTask:de,onPauseTask:ge,onOpenDetail:K.openDetailTask,addToast:n,onQuickCreate:tt,onNewTask:K.openNewTask,onPlanningMode:K.openPlanningWithInitialPlan,onSubtaskBreakdown:K.openSubtaskBreakdown,autoMerge:Pt,onToggleAutoMerge:M,globalPaused:$t,onUpdateTask:qe,onRetryTask:Le,onArchiveTask:Xe,onUnarchiveTask:Ze,onDeleteTask:ie,onArchiveAllDone:it,onLoadArchivedTasks:Ie,searchQuery:$,availableModels:un,onOpenDetailWithTab:kt,favoriteProviders:mn,favoriteModels:Nn,onToggleFavorite:J,onToggleModelFavorite:Pe,taskStuckTimeoutMs:Gt,onOpenMission:si,lastFetchTimeMs:re})}):t.jsx(es,{children:t.jsx(BN,{tasks:h&&V.tasks.length>0?V.tasks:te,projectId:f?.id,onMoveTask:de,onRetryTask:Le,onOpenDetail:K.openDetailTask,addToast:n,globalPaused:$t,onNewTask:K.openNewTask,onQuickCreate:tt,onPlanningMode:K.openPlanningWithInitialPlan,onSubtaskBreakdown:K.openSubtaskBreakdown,availableModels:un,favoriteProviders:mn,favoriteModels:Nn,onToggleFavorite:J,onToggleModelFavorite:Pe,taskStuckTimeoutMs:Gt,searchQuery:$,lastFetchTimeMs:re})});if(!xe)return t.jsxs(t.Fragment,{children:[t.jsx(g4,{stage:_e}),t.jsx(pg,{toasts:e,onRemove:s})]});const ms=!K.modelOnboardingOpen&&OT(),qs=!K.modelOnboardingOpen&&!ms&&Ea()&&!dg();return t.jsxs(t.Fragment,{children:[t.jsx(hw,{isElectron:i,onOpenSettings:Ge,onOpenGitHubImport:K.openGitHubImport,onOpenPlanning:K.openPlanning,onResumePlanning:K.resumePlanning,activePlanningSessionCount:R.length,onOpenUsage:K.openUsage,onOpenActivityLog:K.openActivityLog,onOpenSystemStats:K.openSystemStats,onOpenMailbox:()=>O("mailbox"),mailboxUnreadCount:Te,onOpenSchedules:K.openSchedules,onOpenGitManager:K.openGitManager,onOpenNodes:js,showNodesButton:Ct,onOpenWorkflowSteps:K.openWorkflowSteps,onOpenScripts:K.openScripts,onRunScript:K.runScript,onToggleTerminal:K.toggleTerminal,onOpenFiles:K.openFiles,filesOpen:K.filesOpen,globalPaused:$t,enginePaused:Ht,onToggleGlobalPause:ee,onToggleEnginePause:Oe,view:ce,onChangeView:ke==="project"&&f?O:void 0,showSkillsTab:Nt,showAgentsTab:Rt,searchQuery:$,onSearchChange:F,projects:D,currentProject:f,onSelectProject:Ne,onViewAllProjects:ae,projectId:f?.id,mobileNavEnabled:nt,availableNodes:u,currentNode:d,onSelectNode:q=>{q===null?p():g(q)},isRemote:h,experimentalFeatures:{insights:Zt,roadmap:At,memoryView:H,devServer:fe,devServerView:fe,todoView:$e}}),ke==="project"&&f&&!We&&ce!=="missions"&&!K.isPlanningOpen&&t.jsx(M4,{sessions:W,onResumeSession:ks,onDismissSession:$s,onDismissAll:Yi}),ke==="project"&&f&&ms&&t.jsx(R4,{onResume:K.openModelOnboarding}),ke==="project"&&f&&qs&&t.jsx(T4,{onOpenModelOnboarding:K.openModelOnboarding,onOpenSettings:q=>K.openSettings(q)}),ke==="project"&&f&&w&&E&&C&&!z&&t.jsx(A4,{latestVersion:E,currentVersion:C,onDismiss:_}),ke==="project"&&f&&!k&&A&&!Et&&t.jsx(cg,{hasAiProvider:y,hasGithub:S,onDismiss:Bt}),t.jsx("div",{className:`project-content${ke==="project"&&f?" project-content--with-footer":""}${nt&&!le?" project-content--with-mobile-nav":""}`,children:ii()}),ke==="project"&&f&&!We&&t.jsx(C4,{tasks:h&&V.tasks.length>0?V.tasks:te,projectId:f.id,taskStuckTimeoutMs:Gt,backgroundSessions:ne,backgroundGenerating:N,backgroundNeedsInput:P,onOpenBackgroundSession:ks,onDismissBackgroundSession:j,lastFetchTimeMs:re,currentProjectPath:f.path,onOpenProjectDirectory:Ps}),t.jsx(I4,{view:ce,onChangeView:ke==="project"&&f?O:()=>{},footerVisible:ke==="project"&&!!f,modalOpen:K.anyModalOpen,keyboardOpen:le,onOpenSettings:Ge,onOpenActivityLog:K.openActivityLog,onOpenSystemStats:K.openSystemStats,onOpenMailbox:()=>O("mailbox"),mailboxUnreadCount:Te,onOpenGitManager:K.openGitManager,onOpenWorkflowSteps:K.openWorkflowSteps,onOpenSchedules:K.openSchedules,onOpenScripts:K.openScripts,onToggleTerminal:K.toggleTerminal,onOpenFiles:K.openFiles,onOpenGitHubImport:K.openGitHubImport,onOpenPlanning:K.openPlanning,onResumePlanning:K.resumePlanning,activePlanningSessionCount:R.length,onOpenUsage:()=>K.openUsage(null),onViewAllProjects:ae,onRunScript:K.runScript,projectId:f?.id,showSkillsTab:Nt,experimentalFeatures:{insights:Zt,roadmap:At,memoryView:H,devServer:fe,devServerView:fe,todoView:$e}}),ke==="project"&&f&&ce!=="chat"&&ce!=="mailbox"&&ce!=="insights"&&ce!=="devserver"&&ce!=="dev-server"&&t.jsx(iP,{projectId:f.id,addToast:n,showFAB:Dt,open:ht,onOpenChange:yt,favoriteProviders:mn,favoriteModels:Nn,onToggleFavorite:J,onToggleModelFavorite:Pe}),t.jsx(h4,{projectId:f?.id,tasks:te,projects:r,currentProject:f,addToast:n,toasts:e,removeToast:s,modalManager:K,projectActions:{handleAddProject:ct,handleSetupComplete:Lt,handleModelOnboardingComplete:qt},taskHandlers:{handleModalCreate:mt,handlePlanningTaskCreated:St,handlePlanningTasksCreated:zt,handleSubtaskTasksCreated:Sn,handleGitHubImport:an},taskOperations:{moveTask:de,deleteTask:ie,mergeTask:Ee,retryTask:Le,duplicateTask:et},deepLink:{handleDetailClose:Qe},settings:{prAuthAvailable:Tt,themeMode:T,colorTheme:I,setThemeMode:U,setColorTheme:Y},onSettingsClose:()=>{K.closeSettings(),dt()},onReopenOnboarding:()=>{K.closeSettings(),K.openModelOnboarding()}}),t.jsx(FP,{open:vt})]})}function eI(){return t.jsx(hP,{children:t.jsx(zP,{children:t.jsx(Ew,{children:t.jsx(ZP,{})})})})}_v();hv();wg.createRoot(document.getElementById("root")).render(t.jsx(a.StrictMode,{children:t.jsx(pv,{children:t.jsx(eI,{})})}));"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{Ij as $,Rs as A,kn as B,vn as C,sn as D,go as E,Ui as F,$o as G,FD as H,bn as I,lc as J,wn as K,rt as L,Fs as M,nn as N,Yt as O,Dn as P,MT as Q,Mn as R,ma as S,nd as T,Tj as U,kT as V,wT as W,Kt as X,Pj as Y,Fn as Z,g$ as _,ls as a,B$ as a$,ln as a0,zI as a1,OI as a2,Uy as a3,yc as a4,fa as a5,_a as a6,hi as a7,pi as a8,ui as a9,yr as aA,tw as aB,ED as aC,_D as aD,nw as aE,sw as aF,U4 as aG,Pr as aH,gg as aI,Gh as aJ,Po as aK,Xh as aL,$4 as aM,O4 as aN,gs as aO,Li as aP,ji as aQ,Fd as aR,P$ as aS,$$ as aT,I$ as aU,D$ as aV,L$ as aW,z$ as aX,O$ as aY,F$ as aZ,U$ as a_,MD as aa,TD as ab,RD as ac,AD as ad,PD as ae,Qn as af,ss as ag,ev as ah,Zs as ai,bx as aj,To as ak,wi as al,HD as am,UD as an,BD as ao,qD as ap,pr as aq,Hb as ar,or as as,hx as at,ts as au,ep as av,Vo as aw,cP as ax,CD as ay,cu as az,S$ as b,UI as b$,H$ as b0,q$ as b1,V$ as b2,W$ as b3,G$ as b4,J$ as b5,K$ as b6,$n as b7,td as b8,Fi as b9,dj as bA,a$ as bB,id as bC,oj as bD,lj as bE,cj as bF,rj as bG,QI as bH,Er as bI,zo as bJ,Ub as bK,hr as bL,Ib as bM,Q$ as bN,X$ as bO,Z$ as bP,eD as bQ,tD as bR,nD as bS,sD as bT,Y$ as bU,ap as bV,ba as bW,Fj as bX,yv as bY,jv as bZ,bD as b_,ND as ba,wD as bb,SD as bc,bI as bd,xI as be,gI as bf,vI as bg,_I as bh,MI as bi,SI as bj,kI as bk,wI as bl,NI as bm,jI as bn,yI as bo,fI as bp,CI as bq,uR as br,e$ as bs,ZI as bt,r$ as bu,XI as bv,t$ as bw,n$ as bx,s$ as by,i$ as bz,Ue as c,lD as c$,FI as c0,vD as c1,BI as c2,YI as c3,KI as c4,HI as c5,GI as c6,qI as c7,JI as c8,VI as c9,DD as cA,T$ as cB,lI as cC,bc as cD,Un as cE,cR as cF,RT as cG,cc as cH,Ho as cI,dI as cJ,rI as cK,cI as cL,uI as cM,mI as cN,qi as cO,yw as cP,qo as cQ,LD as cR,Qm as cS,zD as cT,OD as cU,EI as cV,iD as cW,rD as cX,cD as cY,oD as cZ,aD as c_,WI as ca,zg as cb,ti as cc,QA as cd,AI as ce,R$ as cf,sI as cg,iI as ch,xr as ci,C$ as cj,aI as ck,oI as cl,pI as cm,hI as cn,py as co,ay as cp,ei as cq,ry as cr,oy as cs,ly as ct,PI as cu,E$ as cv,_$ as cw,M$ as cx,Si as cy,$D as cz,w$ as d,dD as d0,hp as d1,Vd as d2,Gx as d3,uD as d4,b$ as d5,h$ as d6,f$ as d7,p$ as d8,j$ as d9,RI as dA,TI as dB,DI as dC,LI as dD,$I as dE,y$ as da,Kh as db,u$ as dc,d$ as dd,jT as de,x$ as df,Sr as dg,vM as dh,l$ as di,o$ as dj,By as dk,c$ as dl,m$ as dm,mD as dn,hD as dp,Tb as dq,Sc as dr,yD as ds,gD as dt,fD as du,xD as dv,pD as dw,A$ as dx,ID as dy,II as dz,N$ as e,fr as f,Hn as g,kD as h,ds as i,Ma as j,jD as k,Bn as l,Rj as m,k$ as n,z4 as o,Bs as p,Fo as q,NT as r,Hs as s,Br as t,cn as u,Se as v,Nw as w,v$ as x,wc as y,Xs as z};
|